ReflectionExtractor.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\PropertyInfo\Extractor;
  11. use Symfony\Component\PropertyInfo\PropertyAccessExtractorInterface;
  12. use Symfony\Component\PropertyInfo\PropertyInitializableExtractorInterface;
  13. use Symfony\Component\PropertyInfo\PropertyListExtractorInterface;
  14. use Symfony\Component\PropertyInfo\PropertyReadInfo;
  15. use Symfony\Component\PropertyInfo\PropertyReadInfoExtractorInterface;
  16. use Symfony\Component\PropertyInfo\PropertyTypeExtractorInterface;
  17. use Symfony\Component\PropertyInfo\PropertyWriteInfo;
  18. use Symfony\Component\PropertyInfo\PropertyWriteInfoExtractorInterface;
  19. use Symfony\Component\PropertyInfo\Type;
  20. use Symfony\Component\String\Inflector\EnglishInflector;
  21. use Symfony\Component\String\Inflector\InflectorInterface;
  22. /**
  23. * Extracts data using the reflection API.
  24. *
  25. * @author Kévin Dunglas <dunglas@gmail.com>
  26. *
  27. * @final
  28. */
  29. class ReflectionExtractor implements PropertyListExtractorInterface, PropertyTypeExtractorInterface, PropertyAccessExtractorInterface, PropertyInitializableExtractorInterface, PropertyReadInfoExtractorInterface, PropertyWriteInfoExtractorInterface, ConstructorArgumentTypeExtractorInterface
  30. {
  31. /**
  32. * @internal
  33. */
  34. public static $defaultMutatorPrefixes = ['add', 'remove', 'set'];
  35. /**
  36. * @internal
  37. */
  38. public static $defaultAccessorPrefixes = ['get', 'is', 'has', 'can'];
  39. /**
  40. * @internal
  41. */
  42. public static $defaultArrayMutatorPrefixes = ['add', 'remove'];
  43. public const ALLOW_PRIVATE = 1;
  44. public const ALLOW_PROTECTED = 2;
  45. public const ALLOW_PUBLIC = 4;
  46. /** @var int Allow none of the magic methods */
  47. public const DISALLOW_MAGIC_METHODS = 0;
  48. /** @var int Allow magic __get methods */
  49. public const ALLOW_MAGIC_GET = 1 << 0;
  50. /** @var int Allow magic __set methods */
  51. public const ALLOW_MAGIC_SET = 1 << 1;
  52. /** @var int Allow magic __call methods */
  53. public const ALLOW_MAGIC_CALL = 1 << 2;
  54. private const MAP_TYPES = [
  55. 'integer' => Type::BUILTIN_TYPE_INT,
  56. 'boolean' => Type::BUILTIN_TYPE_BOOL,
  57. 'double' => Type::BUILTIN_TYPE_FLOAT,
  58. ];
  59. private $mutatorPrefixes;
  60. private $accessorPrefixes;
  61. private $arrayMutatorPrefixes;
  62. private $enableConstructorExtraction;
  63. private $methodReflectionFlags;
  64. private $magicMethodsFlags;
  65. private $propertyReflectionFlags;
  66. private $inflector;
  67. private $arrayMutatorPrefixesFirst;
  68. private $arrayMutatorPrefixesLast;
  69. /**
  70. * @param string[]|null $mutatorPrefixes
  71. * @param string[]|null $accessorPrefixes
  72. * @param string[]|null $arrayMutatorPrefixes
  73. */
  74. public function __construct(array $mutatorPrefixes = null, array $accessorPrefixes = null, array $arrayMutatorPrefixes = null, bool $enableConstructorExtraction = true, int $accessFlags = self::ALLOW_PUBLIC, InflectorInterface $inflector = null, int $magicMethodsFlags = self::ALLOW_MAGIC_GET | self::ALLOW_MAGIC_SET)
  75. {
  76. $this->mutatorPrefixes = null !== $mutatorPrefixes ? $mutatorPrefixes : self::$defaultMutatorPrefixes;
  77. $this->accessorPrefixes = null !== $accessorPrefixes ? $accessorPrefixes : self::$defaultAccessorPrefixes;
  78. $this->arrayMutatorPrefixes = null !== $arrayMutatorPrefixes ? $arrayMutatorPrefixes : self::$defaultArrayMutatorPrefixes;
  79. $this->enableConstructorExtraction = $enableConstructorExtraction;
  80. $this->methodReflectionFlags = $this->getMethodsFlags($accessFlags);
  81. $this->propertyReflectionFlags = $this->getPropertyFlags($accessFlags);
  82. $this->magicMethodsFlags = $magicMethodsFlags;
  83. $this->inflector = $inflector ?? new EnglishInflector();
  84. $this->arrayMutatorPrefixesFirst = array_merge($this->arrayMutatorPrefixes, array_diff($this->mutatorPrefixes, $this->arrayMutatorPrefixes));
  85. $this->arrayMutatorPrefixesLast = array_reverse($this->arrayMutatorPrefixesFirst);
  86. }
  87. /**
  88. * {@inheritdoc}
  89. */
  90. public function getProperties(string $class, array $context = []): ?array
  91. {
  92. try {
  93. $reflectionClass = new \ReflectionClass($class);
  94. } catch (\ReflectionException $e) {
  95. return null;
  96. }
  97. $reflectionProperties = $reflectionClass->getProperties();
  98. $properties = [];
  99. foreach ($reflectionProperties as $reflectionProperty) {
  100. if ($reflectionProperty->getModifiers() & $this->propertyReflectionFlags) {
  101. $properties[$reflectionProperty->name] = $reflectionProperty->name;
  102. }
  103. }
  104. foreach ($reflectionClass->getMethods($this->methodReflectionFlags) as $reflectionMethod) {
  105. if ($reflectionMethod->isStatic()) {
  106. continue;
  107. }
  108. $propertyName = $this->getPropertyName($reflectionMethod->name, $reflectionProperties);
  109. if (!$propertyName || isset($properties[$propertyName])) {
  110. continue;
  111. }
  112. if ($reflectionClass->hasProperty($lowerCasedPropertyName = lcfirst($propertyName)) || (!$reflectionClass->hasProperty($propertyName) && !preg_match('/^[A-Z]{2,}/', $propertyName))) {
  113. $propertyName = $lowerCasedPropertyName;
  114. }
  115. $properties[$propertyName] = $propertyName;
  116. }
  117. return $properties ? array_values($properties) : null;
  118. }
  119. /**
  120. * {@inheritdoc}
  121. */
  122. public function getTypes(string $class, string $property, array $context = []): ?array
  123. {
  124. if ($fromMutator = $this->extractFromMutator($class, $property)) {
  125. return $fromMutator;
  126. }
  127. if ($fromAccessor = $this->extractFromAccessor($class, $property)) {
  128. return $fromAccessor;
  129. }
  130. if (
  131. ($context['enable_constructor_extraction'] ?? $this->enableConstructorExtraction) &&
  132. $fromConstructor = $this->extractFromConstructor($class, $property)
  133. ) {
  134. return $fromConstructor;
  135. }
  136. if ($fromDefaultValue = $this->extractFromDefaultValue($class, $property)) {
  137. return $fromDefaultValue;
  138. }
  139. if (\PHP_VERSION_ID >= 70400) {
  140. try {
  141. $reflectionProperty = new \ReflectionProperty($class, $property);
  142. $type = $reflectionProperty->getType();
  143. if (null !== $type && $types = $this->extractFromReflectionType($type, $reflectionProperty->getDeclaringClass())) {
  144. return $types;
  145. }
  146. } catch (\ReflectionException $e) {
  147. // noop
  148. }
  149. }
  150. return null;
  151. }
  152. /**
  153. * {@inheritdoc}
  154. */
  155. public function getTypesFromConstructor(string $class, string $property): ?array
  156. {
  157. try {
  158. $reflection = new \ReflectionClass($class);
  159. } catch (\ReflectionException $e) {
  160. return null;
  161. }
  162. if (!$reflectionConstructor = $reflection->getConstructor()) {
  163. return null;
  164. }
  165. if (!$reflectionParameter = $this->getReflectionParameterFromConstructor($property, $reflectionConstructor)) {
  166. return null;
  167. }
  168. if (!$reflectionType = $reflectionParameter->getType()) {
  169. return null;
  170. }
  171. if (!$types = $this->extractFromReflectionType($reflectionType, $reflectionConstructor->getDeclaringClass())) {
  172. return null;
  173. }
  174. return $types;
  175. }
  176. private function getReflectionParameterFromConstructor(string $property, \ReflectionMethod $reflectionConstructor): ?\ReflectionParameter
  177. {
  178. $reflectionParameter = null;
  179. foreach ($reflectionConstructor->getParameters() as $reflectionParameter) {
  180. if ($reflectionParameter->getName() === $property) {
  181. return $reflectionParameter;
  182. }
  183. }
  184. return null;
  185. }
  186. /**
  187. * {@inheritdoc}
  188. */
  189. public function isReadable(string $class, string $property, array $context = []): ?bool
  190. {
  191. if ($this->isAllowedProperty($class, $property)) {
  192. return true;
  193. }
  194. return null !== $this->getReadInfo($class, $property, $context);
  195. }
  196. /**
  197. * {@inheritdoc}
  198. */
  199. public function isWritable(string $class, string $property, array $context = []): ?bool
  200. {
  201. if ($this->isAllowedProperty($class, $property)) {
  202. return true;
  203. }
  204. [$reflectionMethod] = $this->getMutatorMethod($class, $property);
  205. return null !== $reflectionMethod;
  206. }
  207. /**
  208. * {@inheritdoc}
  209. */
  210. public function isInitializable(string $class, string $property, array $context = []): ?bool
  211. {
  212. try {
  213. $reflectionClass = new \ReflectionClass($class);
  214. } catch (\ReflectionException $e) {
  215. return null;
  216. }
  217. if (!$reflectionClass->isInstantiable()) {
  218. return false;
  219. }
  220. if ($constructor = $reflectionClass->getConstructor()) {
  221. foreach ($constructor->getParameters() as $parameter) {
  222. if ($property === $parameter->name) {
  223. return true;
  224. }
  225. }
  226. } elseif ($parentClass = $reflectionClass->getParentClass()) {
  227. return $this->isInitializable($parentClass->getName(), $property);
  228. }
  229. return false;
  230. }
  231. /**
  232. * {@inheritdoc}
  233. */
  234. public function getReadInfo(string $class, string $property, array $context = []): ?PropertyReadInfo
  235. {
  236. try {
  237. $reflClass = new \ReflectionClass($class);
  238. } catch (\ReflectionException $e) {
  239. return null;
  240. }
  241. $allowGetterSetter = $context['enable_getter_setter_extraction'] ?? false;
  242. $magicMethods = $context['enable_magic_methods_extraction'] ?? $this->magicMethodsFlags;
  243. $allowMagicCall = (bool) ($magicMethods & self::ALLOW_MAGIC_CALL);
  244. $allowMagicGet = (bool) ($magicMethods & self::ALLOW_MAGIC_GET);
  245. if (isset($context['enable_magic_call_extraction'])) {
  246. trigger_deprecation('symfony/property-info', '5.2', 'Using the "enable_magic_call_extraction" context option in "%s()" is deprecated. Use "enable_magic_methods_extraction" instead.', __METHOD__);
  247. $allowMagicCall = $context['enable_magic_call_extraction'] ?? false;
  248. }
  249. $hasProperty = $reflClass->hasProperty($property);
  250. $camelProp = $this->camelize($property);
  251. $getsetter = lcfirst($camelProp); // jQuery style, e.g. read: last(), write: last($item)
  252. foreach ($this->accessorPrefixes as $prefix) {
  253. $methodName = $prefix.$camelProp;
  254. if ($reflClass->hasMethod($methodName) && $reflClass->getMethod($methodName)->getModifiers() & $this->methodReflectionFlags && !$reflClass->getMethod($methodName)->getNumberOfRequiredParameters()) {
  255. $method = $reflClass->getMethod($methodName);
  256. return new PropertyReadInfo(PropertyReadInfo::TYPE_METHOD, $methodName, $this->getReadVisiblityForMethod($method), $method->isStatic(), false);
  257. }
  258. }
  259. if ($allowGetterSetter && $reflClass->hasMethod($getsetter) && ($reflClass->getMethod($getsetter)->getModifiers() & $this->methodReflectionFlags)) {
  260. $method = $reflClass->getMethod($getsetter);
  261. return new PropertyReadInfo(PropertyReadInfo::TYPE_METHOD, $getsetter, $this->getReadVisiblityForMethod($method), $method->isStatic(), false);
  262. }
  263. if ($hasProperty && ($reflClass->getProperty($property)->getModifiers() & $this->propertyReflectionFlags)) {
  264. $reflProperty = $reflClass->getProperty($property);
  265. return new PropertyReadInfo(PropertyReadInfo::TYPE_PROPERTY, $property, $this->getReadVisiblityForProperty($reflProperty), $reflProperty->isStatic(), true);
  266. }
  267. if ($allowMagicGet && $reflClass->hasMethod('__get') && ($reflClass->getMethod('__get')->getModifiers() & $this->methodReflectionFlags)) {
  268. return new PropertyReadInfo(PropertyReadInfo::TYPE_PROPERTY, $property, PropertyReadInfo::VISIBILITY_PUBLIC, false, false);
  269. }
  270. if ($allowMagicCall && $reflClass->hasMethod('__call') && ($reflClass->getMethod('__call')->getModifiers() & $this->methodReflectionFlags)) {
  271. return new PropertyReadInfo(PropertyReadInfo::TYPE_METHOD, 'get'.$camelProp, PropertyReadInfo::VISIBILITY_PUBLIC, false, false);
  272. }
  273. return null;
  274. }
  275. /**
  276. * {@inheritdoc}
  277. */
  278. public function getWriteInfo(string $class, string $property, array $context = []): ?PropertyWriteInfo
  279. {
  280. try {
  281. $reflClass = new \ReflectionClass($class);
  282. } catch (\ReflectionException $e) {
  283. return null;
  284. }
  285. $allowGetterSetter = $context['enable_getter_setter_extraction'] ?? false;
  286. $magicMethods = $context['enable_magic_methods_extraction'] ?? $this->magicMethodsFlags;
  287. $allowMagicCall = (bool) ($magicMethods & self::ALLOW_MAGIC_CALL);
  288. $allowMagicSet = (bool) ($magicMethods & self::ALLOW_MAGIC_SET);
  289. if (isset($context['enable_magic_call_extraction'])) {
  290. trigger_deprecation('symfony/property-info', '5.2', 'Using the "enable_magic_call_extraction" context option in "%s()" is deprecated. Use "enable_magic_methods_extraction" instead.', __METHOD__);
  291. $allowMagicCall = $context['enable_magic_call_extraction'] ?? false;
  292. }
  293. $allowConstruct = $context['enable_constructor_extraction'] ?? $this->enableConstructorExtraction;
  294. $allowAdderRemover = $context['enable_adder_remover_extraction'] ?? true;
  295. $camelized = $this->camelize($property);
  296. $constructor = $reflClass->getConstructor();
  297. $singulars = $this->inflector->singularize($camelized);
  298. $errors = [];
  299. if (null !== $constructor && $allowConstruct) {
  300. foreach ($constructor->getParameters() as $parameter) {
  301. if ($parameter->getName() === $property) {
  302. return new PropertyWriteInfo(PropertyWriteInfo::TYPE_CONSTRUCTOR, $property);
  303. }
  304. }
  305. }
  306. [$adderAccessName, $removerAccessName, $adderAndRemoverErrors] = $this->findAdderAndRemover($reflClass, $singulars);
  307. if ($allowAdderRemover && null !== $adderAccessName && null !== $removerAccessName) {
  308. $adderMethod = $reflClass->getMethod($adderAccessName);
  309. $removerMethod = $reflClass->getMethod($removerAccessName);
  310. $mutator = new PropertyWriteInfo(PropertyWriteInfo::TYPE_ADDER_AND_REMOVER);
  311. $mutator->setAdderInfo(new PropertyWriteInfo(PropertyWriteInfo::TYPE_METHOD, $adderAccessName, $this->getWriteVisiblityForMethod($adderMethod), $adderMethod->isStatic()));
  312. $mutator->setRemoverInfo(new PropertyWriteInfo(PropertyWriteInfo::TYPE_METHOD, $removerAccessName, $this->getWriteVisiblityForMethod($removerMethod), $removerMethod->isStatic()));
  313. return $mutator;
  314. }
  315. $errors = array_merge($errors, $adderAndRemoverErrors);
  316. foreach ($this->mutatorPrefixes as $mutatorPrefix) {
  317. $methodName = $mutatorPrefix.$camelized;
  318. [$accessible, $methodAccessibleErrors] = $this->isMethodAccessible($reflClass, $methodName, 1);
  319. if (!$accessible) {
  320. $errors = array_merge($errors, $methodAccessibleErrors);
  321. continue;
  322. }
  323. $method = $reflClass->getMethod($methodName);
  324. if (!\in_array($mutatorPrefix, $this->arrayMutatorPrefixes, true)) {
  325. return new PropertyWriteInfo(PropertyWriteInfo::TYPE_METHOD, $methodName, $this->getWriteVisiblityForMethod($method), $method->isStatic());
  326. }
  327. }
  328. $getsetter = lcfirst($camelized);
  329. if ($allowGetterSetter) {
  330. [$accessible, $methodAccessibleErrors] = $this->isMethodAccessible($reflClass, $getsetter, 1);
  331. if ($accessible) {
  332. $method = $reflClass->getMethod($getsetter);
  333. return new PropertyWriteInfo(PropertyWriteInfo::TYPE_METHOD, $getsetter, $this->getWriteVisiblityForMethod($method), $method->isStatic());
  334. }
  335. $errors = array_merge($errors, $methodAccessibleErrors);
  336. }
  337. if ($reflClass->hasProperty($property) && ($reflClass->getProperty($property)->getModifiers() & $this->propertyReflectionFlags)) {
  338. $reflProperty = $reflClass->getProperty($property);
  339. return new PropertyWriteInfo(PropertyWriteInfo::TYPE_PROPERTY, $property, $this->getWriteVisiblityForProperty($reflProperty), $reflProperty->isStatic());
  340. }
  341. if ($allowMagicSet) {
  342. [$accessible, $methodAccessibleErrors] = $this->isMethodAccessible($reflClass, '__set', 2);
  343. if ($accessible) {
  344. return new PropertyWriteInfo(PropertyWriteInfo::TYPE_PROPERTY, $property, PropertyWriteInfo::VISIBILITY_PUBLIC, false);
  345. }
  346. $errors = array_merge($errors, $methodAccessibleErrors);
  347. }
  348. if ($allowMagicCall) {
  349. [$accessible, $methodAccessibleErrors] = $this->isMethodAccessible($reflClass, '__call', 2);
  350. if ($accessible) {
  351. return new PropertyWriteInfo(PropertyWriteInfo::TYPE_METHOD, 'set'.$camelized, PropertyWriteInfo::VISIBILITY_PUBLIC, false);
  352. }
  353. $errors = array_merge($errors, $methodAccessibleErrors);
  354. }
  355. if (!$allowAdderRemover && null !== $adderAccessName && null !== $removerAccessName) {
  356. $errors[] = sprintf(
  357. 'The property "%s" in class "%s" can be defined with the methods "%s()" but '.
  358. 'the new value must be an array or an instance of \Traversable',
  359. $property,
  360. $reflClass->getName(),
  361. implode('()", "', [$adderAccessName, $removerAccessName])
  362. );
  363. }
  364. $noneProperty = new PropertyWriteInfo();
  365. $noneProperty->setErrors($errors);
  366. return $noneProperty;
  367. }
  368. /**
  369. * @return Type[]|null
  370. */
  371. private function extractFromMutator(string $class, string $property): ?array
  372. {
  373. [$reflectionMethod, $prefix] = $this->getMutatorMethod($class, $property);
  374. if (null === $reflectionMethod) {
  375. return null;
  376. }
  377. $reflectionParameters = $reflectionMethod->getParameters();
  378. $reflectionParameter = $reflectionParameters[0];
  379. if (!$reflectionType = $reflectionParameter->getType()) {
  380. return null;
  381. }
  382. $type = $this->extractFromReflectionType($reflectionType, $reflectionMethod->getDeclaringClass());
  383. if (1 === \count($type) && \in_array($prefix, $this->arrayMutatorPrefixes)) {
  384. $type = [new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), $type[0])];
  385. }
  386. return $type;
  387. }
  388. /**
  389. * Tries to extract type information from accessors.
  390. *
  391. * @return Type[]|null
  392. */
  393. private function extractFromAccessor(string $class, string $property): ?array
  394. {
  395. [$reflectionMethod, $prefix] = $this->getAccessorMethod($class, $property);
  396. if (null === $reflectionMethod) {
  397. return null;
  398. }
  399. if ($reflectionType = $reflectionMethod->getReturnType()) {
  400. return $this->extractFromReflectionType($reflectionType, $reflectionMethod->getDeclaringClass());
  401. }
  402. if (\in_array($prefix, ['is', 'can', 'has'])) {
  403. return [new Type(Type::BUILTIN_TYPE_BOOL)];
  404. }
  405. return null;
  406. }
  407. /**
  408. * Tries to extract type information from constructor.
  409. *
  410. * @return Type[]|null
  411. */
  412. private function extractFromConstructor(string $class, string $property): ?array
  413. {
  414. try {
  415. $reflectionClass = new \ReflectionClass($class);
  416. } catch (\ReflectionException $e) {
  417. return null;
  418. }
  419. $constructor = $reflectionClass->getConstructor();
  420. if (!$constructor) {
  421. return null;
  422. }
  423. foreach ($constructor->getParameters() as $parameter) {
  424. if ($property !== $parameter->name) {
  425. continue;
  426. }
  427. $reflectionType = $parameter->getType();
  428. return $reflectionType ? $this->extractFromReflectionType($reflectionType, $constructor->getDeclaringClass()) : null;
  429. }
  430. if ($parentClass = $reflectionClass->getParentClass()) {
  431. return $this->extractFromConstructor($parentClass->getName(), $property);
  432. }
  433. return null;
  434. }
  435. private function extractFromDefaultValue(string $class, string $property): ?array
  436. {
  437. try {
  438. $reflectionClass = new \ReflectionClass($class);
  439. } catch (\ReflectionException $e) {
  440. return null;
  441. }
  442. $defaultValue = $reflectionClass->getDefaultProperties()[$property] ?? null;
  443. if (null === $defaultValue) {
  444. return null;
  445. }
  446. $type = \gettype($defaultValue);
  447. $type = static::MAP_TYPES[$type] ?? $type;
  448. return [new Type($type, false, null, Type::BUILTIN_TYPE_ARRAY === $type)];
  449. }
  450. private function extractFromReflectionType(\ReflectionType $reflectionType, \ReflectionClass $declaringClass): array
  451. {
  452. $types = [];
  453. $nullable = $reflectionType->allowsNull();
  454. foreach ($reflectionType instanceof \ReflectionUnionType ? $reflectionType->getTypes() : [$reflectionType] as $type) {
  455. $phpTypeOrClass = $reflectionType instanceof \ReflectionNamedType ? $reflectionType->getName() : (string) $type;
  456. if ('null' === $phpTypeOrClass || 'mixed' === $phpTypeOrClass) {
  457. continue;
  458. }
  459. if (Type::BUILTIN_TYPE_ARRAY === $phpTypeOrClass) {
  460. $types[] = new Type(Type::BUILTIN_TYPE_ARRAY, $nullable, null, true);
  461. } elseif ('void' === $phpTypeOrClass) {
  462. $types[] = new Type(Type::BUILTIN_TYPE_NULL, $nullable);
  463. } elseif ($type->isBuiltin()) {
  464. $types[] = new Type($phpTypeOrClass, $nullable);
  465. } else {
  466. $types[] = new Type(Type::BUILTIN_TYPE_OBJECT, $nullable, $this->resolveTypeName($phpTypeOrClass, $declaringClass));
  467. }
  468. }
  469. return $types;
  470. }
  471. private function resolveTypeName(string $name, \ReflectionClass $declaringClass): string
  472. {
  473. if ('self' === $lcName = strtolower($name)) {
  474. return $declaringClass->name;
  475. }
  476. if ('parent' === $lcName && $parent = $declaringClass->getParentClass()) {
  477. return $parent->name;
  478. }
  479. return $name;
  480. }
  481. private function isAllowedProperty(string $class, string $property): bool
  482. {
  483. try {
  484. $reflectionProperty = new \ReflectionProperty($class, $property);
  485. return $reflectionProperty->getModifiers() & $this->propertyReflectionFlags;
  486. } catch (\ReflectionException $e) {
  487. // Return false if the property doesn't exist
  488. }
  489. return false;
  490. }
  491. /**
  492. * Gets the accessor method.
  493. *
  494. * Returns an array with a the instance of \ReflectionMethod as first key
  495. * and the prefix of the method as second or null if not found.
  496. */
  497. private function getAccessorMethod(string $class, string $property): ?array
  498. {
  499. $ucProperty = ucfirst($property);
  500. foreach ($this->accessorPrefixes as $prefix) {
  501. try {
  502. $reflectionMethod = new \ReflectionMethod($class, $prefix.$ucProperty);
  503. if ($reflectionMethod->isStatic()) {
  504. continue;
  505. }
  506. if (0 === $reflectionMethod->getNumberOfRequiredParameters()) {
  507. return [$reflectionMethod, $prefix];
  508. }
  509. } catch (\ReflectionException $e) {
  510. // Return null if the property doesn't exist
  511. }
  512. }
  513. return null;
  514. }
  515. /**
  516. * Returns an array with a the instance of \ReflectionMethod as first key
  517. * and the prefix of the method as second or null if not found.
  518. */
  519. private function getMutatorMethod(string $class, string $property): ?array
  520. {
  521. $ucProperty = ucfirst($property);
  522. $ucSingulars = $this->inflector->singularize($ucProperty);
  523. $mutatorPrefixes = \in_array($ucProperty, $ucSingulars, true) ? $this->arrayMutatorPrefixesLast : $this->arrayMutatorPrefixesFirst;
  524. foreach ($mutatorPrefixes as $prefix) {
  525. $names = [$ucProperty];
  526. if (\in_array($prefix, $this->arrayMutatorPrefixes)) {
  527. $names = array_merge($names, $ucSingulars);
  528. }
  529. foreach ($names as $name) {
  530. try {
  531. $reflectionMethod = new \ReflectionMethod($class, $prefix.$name);
  532. if ($reflectionMethod->isStatic()) {
  533. continue;
  534. }
  535. // Parameter can be optional to allow things like: method(array $foo = null)
  536. if ($reflectionMethod->getNumberOfParameters() >= 1) {
  537. return [$reflectionMethod, $prefix];
  538. }
  539. } catch (\ReflectionException $e) {
  540. // Try the next prefix if the method doesn't exist
  541. }
  542. }
  543. }
  544. return null;
  545. }
  546. private function getPropertyName(string $methodName, array $reflectionProperties): ?string
  547. {
  548. $pattern = implode('|', array_merge($this->accessorPrefixes, $this->mutatorPrefixes));
  549. if ('' !== $pattern && preg_match('/^('.$pattern.')(.+)$/i', $methodName, $matches)) {
  550. if (!\in_array($matches[1], $this->arrayMutatorPrefixes)) {
  551. return $matches[2];
  552. }
  553. foreach ($reflectionProperties as $reflectionProperty) {
  554. foreach ($this->inflector->singularize($reflectionProperty->name) as $name) {
  555. if (strtolower($name) === strtolower($matches[2])) {
  556. return $reflectionProperty->name;
  557. }
  558. }
  559. }
  560. return $matches[2];
  561. }
  562. return null;
  563. }
  564. /**
  565. * Searches for add and remove methods.
  566. *
  567. * @param \ReflectionClass $reflClass The reflection class for the given object
  568. * @param array $singulars The singular form of the property name or null
  569. *
  570. * @return array An array containing the adder and remover when found and errors
  571. */
  572. private function findAdderAndRemover(\ReflectionClass $reflClass, array $singulars): array
  573. {
  574. if (!\is_array($this->arrayMutatorPrefixes) && 2 !== \count($this->arrayMutatorPrefixes)) {
  575. return [null, null, []];
  576. }
  577. [$addPrefix, $removePrefix] = $this->arrayMutatorPrefixes;
  578. $errors = [];
  579. foreach ($singulars as $singular) {
  580. $addMethod = $addPrefix.$singular;
  581. $removeMethod = $removePrefix.$singular;
  582. [$addMethodFound, $addMethodAccessibleErrors] = $this->isMethodAccessible($reflClass, $addMethod, 1);
  583. [$removeMethodFound, $removeMethodAccessibleErrors] = $this->isMethodAccessible($reflClass, $removeMethod, 1);
  584. $errors = array_merge($errors, $addMethodAccessibleErrors, $removeMethodAccessibleErrors);
  585. if ($addMethodFound && $removeMethodFound) {
  586. return [$addMethod, $removeMethod, []];
  587. }
  588. if ($addMethodFound && !$removeMethodFound) {
  589. $errors[] = sprintf('The add method "%s" in class "%s" was found, but the corresponding remove method "%s" was not found', $addMethod, $reflClass->getName(), $removeMethod);
  590. } elseif (!$addMethodFound && $removeMethodFound) {
  591. $errors[] = sprintf('The remove method "%s" in class "%s" was found, but the corresponding add method "%s" was not found', $removeMethod, $reflClass->getName(), $addMethod);
  592. }
  593. }
  594. return [null, null, $errors];
  595. }
  596. /**
  597. * Returns whether a method is public and has the number of required parameters and errors.
  598. */
  599. private function isMethodAccessible(\ReflectionClass $class, string $methodName, int $parameters): array
  600. {
  601. $errors = [];
  602. if ($class->hasMethod($methodName)) {
  603. $method = $class->getMethod($methodName);
  604. if (\ReflectionMethod::IS_PUBLIC === $this->methodReflectionFlags && !$method->isPublic()) {
  605. $errors[] = sprintf('The method "%s" in class "%s" was found but does not have public access.', $methodName, $class->getName());
  606. } elseif ($method->getNumberOfRequiredParameters() > $parameters || $method->getNumberOfParameters() < $parameters) {
  607. $errors[] = sprintf('The method "%s" in class "%s" requires %d arguments, but should accept only %d.', $methodName, $class->getName(), $method->getNumberOfRequiredParameters(), $parameters);
  608. } else {
  609. return [true, $errors];
  610. }
  611. }
  612. return [false, $errors];
  613. }
  614. /**
  615. * Camelizes a given string.
  616. */
  617. private function camelize(string $string): string
  618. {
  619. return str_replace(' ', '', ucwords(str_replace('_', ' ', $string)));
  620. }
  621. /**
  622. * Return allowed reflection method flags.
  623. */
  624. private function getMethodsFlags(int $accessFlags): int
  625. {
  626. $methodFlags = 0;
  627. if ($accessFlags & self::ALLOW_PUBLIC) {
  628. $methodFlags |= \ReflectionMethod::IS_PUBLIC;
  629. }
  630. if ($accessFlags & self::ALLOW_PRIVATE) {
  631. $methodFlags |= \ReflectionMethod::IS_PRIVATE;
  632. }
  633. if ($accessFlags & self::ALLOW_PROTECTED) {
  634. $methodFlags |= \ReflectionMethod::IS_PROTECTED;
  635. }
  636. return $methodFlags;
  637. }
  638. /**
  639. * Return allowed reflection property flags.
  640. */
  641. private function getPropertyFlags(int $accessFlags): int
  642. {
  643. $propertyFlags = 0;
  644. if ($accessFlags & self::ALLOW_PUBLIC) {
  645. $propertyFlags |= \ReflectionProperty::IS_PUBLIC;
  646. }
  647. if ($accessFlags & self::ALLOW_PRIVATE) {
  648. $propertyFlags |= \ReflectionProperty::IS_PRIVATE;
  649. }
  650. if ($accessFlags & self::ALLOW_PROTECTED) {
  651. $propertyFlags |= \ReflectionProperty::IS_PROTECTED;
  652. }
  653. return $propertyFlags;
  654. }
  655. private function getReadVisiblityForProperty(\ReflectionProperty $reflectionProperty): string
  656. {
  657. if ($reflectionProperty->isPrivate()) {
  658. return PropertyReadInfo::VISIBILITY_PRIVATE;
  659. }
  660. if ($reflectionProperty->isProtected()) {
  661. return PropertyReadInfo::VISIBILITY_PROTECTED;
  662. }
  663. return PropertyReadInfo::VISIBILITY_PUBLIC;
  664. }
  665. private function getReadVisiblityForMethod(\ReflectionMethod $reflectionMethod): string
  666. {
  667. if ($reflectionMethod->isPrivate()) {
  668. return PropertyReadInfo::VISIBILITY_PRIVATE;
  669. }
  670. if ($reflectionMethod->isProtected()) {
  671. return PropertyReadInfo::VISIBILITY_PROTECTED;
  672. }
  673. return PropertyReadInfo::VISIBILITY_PUBLIC;
  674. }
  675. private function getWriteVisiblityForProperty(\ReflectionProperty $reflectionProperty): string
  676. {
  677. if ($reflectionProperty->isPrivate()) {
  678. return PropertyWriteInfo::VISIBILITY_PRIVATE;
  679. }
  680. if ($reflectionProperty->isProtected()) {
  681. return PropertyWriteInfo::VISIBILITY_PROTECTED;
  682. }
  683. return PropertyWriteInfo::VISIBILITY_PUBLIC;
  684. }
  685. private function getWriteVisiblityForMethod(\ReflectionMethod $reflectionMethod): string
  686. {
  687. if ($reflectionMethod->isPrivate()) {
  688. return PropertyWriteInfo::VISIBILITY_PRIVATE;
  689. }
  690. if ($reflectionMethod->isProtected()) {
  691. return PropertyWriteInfo::VISIBILITY_PROTECTED;
  692. }
  693. return PropertyWriteInfo::VISIBILITY_PUBLIC;
  694. }
  695. }