PropertyAccessor.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  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\PropertyAccess;
  11. use Psr\Cache\CacheItemPoolInterface;
  12. use Psr\Log\LoggerInterface;
  13. use Psr\Log\NullLogger;
  14. use Symfony\Component\Cache\Adapter\AdapterInterface;
  15. use Symfony\Component\Cache\Adapter\ApcuAdapter;
  16. use Symfony\Component\Cache\Adapter\NullAdapter;
  17. use Symfony\Component\PropertyAccess\Exception\AccessException;
  18. use Symfony\Component\PropertyAccess\Exception\InvalidArgumentException;
  19. use Symfony\Component\PropertyAccess\Exception\NoSuchIndexException;
  20. use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException;
  21. use Symfony\Component\PropertyAccess\Exception\UnexpectedTypeException;
  22. use Symfony\Component\PropertyAccess\Exception\UninitializedPropertyException;
  23. use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;
  24. use Symfony\Component\PropertyInfo\PropertyReadInfo;
  25. use Symfony\Component\PropertyInfo\PropertyReadInfoExtractorInterface;
  26. use Symfony\Component\PropertyInfo\PropertyWriteInfo;
  27. use Symfony\Component\PropertyInfo\PropertyWriteInfoExtractorInterface;
  28. /**
  29. * Default implementation of {@link PropertyAccessorInterface}.
  30. *
  31. * @author Bernhard Schussek <bschussek@gmail.com>
  32. * @author Kévin Dunglas <dunglas@gmail.com>
  33. * @author Nicolas Grekas <p@tchwork.com>
  34. */
  35. class PropertyAccessor implements PropertyAccessorInterface
  36. {
  37. /** @var int Allow none of the magic methods */
  38. public const DISALLOW_MAGIC_METHODS = ReflectionExtractor::DISALLOW_MAGIC_METHODS;
  39. /** @var int Allow magic __get methods */
  40. public const MAGIC_GET = ReflectionExtractor::ALLOW_MAGIC_GET;
  41. /** @var int Allow magic __set methods */
  42. public const MAGIC_SET = ReflectionExtractor::ALLOW_MAGIC_SET;
  43. /** @var int Allow magic __call methods */
  44. public const MAGIC_CALL = ReflectionExtractor::ALLOW_MAGIC_CALL;
  45. public const DO_NOT_THROW = 0;
  46. public const THROW_ON_INVALID_INDEX = 1;
  47. public const THROW_ON_INVALID_PROPERTY_PATH = 2;
  48. private const VALUE = 0;
  49. private const REF = 1;
  50. private const IS_REF_CHAINED = 2;
  51. private const CACHE_PREFIX_READ = 'r';
  52. private const CACHE_PREFIX_WRITE = 'w';
  53. private const CACHE_PREFIX_PROPERTY_PATH = 'p';
  54. private $magicMethodsFlags;
  55. private $ignoreInvalidIndices;
  56. private $ignoreInvalidProperty;
  57. /**
  58. * @var CacheItemPoolInterface
  59. */
  60. private $cacheItemPool;
  61. private $propertyPathCache = [];
  62. /**
  63. * @var PropertyReadInfoExtractorInterface
  64. */
  65. private $readInfoExtractor;
  66. /**
  67. * @var PropertyWriteInfoExtractorInterface
  68. */
  69. private $writeInfoExtractor;
  70. private $readPropertyCache = [];
  71. private $writePropertyCache = [];
  72. private const RESULT_PROTO = [self::VALUE => null];
  73. /**
  74. * Should not be used by application code. Use
  75. * {@link PropertyAccess::createPropertyAccessor()} instead.
  76. *
  77. * @param int $magicMethods A bitwise combination of the MAGIC_* constants
  78. * to specify the allowed magic methods (__get, __set, __call)
  79. * or self::DISALLOW_MAGIC_METHODS for none
  80. * @param int $throw A bitwise combination of the THROW_* constants
  81. * to specify when exceptions should be thrown
  82. * @param PropertyReadInfoExtractorInterface $readInfoExtractor
  83. * @param PropertyWriteInfoExtractorInterface $writeInfoExtractor
  84. */
  85. public function __construct($magicMethods = self::MAGIC_GET | self::MAGIC_SET, $throw = self::THROW_ON_INVALID_PROPERTY_PATH, CacheItemPoolInterface $cacheItemPool = null, $readInfoExtractor = null, $writeInfoExtractor = null)
  86. {
  87. if (\is_bool($magicMethods)) {
  88. trigger_deprecation('symfony/property-access', '5.2', 'Passing a boolean as the first argument to "%s()" is deprecated. Pass a combination of bitwise flags instead (i.e an integer).', __METHOD__);
  89. $magicMethods = ($magicMethods ? self::MAGIC_CALL : 0) | self::MAGIC_GET | self::MAGIC_SET;
  90. } elseif (!\is_int($magicMethods)) {
  91. throw new \TypeError(sprintf('Argument 1 passed to "%s()" must be an integer, "%s" given.', __METHOD__, get_debug_type($readInfoExtractor)));
  92. }
  93. if (\is_bool($throw)) {
  94. trigger_deprecation('symfony/property-access', '5.3', 'Passing a boolean as the second argument to "%s()" is deprecated. Pass a combination of bitwise flags instead (i.e an integer).', __METHOD__);
  95. $throw = $throw ? self::THROW_ON_INVALID_INDEX : self::DO_NOT_THROW;
  96. if (!\is_bool($readInfoExtractor)) {
  97. $throw |= self::THROW_ON_INVALID_PROPERTY_PATH;
  98. }
  99. }
  100. if (\is_bool($readInfoExtractor)) {
  101. trigger_deprecation('symfony/property-access', '5.3', 'Passing a boolean as the fourth argument to "%s()" is deprecated. Pass a combination of bitwise flags as the second argument instead (i.e an integer).', __METHOD__);
  102. if ($readInfoExtractor) {
  103. $throw |= self::THROW_ON_INVALID_PROPERTY_PATH;
  104. }
  105. $readInfoExtractor = $writeInfoExtractor;
  106. $writeInfoExtractor = 4 < \func_num_args() ? func_get_arg(4) : null;
  107. }
  108. if (null !== $readInfoExtractor && !$readInfoExtractor instanceof PropertyReadInfoExtractorInterface) {
  109. throw new \TypeError(sprintf('Argument 4 passed to "%s()" must be null or an instance of "%s", "%s" given.', __METHOD__, PropertyReadInfoExtractorInterface::class, get_debug_type($readInfoExtractor)));
  110. }
  111. if (null !== $writeInfoExtractor && !$writeInfoExtractor instanceof PropertyWriteInfoExtractorInterface) {
  112. throw new \TypeError(sprintf('Argument 5 passed to "%s()" must be null or an instance of "%s", "%s" given.', __METHOD__, PropertyWriteInfoExtractorInterface::class, get_debug_type($writeInfoExtractor)));
  113. }
  114. $this->magicMethodsFlags = $magicMethods;
  115. $this->ignoreInvalidIndices = 0 === ($throw & self::THROW_ON_INVALID_INDEX);
  116. $this->cacheItemPool = $cacheItemPool instanceof NullAdapter ? null : $cacheItemPool; // Replace the NullAdapter by the null value
  117. $this->ignoreInvalidProperty = 0 === ($throw & self::THROW_ON_INVALID_PROPERTY_PATH);
  118. $this->readInfoExtractor = $readInfoExtractor ?? new ReflectionExtractor([], null, null, false);
  119. $this->writeInfoExtractor = $writeInfoExtractor ?? new ReflectionExtractor(['set'], null, null, false);
  120. }
  121. /**
  122. * {@inheritdoc}
  123. */
  124. public function getValue($objectOrArray, $propertyPath)
  125. {
  126. $zval = [
  127. self::VALUE => $objectOrArray,
  128. ];
  129. if (\is_object($objectOrArray) && false === strpbrk((string) $propertyPath, '.[')) {
  130. return $this->readProperty($zval, $propertyPath, $this->ignoreInvalidProperty)[self::VALUE];
  131. }
  132. $propertyPath = $this->getPropertyPath($propertyPath);
  133. $propertyValues = $this->readPropertiesUntil($zval, $propertyPath, $propertyPath->getLength(), $this->ignoreInvalidIndices);
  134. return $propertyValues[\count($propertyValues) - 1][self::VALUE];
  135. }
  136. /**
  137. * {@inheritdoc}
  138. */
  139. public function setValue(&$objectOrArray, $propertyPath, $value)
  140. {
  141. if (\is_object($objectOrArray) && false === strpbrk((string) $propertyPath, '.[')) {
  142. $zval = [
  143. self::VALUE => $objectOrArray,
  144. ];
  145. try {
  146. $this->writeProperty($zval, $propertyPath, $value);
  147. return;
  148. } catch (\TypeError $e) {
  149. self::throwInvalidArgumentException($e->getMessage(), $e->getTrace(), 0, $propertyPath, $e);
  150. // It wasn't thrown in this class so rethrow it
  151. throw $e;
  152. }
  153. }
  154. $propertyPath = $this->getPropertyPath($propertyPath);
  155. $zval = [
  156. self::VALUE => $objectOrArray,
  157. self::REF => &$objectOrArray,
  158. ];
  159. $propertyValues = $this->readPropertiesUntil($zval, $propertyPath, $propertyPath->getLength() - 1);
  160. $overwrite = true;
  161. try {
  162. for ($i = \count($propertyValues) - 1; 0 <= $i; --$i) {
  163. $zval = $propertyValues[$i];
  164. unset($propertyValues[$i]);
  165. // You only need set value for current element if:
  166. // 1. it's the parent of the last index element
  167. // OR
  168. // 2. its child is not passed by reference
  169. //
  170. // This may avoid uncessary value setting process for array elements.
  171. // For example:
  172. // '[a][b][c]' => 'old-value'
  173. // If you want to change its value to 'new-value',
  174. // you only need set value for '[a][b][c]' and it's safe to ignore '[a][b]' and '[a]'
  175. if ($overwrite) {
  176. $property = $propertyPath->getElement($i);
  177. if ($propertyPath->isIndex($i)) {
  178. if ($overwrite = !isset($zval[self::REF])) {
  179. $ref = &$zval[self::REF];
  180. $ref = $zval[self::VALUE];
  181. }
  182. $this->writeIndex($zval, $property, $value);
  183. if ($overwrite) {
  184. $zval[self::VALUE] = $zval[self::REF];
  185. }
  186. } else {
  187. $this->writeProperty($zval, $property, $value);
  188. }
  189. // if current element is an object
  190. // OR
  191. // if current element's reference chain is not broken - current element
  192. // as well as all its ancients in the property path are all passed by reference,
  193. // then there is no need to continue the value setting process
  194. if (\is_object($zval[self::VALUE]) || isset($zval[self::IS_REF_CHAINED])) {
  195. break;
  196. }
  197. }
  198. $value = $zval[self::VALUE];
  199. }
  200. } catch (\TypeError $e) {
  201. self::throwInvalidArgumentException($e->getMessage(), $e->getTrace(), 0, $propertyPath, $e);
  202. // It wasn't thrown in this class so rethrow it
  203. throw $e;
  204. }
  205. }
  206. private static function throwInvalidArgumentException(string $message, array $trace, int $i, string $propertyPath, \Throwable $previous = null): void
  207. {
  208. if (!isset($trace[$i]['file']) || __FILE__ !== $trace[$i]['file']) {
  209. return;
  210. }
  211. if (\PHP_VERSION_ID < 80000) {
  212. if (!str_starts_with($message, 'Argument ')) {
  213. return;
  214. }
  215. $pos = strpos($message, $delim = 'must be of the type ') ?: (strpos($message, $delim = 'must be an instance of ') ?: strpos($message, $delim = 'must implement interface '));
  216. $pos += \strlen($delim);
  217. $j = strpos($message, ',', $pos);
  218. $type = substr($message, 2 + $j, strpos($message, ' given', $j) - $j - 2);
  219. $message = substr($message, $pos, $j - $pos);
  220. throw new InvalidArgumentException(sprintf('Expected argument of type "%s", "%s" given at property path "%s".', $message, 'NULL' === $type ? 'null' : $type, $propertyPath), 0, $previous);
  221. }
  222. if (preg_match('/^\S+::\S+\(\): Argument #\d+ \(\$\S+\) must be of type (\S+), (\S+) given/', $message, $matches)) {
  223. [, $expectedType, $actualType] = $matches;
  224. throw new InvalidArgumentException(sprintf('Expected argument of type "%s", "%s" given at property path "%s".', $expectedType, 'NULL' === $actualType ? 'null' : $actualType, $propertyPath), 0, $previous);
  225. }
  226. }
  227. /**
  228. * {@inheritdoc}
  229. */
  230. public function isReadable($objectOrArray, $propertyPath)
  231. {
  232. if (!$propertyPath instanceof PropertyPathInterface) {
  233. $propertyPath = new PropertyPath($propertyPath);
  234. }
  235. try {
  236. $zval = [
  237. self::VALUE => $objectOrArray,
  238. ];
  239. $this->readPropertiesUntil($zval, $propertyPath, $propertyPath->getLength(), $this->ignoreInvalidIndices);
  240. return true;
  241. } catch (AccessException $e) {
  242. return false;
  243. } catch (UnexpectedTypeException $e) {
  244. return false;
  245. }
  246. }
  247. /**
  248. * {@inheritdoc}
  249. */
  250. public function isWritable($objectOrArray, $propertyPath)
  251. {
  252. $propertyPath = $this->getPropertyPath($propertyPath);
  253. try {
  254. $zval = [
  255. self::VALUE => $objectOrArray,
  256. ];
  257. $propertyValues = $this->readPropertiesUntil($zval, $propertyPath, $propertyPath->getLength() - 1);
  258. for ($i = \count($propertyValues) - 1; 0 <= $i; --$i) {
  259. $zval = $propertyValues[$i];
  260. unset($propertyValues[$i]);
  261. if ($propertyPath->isIndex($i)) {
  262. if (!$zval[self::VALUE] instanceof \ArrayAccess && !\is_array($zval[self::VALUE])) {
  263. return false;
  264. }
  265. } else {
  266. if (!$this->isPropertyWritable($zval[self::VALUE], $propertyPath->getElement($i))) {
  267. return false;
  268. }
  269. }
  270. if (\is_object($zval[self::VALUE])) {
  271. return true;
  272. }
  273. }
  274. return true;
  275. } catch (AccessException $e) {
  276. return false;
  277. } catch (UnexpectedTypeException $e) {
  278. return false;
  279. }
  280. }
  281. /**
  282. * Reads the path from an object up to a given path index.
  283. *
  284. * @throws UnexpectedTypeException if a value within the path is neither object nor array
  285. * @throws NoSuchIndexException If a non-existing index is accessed
  286. */
  287. private function readPropertiesUntil(array $zval, PropertyPathInterface $propertyPath, int $lastIndex, bool $ignoreInvalidIndices = true): array
  288. {
  289. if (!\is_object($zval[self::VALUE]) && !\is_array($zval[self::VALUE])) {
  290. throw new UnexpectedTypeException($zval[self::VALUE], $propertyPath, 0);
  291. }
  292. // Add the root object to the list
  293. $propertyValues = [$zval];
  294. for ($i = 0; $i < $lastIndex; ++$i) {
  295. $property = $propertyPath->getElement($i);
  296. $isIndex = $propertyPath->isIndex($i);
  297. if ($isIndex) {
  298. // Create missing nested arrays on demand
  299. if (($zval[self::VALUE] instanceof \ArrayAccess && !$zval[self::VALUE]->offsetExists($property)) ||
  300. (\is_array($zval[self::VALUE]) && !isset($zval[self::VALUE][$property]) && !\array_key_exists($property, $zval[self::VALUE]))
  301. ) {
  302. if (!$ignoreInvalidIndices) {
  303. if (!\is_array($zval[self::VALUE])) {
  304. if (!$zval[self::VALUE] instanceof \Traversable) {
  305. throw new NoSuchIndexException(sprintf('Cannot read index "%s" while trying to traverse path "%s".', $property, (string) $propertyPath));
  306. }
  307. $zval[self::VALUE] = iterator_to_array($zval[self::VALUE]);
  308. }
  309. throw new NoSuchIndexException(sprintf('Cannot read index "%s" while trying to traverse path "%s". Available indices are "%s".', $property, (string) $propertyPath, print_r(array_keys($zval[self::VALUE]), true)));
  310. }
  311. if ($i + 1 < $propertyPath->getLength()) {
  312. if (isset($zval[self::REF])) {
  313. $zval[self::VALUE][$property] = [];
  314. $zval[self::REF] = $zval[self::VALUE];
  315. } else {
  316. $zval[self::VALUE] = [$property => []];
  317. }
  318. }
  319. }
  320. $zval = $this->readIndex($zval, $property);
  321. } else {
  322. $zval = $this->readProperty($zval, $property, $this->ignoreInvalidProperty);
  323. }
  324. // the final value of the path must not be validated
  325. if ($i + 1 < $propertyPath->getLength() && !\is_object($zval[self::VALUE]) && !\is_array($zval[self::VALUE])) {
  326. throw new UnexpectedTypeException($zval[self::VALUE], $propertyPath, $i + 1);
  327. }
  328. if (isset($zval[self::REF]) && (0 === $i || isset($propertyValues[$i - 1][self::IS_REF_CHAINED]))) {
  329. // Set the IS_REF_CHAINED flag to true if:
  330. // current property is passed by reference and
  331. // it is the first element in the property path or
  332. // the IS_REF_CHAINED flag of its parent element is true
  333. // Basically, this flag is true only when the reference chain from the top element to current element is not broken
  334. $zval[self::IS_REF_CHAINED] = true;
  335. }
  336. $propertyValues[] = $zval;
  337. }
  338. return $propertyValues;
  339. }
  340. /**
  341. * Reads a key from an array-like structure.
  342. *
  343. * @param string|int $index The key to read
  344. *
  345. * @throws NoSuchIndexException If the array does not implement \ArrayAccess or it is not an array
  346. */
  347. private function readIndex(array $zval, $index): array
  348. {
  349. if (!$zval[self::VALUE] instanceof \ArrayAccess && !\is_array($zval[self::VALUE])) {
  350. throw new NoSuchIndexException(sprintf('Cannot read index "%s" from object of type "%s" because it doesn\'t implement \ArrayAccess.', $index, get_debug_type($zval[self::VALUE])));
  351. }
  352. $result = self::RESULT_PROTO;
  353. if (isset($zval[self::VALUE][$index])) {
  354. $result[self::VALUE] = $zval[self::VALUE][$index];
  355. if (!isset($zval[self::REF])) {
  356. // Save creating references when doing read-only lookups
  357. } elseif (\is_array($zval[self::VALUE])) {
  358. $result[self::REF] = &$zval[self::REF][$index];
  359. } elseif (\is_object($result[self::VALUE])) {
  360. $result[self::REF] = $result[self::VALUE];
  361. }
  362. }
  363. return $result;
  364. }
  365. /**
  366. * Reads the a property from an object.
  367. *
  368. * @throws NoSuchPropertyException If $ignoreInvalidProperty is false and the property does not exist or is not public
  369. */
  370. private function readProperty(array $zval, string $property, bool $ignoreInvalidProperty = false): array
  371. {
  372. if (!\is_object($zval[self::VALUE])) {
  373. throw new NoSuchPropertyException(sprintf('Cannot read property "%s" from an array. Maybe you intended to write the property path as "[%1$s]" instead.', $property));
  374. }
  375. $result = self::RESULT_PROTO;
  376. $object = $zval[self::VALUE];
  377. $class = \get_class($object);
  378. $access = $this->getReadInfo($class, $property);
  379. if (null !== $access) {
  380. $name = $access->getName();
  381. $type = $access->getType();
  382. try {
  383. if (PropertyReadInfo::TYPE_METHOD === $type) {
  384. try {
  385. $result[self::VALUE] = $object->$name();
  386. } catch (\TypeError $e) {
  387. [$trace] = $e->getTrace();
  388. // handle uninitialized properties in PHP >= 7
  389. if (__FILE__ === $trace['file']
  390. && $name === $trace['function']
  391. && $object instanceof $trace['class']
  392. && preg_match('/Return value (?:of .*::\w+\(\) )?must be of (?:the )?type (\w+), null returned$/', $e->getMessage(), $matches)
  393. ) {
  394. throw new UninitializedPropertyException(sprintf('The method "%s::%s()" returned "null", but expected type "%3$s". Did you forget to initialize a property or to make the return type nullable using "?%3$s"?', !str_contains(\get_class($object), "@anonymous\0") ? \get_class($object) : (get_parent_class($object) ?: key(class_implements($object)) ?: 'class').'@anonymous', $name, $matches[1]), 0, $e);
  395. }
  396. throw $e;
  397. }
  398. } elseif (PropertyReadInfo::TYPE_PROPERTY === $type) {
  399. $result[self::VALUE] = $object->$name;
  400. if (isset($zval[self::REF]) && $access->canBeReference()) {
  401. $result[self::REF] = &$object->$name;
  402. }
  403. }
  404. } catch (\Error $e) {
  405. // handle uninitialized properties in PHP >= 7.4
  406. if (\PHP_VERSION_ID >= 70400 && preg_match('/^Typed property ([\w\\\]+)::\$(\w+) must not be accessed before initialization$/', $e->getMessage(), $matches)) {
  407. $r = new \ReflectionProperty($matches[1], $matches[2]);
  408. $type = ($type = $r->getType()) instanceof \ReflectionNamedType ? $type->getName() : (string) $type;
  409. throw new UninitializedPropertyException(sprintf('The property "%s::$%s" is not readable because it is typed "%s". You should initialize it or declare a default value instead.', $r->getDeclaringClass()->getName(), $r->getName(), $type), 0, $e);
  410. }
  411. throw $e;
  412. }
  413. } elseif ($object instanceof \stdClass && property_exists($object, $property)) {
  414. $result[self::VALUE] = $object->$property;
  415. if (isset($zval[self::REF])) {
  416. $result[self::REF] = &$object->$property;
  417. }
  418. } elseif (!$ignoreInvalidProperty) {
  419. throw new NoSuchPropertyException(sprintf('Can\'t get a way to read the property "%s" in class "%s".', $property, $class));
  420. }
  421. // Objects are always passed around by reference
  422. if (isset($zval[self::REF]) && \is_object($result[self::VALUE])) {
  423. $result[self::REF] = $result[self::VALUE];
  424. }
  425. return $result;
  426. }
  427. /**
  428. * Guesses how to read the property value.
  429. */
  430. private function getReadInfo(string $class, string $property): ?PropertyReadInfo
  431. {
  432. $key = str_replace('\\', '.', $class).'..'.$property;
  433. if (isset($this->readPropertyCache[$key])) {
  434. return $this->readPropertyCache[$key];
  435. }
  436. if ($this->cacheItemPool) {
  437. $item = $this->cacheItemPool->getItem(self::CACHE_PREFIX_READ.rawurlencode($key));
  438. if ($item->isHit()) {
  439. return $this->readPropertyCache[$key] = $item->get();
  440. }
  441. }
  442. $accessor = $this->readInfoExtractor->getReadInfo($class, $property, [
  443. 'enable_getter_setter_extraction' => true,
  444. 'enable_magic_methods_extraction' => $this->magicMethodsFlags,
  445. 'enable_constructor_extraction' => false,
  446. ]);
  447. if (isset($item)) {
  448. $this->cacheItemPool->save($item->set($accessor));
  449. }
  450. return $this->readPropertyCache[$key] = $accessor;
  451. }
  452. /**
  453. * Sets the value of an index in a given array-accessible value.
  454. *
  455. * @param string|int $index The index to write at
  456. * @param mixed $value The value to write
  457. *
  458. * @throws NoSuchIndexException If the array does not implement \ArrayAccess or it is not an array
  459. */
  460. private function writeIndex(array $zval, $index, $value)
  461. {
  462. if (!$zval[self::VALUE] instanceof \ArrayAccess && !\is_array($zval[self::VALUE])) {
  463. throw new NoSuchIndexException(sprintf('Cannot modify index "%s" in object of type "%s" because it doesn\'t implement \ArrayAccess.', $index, get_debug_type($zval[self::VALUE])));
  464. }
  465. $zval[self::REF][$index] = $value;
  466. }
  467. /**
  468. * Sets the value of a property in the given object.
  469. *
  470. * @param mixed $value The value to write
  471. *
  472. * @throws NoSuchPropertyException if the property does not exist or is not public
  473. */
  474. private function writeProperty(array $zval, string $property, $value)
  475. {
  476. if (!\is_object($zval[self::VALUE])) {
  477. throw new NoSuchPropertyException(sprintf('Cannot write property "%s" to an array. Maybe you should write the property path as "[%1$s]" instead?', $property));
  478. }
  479. $object = $zval[self::VALUE];
  480. $class = \get_class($object);
  481. $mutator = $this->getWriteInfo($class, $property, $value);
  482. if (PropertyWriteInfo::TYPE_NONE !== $mutator->getType()) {
  483. $type = $mutator->getType();
  484. if (PropertyWriteInfo::TYPE_METHOD === $type) {
  485. $object->{$mutator->getName()}($value);
  486. } elseif (PropertyWriteInfo::TYPE_PROPERTY === $type) {
  487. $object->{$mutator->getName()} = $value;
  488. } elseif (PropertyWriteInfo::TYPE_ADDER_AND_REMOVER === $type) {
  489. $this->writeCollection($zval, $property, $value, $mutator->getAdderInfo(), $mutator->getRemoverInfo());
  490. }
  491. } elseif ($object instanceof \stdClass && property_exists($object, $property)) {
  492. $object->$property = $value;
  493. } elseif (!$this->ignoreInvalidProperty) {
  494. if ($mutator->hasErrors()) {
  495. throw new NoSuchPropertyException(implode('. ', $mutator->getErrors()).'.');
  496. }
  497. throw new NoSuchPropertyException(sprintf('Could not determine access type for property "%s" in class "%s".', $property, get_debug_type($object)));
  498. }
  499. }
  500. /**
  501. * Adjusts a collection-valued property by calling add*() and remove*() methods.
  502. */
  503. private function writeCollection(array $zval, string $property, iterable $collection, PropertyWriteInfo $addMethod, PropertyWriteInfo $removeMethod)
  504. {
  505. // At this point the add and remove methods have been found
  506. $previousValue = $this->readProperty($zval, $property);
  507. $previousValue = $previousValue[self::VALUE];
  508. $removeMethodName = $removeMethod->getName();
  509. $addMethodName = $addMethod->getName();
  510. if ($previousValue instanceof \Traversable) {
  511. $previousValue = iterator_to_array($previousValue);
  512. }
  513. if ($previousValue && \is_array($previousValue)) {
  514. if (\is_object($collection)) {
  515. $collection = iterator_to_array($collection);
  516. }
  517. foreach ($previousValue as $key => $item) {
  518. if (!\in_array($item, $collection, true)) {
  519. unset($previousValue[$key]);
  520. $zval[self::VALUE]->$removeMethodName($item);
  521. }
  522. }
  523. } else {
  524. $previousValue = false;
  525. }
  526. foreach ($collection as $item) {
  527. if (!$previousValue || !\in_array($item, $previousValue, true)) {
  528. $zval[self::VALUE]->$addMethodName($item);
  529. }
  530. }
  531. }
  532. private function getWriteInfo(string $class, string $property, $value): PropertyWriteInfo
  533. {
  534. $useAdderAndRemover = is_iterable($value);
  535. $key = str_replace('\\', '.', $class).'..'.$property.'..'.(int) $useAdderAndRemover;
  536. if (isset($this->writePropertyCache[$key])) {
  537. return $this->writePropertyCache[$key];
  538. }
  539. if ($this->cacheItemPool) {
  540. $item = $this->cacheItemPool->getItem(self::CACHE_PREFIX_WRITE.rawurlencode($key));
  541. if ($item->isHit()) {
  542. return $this->writePropertyCache[$key] = $item->get();
  543. }
  544. }
  545. $mutator = $this->writeInfoExtractor->getWriteInfo($class, $property, [
  546. 'enable_getter_setter_extraction' => true,
  547. 'enable_magic_methods_extraction' => $this->magicMethodsFlags,
  548. 'enable_constructor_extraction' => false,
  549. 'enable_adder_remover_extraction' => $useAdderAndRemover,
  550. ]);
  551. if (isset($item)) {
  552. $this->cacheItemPool->save($item->set($mutator));
  553. }
  554. return $this->writePropertyCache[$key] = $mutator;
  555. }
  556. /**
  557. * Returns whether a property is writable in the given object.
  558. */
  559. private function isPropertyWritable(object $object, string $property): bool
  560. {
  561. if (!\is_object($object)) {
  562. return false;
  563. }
  564. $mutatorForArray = $this->getWriteInfo(\get_class($object), $property, []);
  565. if (PropertyWriteInfo::TYPE_NONE !== $mutatorForArray->getType() || ($object instanceof \stdClass && property_exists($object, $property))) {
  566. return true;
  567. }
  568. $mutator = $this->getWriteInfo(\get_class($object), $property, '');
  569. return PropertyWriteInfo::TYPE_NONE !== $mutator->getType() || ($object instanceof \stdClass && property_exists($object, $property));
  570. }
  571. /**
  572. * Gets a PropertyPath instance and caches it.
  573. *
  574. * @param string|PropertyPath $propertyPath
  575. */
  576. private function getPropertyPath($propertyPath): PropertyPath
  577. {
  578. if ($propertyPath instanceof PropertyPathInterface) {
  579. // Don't call the copy constructor has it is not needed here
  580. return $propertyPath;
  581. }
  582. if (isset($this->propertyPathCache[$propertyPath])) {
  583. return $this->propertyPathCache[$propertyPath];
  584. }
  585. if ($this->cacheItemPool) {
  586. $item = $this->cacheItemPool->getItem(self::CACHE_PREFIX_PROPERTY_PATH.rawurlencode($propertyPath));
  587. if ($item->isHit()) {
  588. return $this->propertyPathCache[$propertyPath] = $item->get();
  589. }
  590. }
  591. $propertyPathInstance = new PropertyPath($propertyPath);
  592. if (isset($item)) {
  593. $item->set($propertyPathInstance);
  594. $this->cacheItemPool->save($item);
  595. }
  596. return $this->propertyPathCache[$propertyPath] = $propertyPathInstance;
  597. }
  598. /**
  599. * Creates the APCu adapter if applicable.
  600. *
  601. * @return AdapterInterface
  602. *
  603. * @throws \LogicException When the Cache Component isn't available
  604. */
  605. public static function createCache(string $namespace, int $defaultLifetime, string $version, LoggerInterface $logger = null)
  606. {
  607. if (!class_exists(ApcuAdapter::class)) {
  608. throw new \LogicException(sprintf('The Symfony Cache component must be installed to use "%s()".', __METHOD__));
  609. }
  610. if (!ApcuAdapter::isSupported()) {
  611. return new NullAdapter();
  612. }
  613. $apcu = new ApcuAdapter($namespace, $defaultLifetime / 5, $version);
  614. if ('cli' === \PHP_SAPI && !filter_var(ini_get('apc.enable_cli'), \FILTER_VALIDATE_BOOLEAN)) {
  615. $apcu->setLogger(new NullLogger());
  616. } elseif (null !== $logger) {
  617. $apcu->setLogger($logger);
  618. }
  619. return $apcu;
  620. }
  621. }