PropertyAccessor.php 27 KB

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