PropertyAccessor.php 31 KB

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