Debian Codegraph @

lib/3rdParty/composer/symfony/property-info/Extractor/ReflectionExtractor.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\PropertyInfo\Extractor;
13
14 use Symfony\Component\PropertyInfo\PropertyAccessExtractorInterface;
15 use Symfony\Component\PropertyInfo\PropertyInitializableExtractorInterface;
16 use Symfony\Component\PropertyInfo\PropertyListExtractorInterface;
17 use Symfony\Component\PropertyInfo\PropertyReadInfo;
18 use Symfony\Component\PropertyInfo\PropertyReadInfoExtractorInterface;
19 use Symfony\Component\PropertyInfo\PropertyTypeExtractorInterface;
20 use Symfony\Component\PropertyInfo\PropertyWriteInfo;
21 use Symfony\Component\PropertyInfo\PropertyWriteInfoExtractorInterface;
22 use Symfony\Component\PropertyInfo\Type as LegacyType;
23 use Symfony\Component\String\Inflector\EnglishInflector;
24 use Symfony\Component\String\Inflector\InflectorInterface;
25 use Symfony\Component\TypeInfo\Exception\UnsupportedException;
26 use Symfony\Component\TypeInfo\Type;
27 use Symfony\Component\TypeInfo\Type\CollectionType;
28 use Symfony\Component\TypeInfo\TypeContext\TypeContextFactory;
29 use Symfony\Component\TypeInfo\TypeIdentifier;
30 use Symfony\Component\TypeInfo\TypeResolver\ReflectionParameterTypeResolver;
31 use Symfony\Component\TypeInfo\TypeResolver\ReflectionPropertyTypeResolver;
32 use Symfony\Component\TypeInfo\TypeResolver\ReflectionReturnTypeResolver;
33 use Symfony\Component\TypeInfo\TypeResolver\ReflectionTypeResolver;
34 use Symfony\Component\TypeInfo\TypeResolver\TypeResolver;
35 use Symfony\Component\TypeInfo\TypeResolver\TypeResolverInterface;
36
37 /**
38 * Extracts data using the reflection API.
39 *
40 * @author Kévin Dunglas <[email protected]>
41 *
42 * @final
43 */
44 class ReflectionExtractor implements PropertyListExtractorInterface, PropertyTypeExtractorInterface, PropertyAccessExtractorInterface, PropertyInitializableExtractorInterface, PropertyReadInfoExtractorInterface, PropertyWriteInfoExtractorInterface, ConstructorArgumentTypeExtractorInterface
45 {
46 /**
47 * @internal
48 */
49 public static array $defaultMutatorPrefixes = ['add', 'remove', 'set'];
50
51 /**
52 * @internal
53 */
54 public static array $defaultAccessorPrefixes = ['get', 'is', 'has', 'can'];
55
56 /**
57 * @internal
58 */
59 public static array $defaultArrayMutatorPrefixes = ['add', 'remove'];
60
61 public const ALLOW_PRIVATE = 1;
62 public const ALLOW_PROTECTED = 2;
63 public const ALLOW_PUBLIC = 4;
64
65 /** @var int Allow none of the magic methods */
66 public const DISALLOW_MAGIC_METHODS = 0;
67 /** @var int Allow magic __get methods */
68 public const ALLOW_MAGIC_GET = 1 << 0;
69 /** @var int Allow magic __set methods */
70 public const ALLOW_MAGIC_SET = 1 << 1;
71 /** @var int Allow magic __call methods */
72 public const ALLOW_MAGIC_CALL = 1 << 2;
73
74 private const MAP_TYPES = [
75 'integer' => TypeIdentifier::INT->value,
76 'boolean' => TypeIdentifier::BOOL->value,
77 'double' => TypeIdentifier::FLOAT->value,
78 ];
79
80 private array $mutatorPrefixes;
81 private array $accessorPrefixes;
82 private array $arrayMutatorPrefixes;
83 private int $methodReflectionFlags;
84 private int $propertyReflectionFlags;
85 private InflectorInterface $inflector;
86 private array $arrayMutatorPrefixesFirst;
87 private array $arrayMutatorPrefixesLast;
88 private TypeResolverInterface $typeResolver;
89
90 /**
91 * @param string[]|null $mutatorPrefixes
92 * @param string[]|null $accessorPrefixes
93 * @param string[]|null $arrayMutatorPrefixes
94 */
95 public function __construct(
96 ?array $mutatorPrefixes = null,
97 ?array $accessorPrefixes = null,
98 ?array $arrayMutatorPrefixes = null,
99 private bool $enableConstructorExtraction = true,
100 int $accessFlags = self::ALLOW_PUBLIC,
101 ?InflectorInterface $inflector = null,
102 private int $magicMethodsFlags = self::ALLOW_MAGIC_GET | self::ALLOW_MAGIC_SET,
103 ) {
104 $this->mutatorPrefixes = $mutatorPrefixes ?? self::$defaultMutatorPrefixes;
105 $this->accessorPrefixes = $accessorPrefixes ?? self::$defaultAccessorPrefixes;
106 $this->arrayMutatorPrefixes = $arrayMutatorPrefixes ?? self::$defaultArrayMutatorPrefixes;
107 $this->methodReflectionFlags = $this->getMethodsFlags($accessFlags);
108 $this->propertyReflectionFlags = $this->getPropertyFlags($accessFlags);
109 $this->inflector = $inflector ?? new EnglishInflector();
110
111 $typeContextFactory = new TypeContextFactory();
112 $this->typeResolver = TypeResolver::create([
113 \ReflectionType::class => $reflectionTypeResolver = new ReflectionTypeResolver(),
114 \ReflectionParameter::class => new ReflectionParameterTypeResolver($reflectionTypeResolver, $typeContextFactory),
115 \ReflectionProperty::class => new ReflectionPropertyTypeResolver($reflectionTypeResolver, $typeContextFactory),
116 \ReflectionFunctionAbstract::class => new ReflectionReturnTypeResolver($reflectionTypeResolver, $typeContextFactory),
117 ]);
118
119 $this->arrayMutatorPrefixesFirst = array_merge($this->arrayMutatorPrefixes, array_diff($this->mutatorPrefixes, $this->arrayMutatorPrefixes));
120 $this->arrayMutatorPrefixesLast = array_reverse($this->arrayMutatorPrefixesFirst);
121 }
122
123 public function getProperties(string $class, array $context = []): ?array
124 {
125 try {
126 $reflectionClass = new \ReflectionClass($class);
127 } catch (\ReflectionException) {
128 return null;
129 }
130
131 $reflectionProperties = $reflectionClass->getProperties();
132
133 $properties = [];
134 foreach ($reflectionProperties as $reflectionProperty) {
135 if ($reflectionProperty->getModifiers() & $this->propertyReflectionFlags) {
136 $properties[$reflectionProperty->name] = $reflectionProperty->name;
137 }
138 }
139
140 foreach ($reflectionClass->getMethods($this->methodReflectionFlags) as $reflectionMethod) {
141 if ($reflectionMethod->isStatic()) {
142 continue;
143 }
144
145 $propertyName = $this->getPropertyName($reflectionMethod->name, $reflectionProperties);
146 if (!$propertyName || isset($properties[$propertyName])) {
147 continue;
148 }
149 if ($reflectionClass->hasProperty($lowerCasedPropertyName = lcfirst($propertyName)) || (!$reflectionClass->hasProperty($propertyName) && !preg_match('/^[A-Z]{2,}/', $propertyName))) {
150 $propertyName = $lowerCasedPropertyName;
151 }
152 $properties[$propertyName] = $propertyName;
153 }
154
155 return $properties ? array_values($properties) : null;
156 }
157
158 /**
159 * @deprecated since Symfony 7.3, use "getType" instead
160 */
161 public function getTypes(string $class, string $property, array $context = []): ?array
162 {
163 trigger_deprecation('symfony/property-info', '7.3', 'The "%s()" method is deprecated, use "%s::getType()" instead.', __METHOD__, self::class);
164
165 if ($fromMutator = $this->extractFromMutator($class, $property)) {
166 return $fromMutator;
167 }
168
169 $allowedPrefixes = array_diff($this->accessorPrefixes, ['is', 'can', 'has']);
170 if ($fromAccessor = $this->extractFromAccessor($class, $property, $allowedPrefixes)) {
171 return $fromAccessor;
172 }
173
174 if (
175 ($context['enable_constructor_extraction'] ?? $this->enableConstructorExtraction)
176 && $fromConstructor = $this->extractFromConstructor($class, $property)
177 ) {
178 return $fromConstructor;
179 }
180
181 if ($fromPropertyDeclaration = $this->extractFromPropertyDeclaration($class, $property)) {
182 return $fromPropertyDeclaration;
183 }
184
185 $allowedPrefixes = array_diff($this->accessorPrefixes, $allowedPrefixes);
186 if ($fromAccessor = $this->extractFromAccessor($class, $property, $allowedPrefixes)) {
187 return $fromAccessor;
188 }
189
190 return null;
191 }
192
193 /**
194 * @deprecated since Symfony 7.3, use "getTypeFromConstructor" instead
195 *
196 * @return LegacyType[]|null
197 */
198 public function getTypesFromConstructor(string $class, string $property): ?array
199 {
200 trigger_deprecation('symfony/property-info', '7.3', 'The "%s()" method is deprecated, use "%s::getTypeFromConstructor()" instead.', __METHOD__, self::class);
201
202 try {
203 $reflection = new \ReflectionClass($class);
204 } catch (\ReflectionException) {
205 return null;
206 }
207 if (!$reflectionConstructor = $reflection->getConstructor()) {
208 return null;
209 }
210 if (!$reflectionParameter = $this->getReflectionParameterFromConstructor($property, $reflectionConstructor)) {
211 return null;
212 }
213 if (!$reflectionType = $reflectionParameter->getType()) {
214 return null;
215 }
216 if (!$types = $this->extractFromReflectionType($reflectionType, $reflectionConstructor->getDeclaringClass())) {
217 return null;
218 }
219
220 return $types;
221 }
222
223 public function getType(string $class, string $property, array $context = []): ?Type
224 {
225 [$mutatorReflection, $prefix] = $this->getMutatorMethod($class, $property);
226
227 if ($mutatorReflection) {
228 try {
229 $type = $this->typeResolver->resolve($mutatorReflection->getParameters()[0]);
230
231 if (!$type instanceof CollectionType && \in_array($prefix, $this->arrayMutatorPrefixes, true)) {
232 $type = $this->isNullableProperty($class, $property) ? Type::nullable(Type::list($type)) : Type::list($type);
233 }
234
235 return $type;
236 } catch (UnsupportedException) {
237 }
238 }
239
240 [$accessorReflection, $prefix] = $this->getAccessorMethod($class, $property);
241 $allowedPrefixes = array_diff($this->accessorPrefixes, ['is', 'can', 'has']);
242 if ($accessorReflection && (\in_array($prefix, $allowedPrefixes, true) || !property_exists($class, $property))) {
243 try {
244 return $this->typeResolver->resolve($accessorReflection);
245 } catch (UnsupportedException) {
246 }
247 }
248
249 if ($context['enable_constructor_extraction'] ?? $this->enableConstructorExtraction) {
250 try {
251 $reflectionClass = new \ReflectionClass($class);
252 if ($type = $this->extractTypeFromConstructor($reflectionClass, $property)) {
253 return $type;
254 }
255 } catch (\ReflectionException) {
256 }
257 }
258
259 try {
260 $reflectionClass = new \ReflectionClass($class);
261 $reflectionProperty = $reflectionClass->getProperty($property);
262 } catch (\ReflectionException) {
263 return null;
264 }
265
266 try {
267 return $this->typeResolver->resolve($reflectionProperty);
268 } catch (UnsupportedException) {
269 }
270
271 $allowedPrefixes = array_diff($this->accessorPrefixes, $allowedPrefixes);
272 [$accessorReflection, $prefix] = $this->getAccessorMethod($class, $property);
273 if ($accessorReflection && \in_array($prefix, $allowedPrefixes, true)) {
274 try {
275 return $this->typeResolver->resolve($accessorReflection);
276 } catch (UnsupportedException) {
277 }
278 }
279
280 if (null === $defaultValue = ($reflectionClass->getDefaultProperties()[$property] ?? null)) {
281 return null;
282 }
283
284 $typeIdentifier = TypeIdentifier::from(static::MAP_TYPES[\gettype($defaultValue)] ?? \gettype($defaultValue));
285 $type = 'array' === $typeIdentifier->value ? Type::array() : Type::builtin($typeIdentifier);
286
287 if ($this->isNullableProperty($class, $property)) {
288 $type = Type::nullable($type);
289 }
290
291 return $type;
292 }
293
294 public function getTypeFromConstructor(string $class, string $property): ?Type
295 {
296 try {
297 $reflection = new \ReflectionClass($class);
298 } catch (\ReflectionException) {
299 return null;
300 }
301
302 if (!$reflectionConstructor = $reflection->getConstructor()) {
303 return null;
304 }
305 if (!$reflectionParameter = $this->getReflectionParameterFromConstructor($property, $reflectionConstructor)) {
306 return null;
307 }
308
309 try {
310 return $this->typeResolver->resolve($reflectionParameter);
311 } catch (UnsupportedException) {
312 return null;
313 }
314 }
315
316 private function getReflectionParameterFromConstructor(string $property, \ReflectionMethod $reflectionConstructor): ?\ReflectionParameter
317 {
318 foreach ($reflectionConstructor->getParameters() as $reflectionParameter) {
319 if ($reflectionParameter->getName() === $property) {
320 return $reflectionParameter;
321 }
322 }
323
324 return null;
325 }
326
327 public function isReadable(string $class, string $property, array $context = []): ?bool
328 {
329 if ($this->isAllowedProperty($class, $property)) {
330 return true;
331 }
332
333 return null !== $this->getReadInfo($class, $property, $context);
334 }
335
336 public function isWritable(string $class, string $property, array $context = []): ?bool
337 {
338 if ($this->isAllowedProperty($class, $property, true)) {
339 return true;
340 }
341
342 // First test with the camelized property name
343 [$reflectionMethod] = $this->getMutatorMethod($class, $this->camelize($property));
344 if (null !== $reflectionMethod) {
345 return true;
346 }
347
348 // Otherwise check for the old way
349 [$reflectionMethod] = $this->getMutatorMethod($class, $property);
350
351 return null !== $reflectionMethod;
352 }
353
354 public function isInitializable(string $class, string $property, array $context = []): ?bool
355 {
356 try {
357 $reflectionClass = new \ReflectionClass($class);
358 } catch (\ReflectionException) {
359 return null;
360 }
361
362 if (!$reflectionClass->isInstantiable()) {
363 return false;
364 }
365
366 if ($constructor = $reflectionClass->getConstructor()) {
367 foreach ($constructor->getParameters() as $parameter) {
368 if ($property === $parameter->name) {
369 return true;
370 }
371 }
372 } elseif ($parentClass = $reflectionClass->getParentClass()) {
373 return $this->isInitializable($parentClass->getName(), $property);
374 }
375
376 return false;
377 }
378
379 public function getReadInfo(string $class, string $property, array $context = []): ?PropertyReadInfo
380 {
381 try {
382 $reflClass = new \ReflectionClass($class);
383 } catch (\ReflectionException) {
384 return null;
385 }
386
387 $allowGetterSetter = $context['enable_getter_setter_extraction'] ?? false;
388 $magicMethods = $context['enable_magic_methods_extraction'] ?? $this->magicMethodsFlags;
389 $allowMagicCall = (bool) ($magicMethods & self::ALLOW_MAGIC_CALL);
390 $allowMagicGet = (bool) ($magicMethods & self::ALLOW_MAGIC_GET);
391 $hasProperty = $reflClass->hasProperty($property);
392 $camelProp = $this->camelize($property);
393 $getsetter = lcfirst($camelProp); // jQuery style, e.g. read: last(), write: last($item)
394
395 foreach ($this->accessorPrefixes as $prefix) {
396 $methodName = $prefix.$camelProp;
397
398 if ($reflClass->hasMethod($methodName) && ($m = $reflClass->getMethod($methodName))->getModifiers() & $this->methodReflectionFlags && !$m->getNumberOfRequiredParameters() && !\in_array((string) $m->getReturnType(), ['void', 'never'], true)) {
399 return new PropertyReadInfo(PropertyReadInfo::TYPE_METHOD, $methodName, $this->getReadVisibilityForMethod($m), $m->isStatic(), false);
400 }
401 }
402
403 if ($allowGetterSetter && $reflClass->hasMethod($getsetter) && ($m = $reflClass->getMethod($getsetter))->getModifiers() & $this->methodReflectionFlags && !$m->getNumberOfRequiredParameters() && !\in_array((string) $m->getReturnType(), ['void', 'never'], true)) {
404 return new PropertyReadInfo(PropertyReadInfo::TYPE_METHOD, $getsetter, $this->getReadVisibilityForMethod($m), $m->isStatic(), false);
405 }
406
407 if ($allowMagicGet && $reflClass->hasMethod('__get') && (($r = $reflClass->getMethod('__get'))->getModifiers() & $this->methodReflectionFlags)) {
408 return new PropertyReadInfo(PropertyReadInfo::TYPE_PROPERTY, $property, PropertyReadInfo::VISIBILITY_PUBLIC, false, $r->returnsReference());
409 }
410
411 if ($hasProperty && (($r = $reflClass->getProperty($property))->getModifiers() & $this->propertyReflectionFlags)) {
412 return new PropertyReadInfo(PropertyReadInfo::TYPE_PROPERTY, $property, $this->getReadVisibilityForProperty($r), $r->isStatic(), true);
413 }
414
415 if ($allowMagicCall && $reflClass->hasMethod('__call') && ($reflClass->getMethod('__call')->getModifiers() & $this->methodReflectionFlags)) {
416 return new PropertyReadInfo(PropertyReadInfo::TYPE_METHOD, 'get'.$camelProp, PropertyReadInfo::VISIBILITY_PUBLIC, false, false);
417 }
418
419 return null;
420 }
421
422 public function getWriteInfo(string $class, string $property, array $context = []): ?PropertyWriteInfo
423 {
424 try {
425 $reflClass = new \ReflectionClass($class);
426 } catch (\ReflectionException) {
427 return null;
428 }
429
430 $allowGetterSetter = $context['enable_getter_setter_extraction'] ?? false;
431 $magicMethods = $context['enable_magic_methods_extraction'] ?? $this->magicMethodsFlags;
432 $allowMagicCall = (bool) ($magicMethods & self::ALLOW_MAGIC_CALL);
433 $allowMagicSet = (bool) ($magicMethods & self::ALLOW_MAGIC_SET);
434 $allowConstruct = $context['enable_constructor_extraction'] ?? $this->enableConstructorExtraction;
435 $allowAdderRemover = $context['enable_adder_remover_extraction'] ?? true;
436
437 $camelized = $this->camelize($property);
438 $nonCamelized = ucfirst($property);
439 $constructor = $reflClass->getConstructor();
440 $singulars = $this->inflector->singularize($camelized);
441 $errors = [];
442
443 if (null !== $constructor && $allowConstruct) {
444 foreach ($constructor->getParameters() as $parameter) {
445 if ($parameter->getName() === $property) {
446 return new PropertyWriteInfo(PropertyWriteInfo::TYPE_CONSTRUCTOR, $property);
447 }
448 }
449 }
450
451 [$adderAccessName, $removerAccessName, $adderAndRemoverErrors] = $this->findAdderAndRemover($reflClass, $singulars);
452 if ($allowAdderRemover && null !== $adderAccessName && null !== $removerAccessName) {
453 $adderMethod = $reflClass->getMethod($adderAccessName);
454 $removerMethod = $reflClass->getMethod($removerAccessName);
455
456 $mutator = new PropertyWriteInfo(PropertyWriteInfo::TYPE_ADDER_AND_REMOVER);
457 $mutator->setAdderInfo(new PropertyWriteInfo(PropertyWriteInfo::TYPE_METHOD, $adderAccessName, $this->getWriteVisibilityForMethod($adderMethod), $adderMethod->isStatic()));
458 $mutator->setRemoverInfo(new PropertyWriteInfo(PropertyWriteInfo::TYPE_METHOD, $removerAccessName, $this->getWriteVisibilityForMethod($removerMethod), $removerMethod->isStatic()));
459
460 return $mutator;
461 }
462
463 $errors[] = $adderAndRemoverErrors;
464
465 foreach ($this->mutatorPrefixes as $mutatorPrefix) {
466 $methodName = $mutatorPrefix.$camelized;
467
468 [$accessible, $methodAccessibleErrors] = $this->isMethodAccessible($reflClass, $methodName, 1);
469 if (!$accessible) {
470 $errors[] = $methodAccessibleErrors;
471 continue;
472 }
473
474 $method = $reflClass->getMethod($methodName);
475
476 if (!\in_array($mutatorPrefix, $this->arrayMutatorPrefixes, true)) {
477 return new PropertyWriteInfo(PropertyWriteInfo::TYPE_METHOD, $methodName, $this->getWriteVisibilityForMethod($method), $method->isStatic());
478 }
479 }
480
481 if ($camelized !== $nonCamelized) {
482 foreach ($this->mutatorPrefixes as $mutatorPrefix) {
483 $methodName = $mutatorPrefix.$nonCamelized;
484
485 [$accessible, $methodAccessibleErrors] = $this->isMethodAccessible($reflClass, $methodName, 1);
486 if (!$accessible) {
487 $errors[] = $methodAccessibleErrors;
488 continue;
489 }
490
491 $method = $reflClass->getMethod($methodName);
492
493 if (!\in_array($mutatorPrefix, $this->arrayMutatorPrefixes, true)) {
494 return new PropertyWriteInfo(PropertyWriteInfo::TYPE_METHOD, $methodName, $this->getWriteVisibilityForMethod($method), $method->isStatic());
495 }
496 }
497 }
498
499 $getsetter = lcfirst($camelized);
500 $getsetterNonCamelized = lcfirst($nonCamelized);
501
502 if ($allowGetterSetter) {
503 [$accessible, $methodAccessibleErrors] = $this->isMethodAccessible($reflClass, $getsetter, 1);
504 if ($accessible) {
505 $method = $reflClass->getMethod($getsetter);
506
507 return new PropertyWriteInfo(PropertyWriteInfo::TYPE_METHOD, $getsetter, $this->getWriteVisibilityForMethod($method), $method->isStatic());
508 }
509
510 $errors[] = $methodAccessibleErrors;
511
512 if ($getsetter !== $getsetterNonCamelized) {
513 [$accessible, $methodAccessibleErrors] = $this->isMethodAccessible($reflClass, $getsetterNonCamelized, 1);
514 if ($accessible) {
515 $method = $reflClass->getMethod($getsetterNonCamelized);
516
517 return new PropertyWriteInfo(PropertyWriteInfo::TYPE_METHOD, $getsetterNonCamelized, $this->getWriteVisibilityForMethod($method), $method->isStatic());
518 }
519 $errors[] = $methodAccessibleErrors;
520 }
521 }
522
523 if ($reflClass->hasProperty($property) && ($reflClass->getProperty($property)->getModifiers() & $this->propertyReflectionFlags)) {
524 $reflProperty = $reflClass->getProperty($property);
525 if (!$reflProperty->isReadOnly()) {
526 return new PropertyWriteInfo(PropertyWriteInfo::TYPE_PROPERTY, $property, $this->getWriteVisibilityForProperty($reflProperty), $reflProperty->isStatic());
527 }
528
529 $errors[] = [\sprintf('The property "%s" in class "%s" is a promoted readonly property.', $property, $reflClass->getName())];
530 $allowMagicSet = $allowMagicCall = false;
531 }
532
533 if ($allowMagicSet) {
534 [$accessible, $methodAccessibleErrors] = $this->isMethodAccessible($reflClass, '__set', 2);
535 if ($accessible) {
536 return new PropertyWriteInfo(PropertyWriteInfo::TYPE_PROPERTY, $property, PropertyWriteInfo::VISIBILITY_PUBLIC, false);
537 }
538
539 $errors[] = $methodAccessibleErrors;
540 }
541
542 if ($allowMagicCall) {
543 [$accessible, $methodAccessibleErrors] = $this->isMethodAccessible($reflClass, '__call', 2);
544 if ($accessible) {
545 return new PropertyWriteInfo(PropertyWriteInfo::TYPE_METHOD, 'set'.$camelized, PropertyWriteInfo::VISIBILITY_PUBLIC, false);
546 }
547
548 $errors[] = $methodAccessibleErrors;
549 }
550
551 if (!$allowAdderRemover && null !== $adderAccessName && null !== $removerAccessName) {
552 $errors[] = [\sprintf(
553 'The property "%s" in class "%s" can be defined with the methods "%s()" but '.
554 'the new value must be an array or an instance of \Traversable',
555 $property,
556 $reflClass->getName(),
557 implode('()", "', [$adderAccessName, $removerAccessName])
558 )];
559 }
560
561 $noneProperty = new PropertyWriteInfo();
562 $noneProperty->setErrors(array_merge([], ...$errors));
563
564 return $noneProperty;
565 }
566
567 /**
568 * @return LegacyType[]|null
569 */
570 private function extractFromMutator(string $class, string $property): ?array
571 {
572 [$reflectionMethod, $prefix] = $this->getMutatorMethod($class, $property);
573 if (null === $reflectionMethod) {
574 return null;
575 }
576
577 $reflectionParameters = $reflectionMethod->getParameters();
578 $reflectionParameter = $reflectionParameters[0];
579
580 if (!$reflectionType = $reflectionParameter->getType()) {
581 return null;
582 }
583 $type = $this->extractFromReflectionType($reflectionType, $reflectionMethod->getDeclaringClass());
584
585 if (1 === \count($type) && \in_array($prefix, $this->arrayMutatorPrefixes, true)) {
586 $type = [new LegacyType(LegacyType::BUILTIN_TYPE_ARRAY, $this->isNullableProperty($class, $property), null, true, new LegacyType(LegacyType::BUILTIN_TYPE_INT), $type[0])];
587 }
588
589 return $type;
590 }
591
592 /**
593 * Tries to extract type information from accessors.
594 *
595 * @return LegacyType[]|null
596 */
597 private function extractFromAccessor(string $class, string $property, array $allowedPrefixes): ?array
598 {
599 [$reflectionMethod, $prefix] = $this->getAccessorMethod($class, $property);
600 if (null === $reflectionMethod) {
601 return null;
602 }
603
604 if (!\in_array($prefix, $allowedPrefixes, true)) {
605 return null;
606 }
607
608 if ($reflectionType = $reflectionMethod->getReturnType()) {
609 return $this->extractFromReflectionType($reflectionType, $reflectionMethod->getDeclaringClass());
610 }
611
612 if (\in_array($prefix, ['is', 'can', 'has'], true)) {
613 return [new LegacyType(LegacyType::BUILTIN_TYPE_BOOL)];
614 }
615
616 return null;
617 }
618
619 /**
620 * Tries to extract type information from constructor.
621 *
622 * @return LegacyType[]|null
623 */
624 private function extractFromConstructor(string $class, string $property): ?array
625 {
626 try {
627 $reflectionClass = new \ReflectionClass($class);
628 } catch (\ReflectionException) {
629 return null;
630 }
631
632 $constructor = $reflectionClass->getConstructor();
633
634 if (!$constructor) {
635 return null;
636 }
637
638 foreach ($constructor->getParameters() as $parameter) {
639 if ($property !== $parameter->name) {
640 continue;
641 }
642 $reflectionType = $parameter->getType();
643
644 return $reflectionType ? $this->extractFromReflectionType($reflectionType, $constructor->getDeclaringClass()) : null;
645 }
646
647 if ($parentClass = $reflectionClass->getParentClass()) {
648 return $this->extractFromConstructor($parentClass->getName(), $property);
649 }
650
651 return null;
652 }
653
654 private function extractFromPropertyDeclaration(string $class, string $property): ?array
655 {
656 try {
657 $reflectionClass = new \ReflectionClass($class);
658
659 $reflectionProperty = $reflectionClass->getProperty($property);
660 $reflectionPropertyType = $reflectionProperty->getType();
661
662 if (null !== $reflectionPropertyType && $types = $this->extractFromReflectionType($reflectionPropertyType, $reflectionProperty->getDeclaringClass())) {
663 return $types;
664 }
665 } catch (\ReflectionException) {
666 return null;
667 }
668
669 $defaultValue = $reflectionClass->getDefaultProperties()[$property] ?? null;
670
671 if (null === $defaultValue) {
672 return null;
673 }
674
675 $type = \gettype($defaultValue);
676 $type = static::MAP_TYPES[$type] ?? $type;
677
678 return [new LegacyType($type, $this->isNullableProperty($class, $property), null, LegacyType::BUILTIN_TYPE_ARRAY === $type)];
679 }
680
681 private function extractTypeFromConstructor(\ReflectionClass $reflectionClass, string $property): ?Type
682 {
683 if (!$constructor = $reflectionClass->getConstructor()) {
684 return null;
685 }
686
687 foreach ($constructor->getParameters() as $parameter) {
688 if ($property !== $parameter->name) {
689 continue;
690 }
691
692 try {
693 return $this->typeResolver->resolve($parameter);
694 } catch (UnsupportedException) {
695 }
696 }
697
698 if ($parentClass = $reflectionClass->getParentClass()) {
699 return $this->extractTypeFromConstructor($parentClass, $property);
700 }
701
702 return null;
703 }
704
705 private function extractFromReflectionType(\ReflectionType $reflectionType, \ReflectionClass $declaringClass): array
706 {
707 $types = [];
708 $nullable = $reflectionType->allowsNull();
709
710 foreach (($reflectionType instanceof \ReflectionUnionType || $reflectionType instanceof \ReflectionIntersectionType) ? $reflectionType->getTypes() : [$reflectionType] as $type) {
711 if (!$type instanceof \ReflectionNamedType) {
712 // Nested composite types are not supported yet.
713 return [];
714 }
715
716 $phpTypeOrClass = $type->getName();
717 if ('null' === $phpTypeOrClass || 'mixed' === $phpTypeOrClass || 'never' === $phpTypeOrClass) {
718 continue;
719 }
720
721 if (LegacyType::BUILTIN_TYPE_ARRAY === $phpTypeOrClass) {
722 $types[] = new LegacyType(LegacyType::BUILTIN_TYPE_ARRAY, $nullable, null, true);
723 } elseif ('void' === $phpTypeOrClass) {
724 $types[] = new LegacyType(LegacyType::BUILTIN_TYPE_NULL, $nullable);
725 } elseif ($type->isBuiltin()) {
726 $types[] = new LegacyType($phpTypeOrClass, $nullable);
727 } else {
728 $types[] = new LegacyType(LegacyType::BUILTIN_TYPE_OBJECT, $nullable, $this->resolveTypeName($phpTypeOrClass, $declaringClass));
729 }
730 }
731
732 return $types;
733 }
734
735 private function resolveTypeName(string $name, \ReflectionClass $declaringClass): string
736 {
737 if ('self' === $lcName = strtolower($name)) {
738 return $declaringClass->name;
739 }
740 if ('parent' === $lcName && $parent = $declaringClass->getParentClass()) {
741 return $parent->name;
742 }
743
744 return $name;
745 }
746
747 private function isNullableProperty(string $class, string $property): bool
748 {
749 try {
750 $reflectionProperty = new \ReflectionProperty($class, $property);
751
752 $reflectionPropertyType = $reflectionProperty->getType();
753
754 return null !== $reflectionPropertyType && $reflectionPropertyType->allowsNull();
755 } catch (\ReflectionException) {
756 // Return false if the property doesn't exist
757 }
758
759 return false;
760 }
761
762 private function isAllowedProperty(string $class, string $property, bool $writeAccessRequired = false): bool
763 {
764 try {
765 $reflectionProperty = new \ReflectionProperty($class, $property);
766
767 if ($writeAccessRequired) {
768 if ($reflectionProperty->isReadOnly()) {
769 return false;
770 }
771
772 if (\PHP_VERSION_ID >= 80400 && $reflectionProperty->isProtectedSet()) {
773 return (bool) ($this->propertyReflectionFlags & \ReflectionProperty::IS_PROTECTED);
774 }
775
776 if (\PHP_VERSION_ID >= 80400 && $reflectionProperty->isPrivateSet()) {
777 return (bool) ($this->propertyReflectionFlags & \ReflectionProperty::IS_PRIVATE);
778 }
779
780 if (\PHP_VERSION_ID >= 80400 && $reflectionProperty->isVirtual() && !$reflectionProperty->hasHook(\PropertyHookType::Set)) {
781 return false;
782 }
783 }
784
785 return (bool) ($reflectionProperty->getModifiers() & $this->propertyReflectionFlags);
786 } catch (\ReflectionException) {
787 // Return false if the property doesn't exist
788 }
789
790 return false;
791 }
792
793 /**
794 * Gets the accessor method.
795 *
796 * Returns an array with an instance of \ReflectionMethod as the first key
797 * and the prefix of the method as the second, or null if not found.
798 */
799 private function getAccessorMethod(string $class, string $property): ?array
800 {
801 $ucProperty = ucfirst($property);
802
803 foreach ($this->accessorPrefixes as $prefix) {
804 try {
805 $reflectionMethod = new \ReflectionMethod($class, $prefix.$ucProperty);
806 if ($reflectionMethod->isStatic()) {
807 continue;
808 }
809
810 if (0 === $reflectionMethod->getNumberOfRequiredParameters()) {
811 return [$reflectionMethod, $prefix];
812 }
813 } catch (\ReflectionException) {
814 // Return null if the property doesn't exist
815 }
816 }
817
818 return null;
819 }
820
821 /**
822 * Returns an array with an instance of \ReflectionMethod as the first key
823 * and the prefix of the method as the second, or null if not found.
824 */
825 private function getMutatorMethod(string $class, string $property): ?array
826 {
827 $ucProperty = ucfirst($property);
828 $ucSingulars = $this->inflector->singularize($ucProperty);
829
830 $mutatorPrefixes = \in_array($ucProperty, $ucSingulars, true) ? $this->arrayMutatorPrefixesLast : $this->arrayMutatorPrefixesFirst;
831
832 foreach ($mutatorPrefixes as $prefix) {
833 $names = [$ucProperty];
834 if (\in_array($prefix, $this->arrayMutatorPrefixes, true)) {
835 $names = array_merge($names, $ucSingulars);
836 }
837
838 foreach ($names as $name) {
839 try {
840 $reflectionMethod = new \ReflectionMethod($class, $prefix.$name);
841 if ($reflectionMethod->isStatic()) {
842 continue;
843 }
844
845 // Parameter can be optional to allow things like: method(?array $foo = null)
846 if ($reflectionMethod->getNumberOfParameters() >= 1) {
847 return [$reflectionMethod, $prefix];
848 }
849 } catch (\ReflectionException) {
850 // Try the next prefix if the method doesn't exist
851 }
852 }
853 }
854
855 return null;
856 }
857
858 private function getPropertyName(string $methodName, array $reflectionProperties): ?string
859 {
860 $pattern = implode('|', array_merge($this->accessorPrefixes, $this->mutatorPrefixes));
861
862 if ('' !== $pattern && preg_match('/^('.$pattern.')(.+)$/i', $methodName, $matches)) {
863 if (!\in_array($matches[1], $this->arrayMutatorPrefixes, true)) {
864 return $matches[2];
865 }
866
867 foreach ($reflectionProperties as $reflectionProperty) {
868 foreach ($this->inflector->singularize($reflectionProperty->name) as $name) {
869 if (strtolower($name) === strtolower($matches[2])) {
870 return $reflectionProperty->name;
871 }
872 }
873 }
874
875 return $matches[2];
876 }
877
878 return null;
879 }
880
881 /**
882 * Searches for add and remove methods.
883 *
884 * @param \ReflectionClass $reflClass The reflection class for the given object
885 * @param array $singulars The singular form of the property name or null
886 *
887 * @return array An array containing the adder and remover when found and errors
888 */
889 private function findAdderAndRemover(\ReflectionClass $reflClass, array $singulars): array
890 {
891 if (2 !== \count($this->arrayMutatorPrefixes)) {
892 return [null, null, []];
893 }
894
895 [$addPrefix, $removePrefix] = $this->arrayMutatorPrefixes;
896 $errors = [];
897
898 foreach ($singulars as $singular) {
899 $addMethod = $addPrefix.$singular;
900 $removeMethod = $removePrefix.$singular;
901
902 [$addMethodFound, $addMethodAccessibleErrors] = $this->isMethodAccessible($reflClass, $addMethod, 1);
903 [$removeMethodFound, $removeMethodAccessibleErrors] = $this->isMethodAccessible($reflClass, $removeMethod, 1);
904 $errors[] = $addMethodAccessibleErrors;
905 $errors[] = $removeMethodAccessibleErrors;
906
907 if ($addMethodFound && $removeMethodFound) {
908 return [$addMethod, $removeMethod, []];
909 }
910
911 if ($addMethodFound && !$removeMethodFound) {
912 $errors[] = [\sprintf('The add method "%s" in class "%s" was found, but the corresponding remove method "%s" was not found', $addMethod, $reflClass->getName(), $removeMethod)];
913 } elseif (!$addMethodFound && $removeMethodFound) {
914 $errors[] = [\sprintf('The remove method "%s" in class "%s" was found, but the corresponding add method "%s" was not found', $removeMethod, $reflClass->getName(), $addMethod)];
915 }
916 }
917
918 return [null, null, array_merge([], ...$errors)];
919 }
920
921 /**
922 * Returns whether a method is public and has the number of required parameters and errors.
923 */
924 private function isMethodAccessible(\ReflectionClass $class, string $methodName, int $parameters): array
925 {
926 $errors = [];
927
928 if ($class->hasMethod($methodName)) {
929 $method = $class->getMethod($methodName);
930
931 if (\ReflectionMethod::IS_PUBLIC === $this->methodReflectionFlags && !$method->isPublic()) {
932 $errors[] = \sprintf('The method "%s" in class "%s" was found but does not have public access.', $methodName, $class->getName());
933 } elseif ($method->getNumberOfRequiredParameters() > $parameters || $method->getNumberOfParameters() < $parameters) {
934 $errors[] = \sprintf('The method "%s" in class "%s" requires %d arguments, but should accept only %d.', $methodName, $class->getName(), $method->getNumberOfRequiredParameters(), $parameters);
935 } else {
936 return [true, $errors];
937 }
938 }
939
940 return [false, $errors];
941 }
942
943 /**
944 * Camelizes a given string.
945 */
946 private function camelize(string $string): string
947 {
948 if ('' === ltrim($string, '_')) {
949 return $string;
950 }
951
952 return str_replace(' ', '', ucwords(str_replace('_', ' ', $string)));
953 }
954
955 /**
956 * Return allowed reflection method flags.
957 */
958 private function getMethodsFlags(int $accessFlags): int
959 {
960 $methodFlags = 0;
961
962 if ($accessFlags & self::ALLOW_PUBLIC) {
963 $methodFlags |= \ReflectionMethod::IS_PUBLIC;
964 }
965
966 if ($accessFlags & self::ALLOW_PRIVATE) {
967 $methodFlags |= \ReflectionMethod::IS_PRIVATE;
968 }
969
970 if ($accessFlags & self::ALLOW_PROTECTED) {
971 $methodFlags |= \ReflectionMethod::IS_PROTECTED;
972 }
973
974 return $methodFlags;
975 }
976
977 /**
978 * Return allowed reflection property flags.
979 */
980 private function getPropertyFlags(int $accessFlags): int
981 {
982 $propertyFlags = 0;
983
984 if ($accessFlags & self::ALLOW_PUBLIC) {
985 $propertyFlags |= \ReflectionProperty::IS_PUBLIC;
986 }
987
988 if ($accessFlags & self::ALLOW_PRIVATE) {
989 $propertyFlags |= \ReflectionProperty::IS_PRIVATE;
990 }
991
992 if ($accessFlags & self::ALLOW_PROTECTED) {
993 $propertyFlags |= \ReflectionProperty::IS_PROTECTED;
994 }
995
996 return $propertyFlags;
997 }
998
999 private function getReadVisibilityForProperty(\ReflectionProperty $reflectionProperty): string
1000 {
1001 if ($reflectionProperty->isPrivate()) {
1002 return PropertyReadInfo::VISIBILITY_PRIVATE;
1003 }
1004
1005 if ($reflectionProperty->isProtected()) {
1006 return PropertyReadInfo::VISIBILITY_PROTECTED;
1007 }
1008
1009 return PropertyReadInfo::VISIBILITY_PUBLIC;
1010 }
1011
1012 private function getReadVisibilityForMethod(\ReflectionMethod $reflectionMethod): string
1013 {
1014 if ($reflectionMethod->isPrivate()) {
1015 return PropertyReadInfo::VISIBILITY_PRIVATE;
1016 }
1017
1018 if ($reflectionMethod->isProtected()) {
1019 return PropertyReadInfo::VISIBILITY_PROTECTED;
1020 }
1021
1022 return PropertyReadInfo::VISIBILITY_PUBLIC;
1023 }
1024
1025 private function getWriteVisibilityForProperty(\ReflectionProperty $reflectionProperty): string
1026 {
1027 if (\PHP_VERSION_ID >= 80400) {
1028 if ($reflectionProperty->isVirtual() && !$reflectionProperty->hasHook(\PropertyHookType::Set)) {
1029 return PropertyWriteInfo::VISIBILITY_PRIVATE;
1030 }
1031
1032 if ($reflectionProperty->isPrivateSet()) {
1033 return PropertyWriteInfo::VISIBILITY_PRIVATE;
1034 }
1035
1036 if ($reflectionProperty->isProtectedSet()) {
1037 return PropertyWriteInfo::VISIBILITY_PROTECTED;
1038 }
1039 }
1040
1041 if ($reflectionProperty->isPrivate()) {
1042 return PropertyWriteInfo::VISIBILITY_PRIVATE;
1043 }
1044
1045 if ($reflectionProperty->isProtected()) {
1046 return PropertyWriteInfo::VISIBILITY_PROTECTED;
1047 }
1048
1049 return PropertyWriteInfo::VISIBILITY_PUBLIC;
1050 }
1051
1052 private function getWriteVisibilityForMethod(\ReflectionMethod $reflectionMethod): string
1053 {
1054 if ($reflectionMethod->isPrivate()) {
1055 return PropertyWriteInfo::VISIBILITY_PRIVATE;
1056 }
1057
1058 if ($reflectionMethod->isProtected()) {
1059 return PropertyWriteInfo::VISIBILITY_PROTECTED;
1060 }
1061
1062 return PropertyWriteInfo::VISIBILITY_PUBLIC;
1063 }
1064 }