-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParser.php
More file actions
557 lines (502 loc) · 17.9 KB
/
Parser.php
File metadata and controls
557 lines (502 loc) · 17.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
<?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 6.0.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\AttributeResolver;
use Cake\AttributeResolver\Enum\AttributeTargetType;
use Cake\AttributeResolver\ValueObject\AttributeInfo;
use Cake\AttributeResolver\ValueObject\AttributeTarget;
use Generator;
use PhpToken;
use ReflectionAttribute;
use ReflectionClass;
use ReflectionClassConstant;
use ReflectionMethod;
use ReflectionParameter;
use ReflectionProperty;
use SplFileInfo;
use Throwable;
class Parser
{
/**
* Cache for attribute constructor reflections.
*
* @var array<string, \ReflectionMethod|null>
*/
private array $constructorCache = [];
/**
* @param array<string> $excludeAttributes
*/
public function __construct(
protected array $excludeAttributes = [],
) {
}
/**
* Parse a PHP file and extract all attributes.
*
* @param \SplFileInfo $file File object to parse
* @param string|null $pluginName Plugin name if file belongs to a plugin
* @return \Generator<\Cake\AttributeResolver\ValueObject\AttributeInfo>
*/
public function parseFile(SplFileInfo $file, ?string $pluginName = null): Generator
{
$realFilePath = $file->getRealPath();
if ($realFilePath === false) {
return;
}
try {
$fileTime = $file->getMTime();
$classes = $this->getClassesFromFile($realFilePath);
foreach ($classes as $className) {
try {
if (!$this->isTypeLoaded($className)) {
continue;
}
assert(
class_exists($className) || interface_exists($className) ||
trait_exists($className) || enum_exists($className),
);
$reflection = new ReflectionClass($className);
// Skip classes not from this file
$reflectionFile = $reflection->getFileName();
if ($reflectionFile === false || realpath($reflectionFile) !== $realFilePath) {
continue;
}
yield from $this->parseClass($reflection, $realFilePath, $fileTime, $pluginName);
} catch (Throwable) {
// Skip classes that fail reflection
}
}
} catch (Throwable) {
// Skip files that fail parsing
}
}
/**
* Extract class names from a PHP file.
*
* Uses token parsing to safely detect classes, interfaces, traits, and enums.
* Then loads them either via autoloader or direct file inclusion.
*
* @param string $filePath File path (should be normalized with realpath)
* @return array<string>
*/
protected function getClassesFromFile(string $filePath): array
{
$classNames = $this->getClassNamesFromTokens($filePath);
// Try to load classes via autoloader (PSR-4 compliant only)
foreach ($classNames as $className) {
if ($this->isTypeLoaded($className)) {
continue;
}
$this->loadType($className);
}
return $classNames;
}
/**
* Extract class name from PHP file using token parsing.
*
* Leverages PSR-4 constraint: one class per file. Returns immediately
* when the first class/interface/trait/enum is found.
*
* @param string $filePath File path to parse
* @return array<string> Fully qualified class name (single element array)
*/
protected function getClassNamesFromTokens(string $filePath): array
{
$code = file_get_contents($filePath);
if ($code === false) {
return [];
}
$tokens = PhpToken::tokenize($code);
$namespace = '';
$waitingForNamespace = false;
$waitingForClass = false;
foreach ($tokens as $i => $token) {
// Detect namespace declaration
if ($token->id === T_NAMESPACE) {
$waitingForNamespace = true;
continue;
}
// Capture namespace name
if ($waitingForNamespace && ($token->id === T_NAME_QUALIFIED || $token->id === T_STRING)) {
$namespace = $token->text;
$waitingForNamespace = false;
continue;
}
// Detect class/interface/trait/enum declaration
if (in_array($token->id, [T_CLASS, T_INTERFACE, T_TRAIT, T_ENUM], true)) {
// Skip anonymous classes
if ($token->id === T_CLASS && $this->isAnonymousClass($tokens, $i)) {
continue;
}
$waitingForClass = true;
continue;
}
// Capture class name and return immediately (PSR-4: one class per file)
if ($waitingForClass && $token->id === T_STRING) {
$className = $token->text;
$fullyQualifiedName = $namespace !== '' ? $namespace . '\\' . $className : $className;
return [$fullyQualifiedName];
}
}
return [];
}
/**
* Check if T_CLASS token represents an anonymous class.
*
* Anonymous classes are preceded by the 'new' keyword.
*
* @param array<\PhpToken> $tokens All tokens from PhpToken::tokenize()
* @param int $currentIndex Current token index
* @return bool True if anonymous class
*/
protected function isAnonymousClass(array $tokens, int $currentIndex): bool
{
// Look backward for 'new' keyword (skip whitespace/comments)
for ($i = $currentIndex - 1; $i >= 0; $i--) {
$token = $tokens[$i];
if ($token->id === T_NEW) {
return true;
}
if (!in_array($token->id, [T_WHITESPACE, T_COMMENT, T_DOC_COMMENT], true)) {
return false;
}
}
return false;
}
/**
* Check if a type (class/interface/trait/enum) is already loaded.
*
* @param string $typeName Type name to check
* @return bool True if type is loaded
*/
protected function isTypeLoaded(string $typeName): bool
{
return class_exists($typeName, false)
|| interface_exists($typeName, false)
|| trait_exists($typeName, false)
|| enum_exists($typeName, false);
}
/**
* Try to load a type via autoloader.
*
* @param string $typeName Type name to load
* @return bool True if type was loaded
*/
protected function loadType(string $typeName): bool
{
return class_exists($typeName)
|| interface_exists($typeName)
|| trait_exists($typeName)
|| enum_exists($typeName);
}
/**
* Parse attributes from a class and its members.
*
* @param \ReflectionClass<object> $reflection Class reflection
* @param string $filePath File path
* @param int $fileTime File modification time
* @param string|null $pluginName Plugin name
* @return \Generator<\Cake\AttributeResolver\ValueObject\AttributeInfo>
*/
protected function parseClass(
ReflectionClass $reflection,
string $filePath,
int $fileTime,
?string $pluginName,
): Generator {
$className = $reflection->getName();
$startLine = $reflection->getStartLine();
// Parse class-level attributes
yield from $this->parseAttributes(
$reflection->getAttributes(),
$className,
$filePath,
$startLine === false ? 0 : $startLine,
$fileTime,
new AttributeTarget(AttributeTargetType::CLASS_TYPE, $className),
$pluginName,
);
// Parse method attributes
foreach ($reflection->getMethods() as $method) {
yield from $this->parseMethod($method, $filePath, $fileTime, $className, $pluginName);
}
// Parse property attributes
foreach ($reflection->getProperties() as $property) {
yield from $this->parseProperty($property, $filePath, $fileTime, $className, $pluginName);
}
// Parse constant attributes
foreach ($reflection->getReflectionConstants() as $constant) {
yield from $this->parseConstant($constant, $filePath, $fileTime, $className, $pluginName);
}
}
/**
* Parse method attributes.
*
* @param \ReflectionMethod $method Method reflection
* @param string $filePath File path
* @param int $fileTime File modification time
* @param string $className Declaring class name
* @param string|null $pluginName Plugin name
* @return \Generator<\Cake\AttributeResolver\ValueObject\AttributeInfo>
*/
protected function parseMethod(
ReflectionMethod $method,
string $filePath,
int $fileTime,
string $className,
?string $pluginName,
): Generator {
$startLine = $method->getStartLine();
$target = new AttributeTarget(
AttributeTargetType::METHOD,
$method->getName(),
$className,
);
yield from $this->parseAttributes(
$method->getAttributes(),
$className,
$filePath,
$startLine === false ? 0 : $startLine,
$fileTime,
$target,
$pluginName,
);
foreach ($method->getParameters() as $parameter) {
yield from $this->parseParameter(
$parameter,
$filePath,
$fileTime,
$className,
$method->getName(),
$pluginName,
);
}
}
/**
* Parse property attributes.
*
* @param \ReflectionProperty $property Property reflection
* @param string $filePath File path
* @param int $fileTime File modification time
* @param string $className Declaring class name
* @param string|null $pluginName Plugin name
* @return \Generator<\Cake\AttributeResolver\ValueObject\AttributeInfo>
*/
protected function parseProperty(
ReflectionProperty $property,
string $filePath,
int $fileTime,
string $className,
?string $pluginName,
): Generator {
$target = new AttributeTarget(
AttributeTargetType::PROPERTY,
$property->getName(),
$className,
);
yield from $this->parseAttributes(
$property->getAttributes(),
$className,
$filePath,
0, // Properties don't have reliable line numbers
$fileTime,
$target,
$pluginName,
);
}
/**
* Parse parameter attributes.
*
* @param \ReflectionParameter $parameter Parameter reflection
* @param string $filePath File path
* @param int $fileTime File modification time
* @param string $className Declaring class name
* @param string $methodName Method name
* @param string|null $pluginName Plugin name
* @return \Generator<\Cake\AttributeResolver\ValueObject\AttributeInfo>
*/
protected function parseParameter(
ReflectionParameter $parameter,
string $filePath,
int $fileTime,
string $className,
string $methodName,
?string $pluginName,
): Generator {
$declaringFunction = $parameter->getDeclaringFunction();
$startLine = $declaringFunction instanceof ReflectionMethod ? $declaringFunction->getStartLine() : false;
$target = new AttributeTarget(
AttributeTargetType::PARAMETER,
$parameter->getName(),
$className . '::' . $methodName,
);
yield from $this->parseAttributes(
$parameter->getAttributes(),
$className,
$filePath,
$startLine === false ? 0 : $startLine,
$fileTime,
$target,
$pluginName,
);
}
/**
* Parse class constant attributes.
*
* @param \ReflectionClassConstant $constant Constant reflection
* @param string $filePath File path
* @param int $fileTime File modification time
* @param string $className Declaring class name
* @param string|null $pluginName Plugin name
* @return \Generator<\Cake\AttributeResolver\ValueObject\AttributeInfo>
*/
protected function parseConstant(
ReflectionClassConstant $constant,
string $filePath,
int $fileTime,
string $className,
?string $pluginName,
): Generator {
$target = new AttributeTarget(
AttributeTargetType::CONSTANT,
$constant->getName(),
$className,
);
yield from $this->parseAttributes(
$constant->getAttributes(),
$className,
$filePath,
0, // Constants don't have reliable line numbers
$fileTime,
$target,
$pluginName,
);
}
/**
* Parse reflection attributes and convert to AttributeInfo.
*
* @param array<\ReflectionAttribute<object>> $attributes Reflection attributes
* @param string $className Class name
* @param string $filePath File path
* @param int $lineNumber Line number
* @param int $fileTime File modification time
* @param \Cake\AttributeResolver\ValueObject\AttributeTarget $target Attribute target
* @param string|null $pluginName Plugin name
* @return \Generator<\Cake\AttributeResolver\ValueObject\AttributeInfo>
*/
protected function parseAttributes(
array $attributes,
string $className,
string $filePath,
int $lineNumber,
int $fileTime,
AttributeTarget $target,
?string $pluginName,
): Generator {
foreach ($attributes as $attribute) {
$attributeName = ltrim($attribute->getName(), '\\');
if ($this->shouldExclude($attributeName)) {
continue;
}
yield new AttributeInfo(
className: $className,
attributeName: $attributeName,
arguments: $this->extractAttributeArguments($attribute),
filePath: $filePath,
lineNumber: $lineNumber,
target: $target,
fileTime: $fileTime,
pluginName: $pluginName,
);
}
}
/**
* Extract named arguments from a reflection attribute.
*
* @param \ReflectionAttribute<object> $attribute Reflection attribute
* @return array<string, mixed> Named arguments array
*/
protected function extractAttributeArguments(ReflectionAttribute $attribute): array
{
try {
$rawArgs = $attribute->getArguments();
$constructor = $this->getAttributeConstructor($attribute->getName());
if (!$constructor instanceof ReflectionMethod) {
return $rawArgs;
}
$parameters = $constructor->getParameters();
$namedArgs = [];
// Map arguments to parameter names
foreach ($rawArgs as $index => $value) {
if (is_string($index)) {
// Already a named argument
$namedArgs[$index] = $value;
} elseif (isset($parameters[$index])) {
// Positional argument - map to parameter name
$namedArgs[$parameters[$index]->getName()] = $value;
}
}
return $namedArgs;
} catch (Throwable) {
// Fallback to raw arguments
return $attribute->getArguments();
}
}
/**
* Get the constructor for an attribute class (cached).
*
* @param string $attributeName Attribute class name
* @return \ReflectionMethod|null Constructor or null if none exists
*/
protected function getAttributeConstructor(string $attributeName): ?ReflectionMethod
{
if (!array_key_exists($attributeName, $this->constructorCache)) {
try {
if (!class_exists($attributeName)) {
$this->constructorCache[$attributeName] = null;
return null;
}
$attributeClass = new ReflectionClass($attributeName);
$this->constructorCache[$attributeName] = $attributeClass->getConstructor();
} catch (Throwable) {
$this->constructorCache[$attributeName] = null;
}
}
return $this->constructorCache[$attributeName];
}
/**
* Check if an attribute should be excluded.
*
* @param string $attributeName Attribute name
* @return bool True if should be excluded
*/
protected function shouldExclude(string $attributeName): bool
{
return array_any($this->excludeAttributes, function (string $pattern) use ($attributeName): bool {
// Exact match
if ($pattern === $attributeName) {
return true;
}
// Wildcard prefix match: "App\Internal\*" or "App\Attribute*" matches with prefix
if (str_ends_with($pattern, '*')) {
$prefix = substr($pattern, 0, -1); // Remove "*"
if (str_starts_with($attributeName, $prefix)) {
return true;
}
}
return false;
});
}
}