PropertyAccessor.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817
  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 Symfony\Component\PropertyAccess\Exception\AccessException;
  12. use Symfony\Component\PropertyAccess\Exception\InvalidArgumentException;
  13. use Symfony\Component\PropertyAccess\Exception\NoSuchIndexException;
  14. use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException;
  15. use Symfony\Component\PropertyAccess\Exception\UnexpectedTypeException;
  16. /**
  17. * Default implementation of {@link PropertyAccessorInterface}.
  18. *
  19. * @author Bernhard Schussek <bschussek@gmail.com>
  20. * @author Kévin Dunglas <dunglas@gmail.com>
  21. * @author Nicolas Grekas <p@tchwork.com>
  22. */
  23. class PropertyAccessor implements PropertyAccessorInterface
  24. {
  25. /**
  26. * @internal
  27. */
  28. const VALUE = 0;
  29. /**
  30. * @internal
  31. */
  32. const REF = 1;
  33. /**
  34. * @internal
  35. */
  36. const IS_REF_CHAINED = 2;
  37. /**
  38. * @internal
  39. */
  40. const ACCESS_HAS_PROPERTY = 0;
  41. /**
  42. * @internal
  43. */
  44. const ACCESS_TYPE = 1;
  45. /**
  46. * @internal
  47. */
  48. const ACCESS_NAME = 2;
  49. /**
  50. * @internal
  51. */
  52. const ACCESS_REF = 3;
  53. /**
  54. * @internal
  55. */
  56. const ACCESS_ADDER = 4;
  57. /**
  58. * @internal
  59. */
  60. const ACCESS_REMOVER = 5;
  61. /**
  62. * @internal
  63. */
  64. const ACCESS_TYPE_METHOD = 0;
  65. /**
  66. * @internal
  67. */
  68. const ACCESS_TYPE_PROPERTY = 1;
  69. /**
  70. * @internal
  71. */
  72. const ACCESS_TYPE_MAGIC = 2;
  73. /**
  74. * @internal
  75. */
  76. const ACCESS_TYPE_ADDER_AND_REMOVER = 3;
  77. /**
  78. * @internal
  79. */
  80. const ACCESS_TYPE_NOT_FOUND = 4;
  81. private $magicCall;
  82. private $ignoreInvalidIndices;
  83. private $readPropertyCache = array();
  84. private $writePropertyCache = array();
  85. private static $previousErrorHandler = false;
  86. private static $errorHandler = array(__CLASS__, 'handleError');
  87. private static $resultProto = array(self::VALUE => null);
  88. /**
  89. * Should not be used by application code. Use
  90. * {@link PropertyAccess::createPropertyAccessor()} instead.
  91. *
  92. * @param bool $magicCall
  93. * @param bool $throwExceptionOnInvalidIndex
  94. */
  95. public function __construct($magicCall = false, $throwExceptionOnInvalidIndex = false)
  96. {
  97. $this->magicCall = $magicCall;
  98. $this->ignoreInvalidIndices = !$throwExceptionOnInvalidIndex;
  99. }
  100. /**
  101. * {@inheritdoc}
  102. */
  103. public function getValue($objectOrArray, $propertyPath)
  104. {
  105. if (!$propertyPath instanceof PropertyPathInterface) {
  106. $propertyPath = new PropertyPath($propertyPath);
  107. }
  108. $zval = array(
  109. self::VALUE => $objectOrArray,
  110. );
  111. $propertyValues = $this->readPropertiesUntil($zval, $propertyPath, $propertyPath->getLength(), $this->ignoreInvalidIndices);
  112. return $propertyValues[count($propertyValues) - 1][self::VALUE];
  113. }
  114. /**
  115. * {@inheritdoc}
  116. */
  117. public function setValue(&$objectOrArray, $propertyPath, $value)
  118. {
  119. if (!$propertyPath instanceof PropertyPathInterface) {
  120. $propertyPath = new PropertyPath($propertyPath);
  121. }
  122. $zval = array(
  123. self::VALUE => $objectOrArray,
  124. self::REF => &$objectOrArray,
  125. );
  126. $propertyValues = $this->readPropertiesUntil($zval, $propertyPath, $propertyPath->getLength() - 1);
  127. $overwrite = true;
  128. try {
  129. if (\PHP_VERSION_ID < 70000 && false === self::$previousErrorHandler) {
  130. self::$previousErrorHandler = set_error_handler(self::$errorHandler);
  131. }
  132. for ($i = count($propertyValues) - 1; 0 <= $i; --$i) {
  133. $zval = $propertyValues[$i];
  134. unset($propertyValues[$i]);
  135. // You only need set value for current element if:
  136. // 1. it's the parent of the last index element
  137. // OR
  138. // 2. its child is not passed by reference
  139. //
  140. // This may avoid uncessary value setting process for array elements.
  141. // For example:
  142. // '[a][b][c]' => 'old-value'
  143. // If you want to change its value to 'new-value',
  144. // you only need set value for '[a][b][c]' and it's safe to ignore '[a][b]' and '[a]'
  145. //
  146. if ($overwrite) {
  147. $property = $propertyPath->getElement($i);
  148. if ($propertyPath->isIndex($i)) {
  149. if ($overwrite = !isset($zval[self::REF])) {
  150. $ref = &$zval[self::REF];
  151. $ref = $zval[self::VALUE];
  152. }
  153. $this->writeIndex($zval, $property, $value);
  154. if ($overwrite) {
  155. $zval[self::VALUE] = $zval[self::REF];
  156. }
  157. } else {
  158. $this->writeProperty($zval, $property, $value);
  159. }
  160. // if current element is an object
  161. // OR
  162. // if current element's reference chain is not broken - current element
  163. // as well as all its ancients in the property path are all passed by reference,
  164. // then there is no need to continue the value setting process
  165. if (is_object($zval[self::VALUE]) || isset($zval[self::IS_REF_CHAINED])) {
  166. break;
  167. }
  168. }
  169. $value = $zval[self::VALUE];
  170. }
  171. } catch (\TypeError $e) {
  172. try {
  173. self::throwInvalidArgumentException($e->getMessage(), $e->getTrace(), 0);
  174. } catch (InvalidArgumentException $e) {
  175. }
  176. } catch (\Exception $e) {
  177. } catch (\Throwable $e) {
  178. }
  179. if (\PHP_VERSION_ID < 70000 && false !== self::$previousErrorHandler) {
  180. restore_error_handler();
  181. self::$previousErrorHandler = false;
  182. }
  183. if (isset($e)) {
  184. throw $e;
  185. }
  186. }
  187. /**
  188. * @internal
  189. */
  190. public static function handleError($type, $message, $file, $line, $context)
  191. {
  192. if (E_RECOVERABLE_ERROR === $type) {
  193. self::throwInvalidArgumentException($message, debug_backtrace(false), 1);
  194. }
  195. return null !== self::$previousErrorHandler && false !== call_user_func(self::$previousErrorHandler, $type, $message, $file, $line, $context);
  196. }
  197. private static function throwInvalidArgumentException($message, $trace, $i)
  198. {
  199. if (isset($trace[$i]['file']) && __FILE__ === $trace[$i]['file'] && isset($trace[$i]['args'][0])) {
  200. $pos = strpos($message, $delim = 'must be of the type ') ?: (strpos($message, $delim = 'must be an instance of ') ?: strpos($message, $delim = 'must implement interface '));
  201. $pos += strlen($delim);
  202. $type = $trace[$i]['args'][0];
  203. $type = is_object($type) ? get_class($type) : gettype($type);
  204. throw new InvalidArgumentException(sprintf('Expected argument of type "%s", "%s" given', substr($message, $pos, strpos($message, ',', $pos) - $pos), $type));
  205. }
  206. }
  207. /**
  208. * {@inheritdoc}
  209. */
  210. public function isReadable($objectOrArray, $propertyPath)
  211. {
  212. if (!$propertyPath instanceof PropertyPathInterface) {
  213. $propertyPath = new PropertyPath($propertyPath);
  214. }
  215. try {
  216. $zval = array(
  217. self::VALUE => $objectOrArray,
  218. );
  219. $this->readPropertiesUntil($zval, $propertyPath, $propertyPath->getLength(), $this->ignoreInvalidIndices);
  220. return true;
  221. } catch (AccessException $e) {
  222. return false;
  223. } catch (UnexpectedTypeException $e) {
  224. return false;
  225. }
  226. }
  227. /**
  228. * {@inheritdoc}
  229. */
  230. public function isWritable($objectOrArray, $propertyPath)
  231. {
  232. if (!$propertyPath instanceof PropertyPathInterface) {
  233. $propertyPath = new PropertyPath($propertyPath);
  234. }
  235. try {
  236. $zval = array(
  237. self::VALUE => $objectOrArray,
  238. );
  239. $propertyValues = $this->readPropertiesUntil($zval, $propertyPath, $propertyPath->getLength() - 1);
  240. for ($i = count($propertyValues) - 1; 0 <= $i; --$i) {
  241. $zval = $propertyValues[$i];
  242. unset($propertyValues[$i]);
  243. if ($propertyPath->isIndex($i)) {
  244. if (!$zval[self::VALUE] instanceof \ArrayAccess && !is_array($zval[self::VALUE])) {
  245. return false;
  246. }
  247. } else {
  248. if (!$this->isPropertyWritable($zval[self::VALUE], $propertyPath->getElement($i))) {
  249. return false;
  250. }
  251. }
  252. if (is_object($zval[self::VALUE])) {
  253. return true;
  254. }
  255. }
  256. return true;
  257. } catch (AccessException $e) {
  258. return false;
  259. } catch (UnexpectedTypeException $e) {
  260. return false;
  261. }
  262. }
  263. /**
  264. * Reads the path from an object up to a given path index.
  265. *
  266. * @param array $zval The array containing the object or array to read from
  267. * @param PropertyPathInterface $propertyPath The property path to read
  268. * @param int $lastIndex The index up to which should be read
  269. * @param bool $ignoreInvalidIndices Whether to ignore invalid indices or throw an exception
  270. *
  271. * @return array The values read in the path
  272. *
  273. * @throws UnexpectedTypeException if a value within the path is neither object nor array
  274. * @throws NoSuchIndexException If a non-existing index is accessed
  275. */
  276. private function readPropertiesUntil($zval, PropertyPathInterface $propertyPath, $lastIndex, $ignoreInvalidIndices = true)
  277. {
  278. if (!is_object($zval[self::VALUE]) && !is_array($zval[self::VALUE])) {
  279. throw new UnexpectedTypeException($zval[self::VALUE], $propertyPath, 0);
  280. }
  281. // Add the root object to the list
  282. $propertyValues = array($zval);
  283. for ($i = 0; $i < $lastIndex; ++$i) {
  284. $property = $propertyPath->getElement($i);
  285. $isIndex = $propertyPath->isIndex($i);
  286. if ($isIndex) {
  287. // Create missing nested arrays on demand
  288. if (($zval[self::VALUE] instanceof \ArrayAccess && !$zval[self::VALUE]->offsetExists($property)) ||
  289. (is_array($zval[self::VALUE]) && !isset($zval[self::VALUE][$property]) && !array_key_exists($property, $zval[self::VALUE]))
  290. ) {
  291. if (!$ignoreInvalidIndices) {
  292. if (!is_array($zval[self::VALUE])) {
  293. if (!$zval[self::VALUE] instanceof \Traversable) {
  294. throw new NoSuchIndexException(sprintf(
  295. 'Cannot read index "%s" while trying to traverse path "%s".',
  296. $property,
  297. (string) $propertyPath
  298. ));
  299. }
  300. $zval[self::VALUE] = iterator_to_array($zval[self::VALUE]);
  301. }
  302. throw new NoSuchIndexException(sprintf(
  303. 'Cannot read index "%s" while trying to traverse path "%s". Available indices are "%s".',
  304. $property,
  305. (string) $propertyPath,
  306. print_r(array_keys($zval[self::VALUE]), true)
  307. ));
  308. }
  309. if ($i + 1 < $propertyPath->getLength()) {
  310. if (isset($zval[self::REF])) {
  311. $zval[self::VALUE][$property] = array();
  312. $zval[self::REF] = $zval[self::VALUE];
  313. } else {
  314. $zval[self::VALUE] = array($property => array());
  315. }
  316. }
  317. }
  318. $zval = $this->readIndex($zval, $property);
  319. } else {
  320. $zval = $this->readProperty($zval, $property);
  321. }
  322. // the final value of the path must not be validated
  323. if ($i + 1 < $propertyPath->getLength() && !is_object($zval[self::VALUE]) && !is_array($zval[self::VALUE])) {
  324. throw new UnexpectedTypeException($zval[self::VALUE], $propertyPath, $i + 1);
  325. }
  326. if (isset($zval[self::REF]) && (0 === $i || isset($propertyValues[$i - 1][self::IS_REF_CHAINED]))) {
  327. // Set the IS_REF_CHAINED flag to true if:
  328. // current property is passed by reference and
  329. // it is the first element in the property path or
  330. // the IS_REF_CHAINED flag of its parent element is true
  331. // Basically, this flag is true only when the reference chain from the top element to current element is not broken
  332. $zval[self::IS_REF_CHAINED] = true;
  333. }
  334. $propertyValues[] = $zval;
  335. }
  336. return $propertyValues;
  337. }
  338. /**
  339. * Reads a key from an array-like structure.
  340. *
  341. * @param array $zval The array containing the array or \ArrayAccess object to read from
  342. * @param string|int $index The key to read
  343. *
  344. * @return array The array containing the value of the key
  345. *
  346. * @throws NoSuchIndexException If the array does not implement \ArrayAccess or it is not an array
  347. */
  348. private function readIndex($zval, $index)
  349. {
  350. if (!$zval[self::VALUE] instanceof \ArrayAccess && !is_array($zval[self::VALUE])) {
  351. throw new NoSuchIndexException(sprintf('Cannot read index "%s" from object of type "%s" because it doesn\'t implement \ArrayAccess.', $index, get_class($zval[self::VALUE])));
  352. }
  353. $result = self::$resultProto;
  354. if (isset($zval[self::VALUE][$index])) {
  355. $result[self::VALUE] = $zval[self::VALUE][$index];
  356. if (!isset($zval[self::REF])) {
  357. // Save creating references when doing read-only lookups
  358. } elseif (is_array($zval[self::VALUE])) {
  359. $result[self::REF] = &$zval[self::REF][$index];
  360. } elseif (is_object($result[self::VALUE])) {
  361. $result[self::REF] = $result[self::VALUE];
  362. }
  363. }
  364. return $result;
  365. }
  366. /**
  367. * Reads the a property from an object.
  368. *
  369. * @param array $zval The array containing the object to read from
  370. * @param string $property The property to read
  371. *
  372. * @return array The array containing the value of the property
  373. *
  374. * @throws NoSuchPropertyException if the property does not exist or is not public
  375. */
  376. private function readProperty($zval, $property)
  377. {
  378. if (!is_object($zval[self::VALUE])) {
  379. throw new NoSuchPropertyException(sprintf('Cannot read property "%s" from an array. Maybe you intended to write the property path as "[%1$s]" instead.', $property));
  380. }
  381. $result = self::$resultProto;
  382. $object = $zval[self::VALUE];
  383. $access = $this->getReadAccessInfo(get_class($object), $property);
  384. if (self::ACCESS_TYPE_METHOD === $access[self::ACCESS_TYPE]) {
  385. $result[self::VALUE] = $object->{$access[self::ACCESS_NAME]}();
  386. } elseif (self::ACCESS_TYPE_PROPERTY === $access[self::ACCESS_TYPE]) {
  387. $result[self::VALUE] = $object->{$access[self::ACCESS_NAME]};
  388. if ($access[self::ACCESS_REF] && isset($zval[self::REF])) {
  389. $result[self::REF] = &$object->{$access[self::ACCESS_NAME]};
  390. }
  391. } elseif (!$access[self::ACCESS_HAS_PROPERTY] && property_exists($object, $property)) {
  392. // Needed to support \stdClass instances. We need to explicitly
  393. // exclude $access[self::ACCESS_HAS_PROPERTY], otherwise if
  394. // a *protected* property was found on the class, property_exists()
  395. // returns true, consequently the following line will result in a
  396. // fatal error.
  397. $result[self::VALUE] = $object->$property;
  398. if (isset($zval[self::REF])) {
  399. $result[self::REF] = &$object->$property;
  400. }
  401. } elseif (self::ACCESS_TYPE_MAGIC === $access[self::ACCESS_TYPE]) {
  402. // we call the getter and hope the __call do the job
  403. $result[self::VALUE] = $object->{$access[self::ACCESS_NAME]}();
  404. } else {
  405. throw new NoSuchPropertyException($access[self::ACCESS_NAME]);
  406. }
  407. // Objects are always passed around by reference
  408. if (isset($zval[self::REF]) && is_object($result[self::VALUE])) {
  409. $result[self::REF] = $result[self::VALUE];
  410. }
  411. return $result;
  412. }
  413. /**
  414. * Guesses how to read the property value.
  415. *
  416. * @param string $class
  417. * @param string $property
  418. *
  419. * @return array
  420. */
  421. private function getReadAccessInfo($class, $property)
  422. {
  423. $key = $class.'::'.$property;
  424. if (isset($this->readPropertyCache[$key])) {
  425. $access = $this->readPropertyCache[$key];
  426. } else {
  427. $access = array();
  428. $reflClass = new \ReflectionClass($class);
  429. $access[self::ACCESS_HAS_PROPERTY] = $reflClass->hasProperty($property);
  430. $camelProp = $this->camelize($property);
  431. $getter = 'get'.$camelProp;
  432. $getsetter = lcfirst($camelProp); // jQuery style, e.g. read: last(), write: last($item)
  433. $isser = 'is'.$camelProp;
  434. $hasser = 'has'.$camelProp;
  435. if ($reflClass->hasMethod($getter) && $reflClass->getMethod($getter)->isPublic()) {
  436. $access[self::ACCESS_TYPE] = self::ACCESS_TYPE_METHOD;
  437. $access[self::ACCESS_NAME] = $getter;
  438. } elseif ($reflClass->hasMethod($getsetter) && $reflClass->getMethod($getsetter)->isPublic()) {
  439. $access[self::ACCESS_TYPE] = self::ACCESS_TYPE_METHOD;
  440. $access[self::ACCESS_NAME] = $getsetter;
  441. } elseif ($reflClass->hasMethod($isser) && $reflClass->getMethod($isser)->isPublic()) {
  442. $access[self::ACCESS_TYPE] = self::ACCESS_TYPE_METHOD;
  443. $access[self::ACCESS_NAME] = $isser;
  444. } elseif ($reflClass->hasMethod($hasser) && $reflClass->getMethod($hasser)->isPublic()) {
  445. $access[self::ACCESS_TYPE] = self::ACCESS_TYPE_METHOD;
  446. $access[self::ACCESS_NAME] = $hasser;
  447. } elseif ($reflClass->hasMethod('__get') && $reflClass->getMethod('__get')->isPublic()) {
  448. $access[self::ACCESS_TYPE] = self::ACCESS_TYPE_PROPERTY;
  449. $access[self::ACCESS_NAME] = $property;
  450. $access[self::ACCESS_REF] = false;
  451. } elseif ($access[self::ACCESS_HAS_PROPERTY] && $reflClass->getProperty($property)->isPublic()) {
  452. $access[self::ACCESS_TYPE] = self::ACCESS_TYPE_PROPERTY;
  453. $access[self::ACCESS_NAME] = $property;
  454. $access[self::ACCESS_REF] = true;
  455. } elseif ($this->magicCall && $reflClass->hasMethod('__call') && $reflClass->getMethod('__call')->isPublic()) {
  456. // we call the getter and hope the __call do the job
  457. $access[self::ACCESS_TYPE] = self::ACCESS_TYPE_MAGIC;
  458. $access[self::ACCESS_NAME] = $getter;
  459. } else {
  460. $methods = array($getter, $getsetter, $isser, $hasser, '__get');
  461. if ($this->magicCall) {
  462. $methods[] = '__call';
  463. }
  464. $access[self::ACCESS_TYPE] = self::ACCESS_TYPE_NOT_FOUND;
  465. $access[self::ACCESS_NAME] = sprintf(
  466. 'Neither the property "%s" nor one of the methods "%s()" '.
  467. 'exist and have public access in class "%s".',
  468. $property,
  469. implode('()", "', $methods),
  470. $reflClass->name
  471. );
  472. }
  473. $this->readPropertyCache[$key] = $access;
  474. }
  475. return $access;
  476. }
  477. /**
  478. * Sets the value of an index in a given array-accessible value.
  479. *
  480. * @param array $zval The array containing the array or \ArrayAccess object to write to
  481. * @param string|int $index The index to write at
  482. * @param mixed $value The value to write
  483. *
  484. * @throws NoSuchIndexException If the array does not implement \ArrayAccess or it is not an array
  485. */
  486. private function writeIndex($zval, $index, $value)
  487. {
  488. if (!$zval[self::VALUE] instanceof \ArrayAccess && !is_array($zval[self::VALUE])) {
  489. throw new NoSuchIndexException(sprintf('Cannot modify index "%s" in object of type "%s" because it doesn\'t implement \ArrayAccess', $index, get_class($zval[self::VALUE])));
  490. }
  491. $zval[self::REF][$index] = $value;
  492. }
  493. /**
  494. * Sets the value of a property in the given object.
  495. *
  496. * @param array $zval The array containing the object to write to
  497. * @param string $property The property to write
  498. * @param mixed $value The value to write
  499. *
  500. * @throws NoSuchPropertyException if the property does not exist or is not public
  501. */
  502. private function writeProperty($zval, $property, $value)
  503. {
  504. if (!is_object($zval[self::VALUE])) {
  505. throw new NoSuchPropertyException(sprintf('Cannot write property "%s" to an array. Maybe you should write the property path as "[%1$s]" instead?', $property));
  506. }
  507. $object = $zval[self::VALUE];
  508. $access = $this->getWriteAccessInfo(get_class($object), $property, $value);
  509. if (self::ACCESS_TYPE_METHOD === $access[self::ACCESS_TYPE]) {
  510. $object->{$access[self::ACCESS_NAME]}($value);
  511. } elseif (self::ACCESS_TYPE_PROPERTY === $access[self::ACCESS_TYPE]) {
  512. $object->{$access[self::ACCESS_NAME]} = $value;
  513. } elseif (self::ACCESS_TYPE_ADDER_AND_REMOVER === $access[self::ACCESS_TYPE]) {
  514. $this->writeCollection($zval, $property, $value, $access[self::ACCESS_ADDER], $access[self::ACCESS_REMOVER]);
  515. } elseif (!$access[self::ACCESS_HAS_PROPERTY] && property_exists($object, $property)) {
  516. // Needed to support \stdClass instances. We need to explicitly
  517. // exclude $access[self::ACCESS_HAS_PROPERTY], otherwise if
  518. // a *protected* property was found on the class, property_exists()
  519. // returns true, consequently the following line will result in a
  520. // fatal error.
  521. $object->$property = $value;
  522. } elseif (self::ACCESS_TYPE_MAGIC === $access[self::ACCESS_TYPE]) {
  523. $object->{$access[self::ACCESS_NAME]}($value);
  524. } else {
  525. throw new NoSuchPropertyException($access[self::ACCESS_NAME]);
  526. }
  527. }
  528. /**
  529. * Adjusts a collection-valued property by calling add*() and remove*() methods.
  530. *
  531. * @param array $zval The array containing the object to write to
  532. * @param string $property The property to write
  533. * @param iterable $collection The collection to write
  534. * @param string $addMethod The add*() method
  535. * @param string $removeMethod The remove*() method
  536. */
  537. private function writeCollection($zval, $property, $collection, $addMethod, $removeMethod)
  538. {
  539. // At this point the add and remove methods have been found
  540. $previousValue = $this->readProperty($zval, $property);
  541. $previousValue = $previousValue[self::VALUE];
  542. if ($previousValue instanceof \Traversable) {
  543. $previousValue = iterator_to_array($previousValue);
  544. }
  545. if ($previousValue && is_array($previousValue)) {
  546. if (is_object($collection)) {
  547. $collection = iterator_to_array($collection);
  548. }
  549. foreach ($previousValue as $key => $item) {
  550. if (!in_array($item, $collection, true)) {
  551. unset($previousValue[$key]);
  552. $zval[self::VALUE]->{$removeMethod}($item);
  553. }
  554. }
  555. } else {
  556. $previousValue = false;
  557. }
  558. foreach ($collection as $item) {
  559. if (!$previousValue || !in_array($item, $previousValue, true)) {
  560. $zval[self::VALUE]->{$addMethod}($item);
  561. }
  562. }
  563. }
  564. /**
  565. * Guesses how to write the property value.
  566. *
  567. * @param string $class
  568. * @param string $property
  569. * @param mixed $value
  570. *
  571. * @return array
  572. */
  573. private function getWriteAccessInfo($class, $property, $value)
  574. {
  575. $key = $class.'::'.$property;
  576. if (isset($this->writePropertyCache[$key])) {
  577. $access = $this->writePropertyCache[$key];
  578. } else {
  579. $access = array();
  580. $reflClass = new \ReflectionClass($class);
  581. $access[self::ACCESS_HAS_PROPERTY] = $reflClass->hasProperty($property);
  582. $camelized = $this->camelize($property);
  583. $singulars = (array) StringUtil::singularify($camelized);
  584. if (is_array($value) || $value instanceof \Traversable) {
  585. $methods = $this->findAdderAndRemover($reflClass, $singulars);
  586. if (null !== $methods) {
  587. $access[self::ACCESS_TYPE] = self::ACCESS_TYPE_ADDER_AND_REMOVER;
  588. $access[self::ACCESS_ADDER] = $methods[0];
  589. $access[self::ACCESS_REMOVER] = $methods[1];
  590. }
  591. }
  592. if (!isset($access[self::ACCESS_TYPE])) {
  593. $setter = 'set'.$camelized;
  594. $getsetter = lcfirst($camelized); // jQuery style, e.g. read: last(), write: last($item)
  595. if ($this->isMethodAccessible($reflClass, $setter, 1)) {
  596. $access[self::ACCESS_TYPE] = self::ACCESS_TYPE_METHOD;
  597. $access[self::ACCESS_NAME] = $setter;
  598. } elseif ($this->isMethodAccessible($reflClass, $getsetter, 1)) {
  599. $access[self::ACCESS_TYPE] = self::ACCESS_TYPE_METHOD;
  600. $access[self::ACCESS_NAME] = $getsetter;
  601. } elseif ($this->isMethodAccessible($reflClass, '__set', 2)) {
  602. $access[self::ACCESS_TYPE] = self::ACCESS_TYPE_PROPERTY;
  603. $access[self::ACCESS_NAME] = $property;
  604. } elseif ($access[self::ACCESS_HAS_PROPERTY] && $reflClass->getProperty($property)->isPublic()) {
  605. $access[self::ACCESS_TYPE] = self::ACCESS_TYPE_PROPERTY;
  606. $access[self::ACCESS_NAME] = $property;
  607. } elseif ($this->magicCall && $this->isMethodAccessible($reflClass, '__call', 2)) {
  608. // we call the getter and hope the __call do the job
  609. $access[self::ACCESS_TYPE] = self::ACCESS_TYPE_MAGIC;
  610. $access[self::ACCESS_NAME] = $setter;
  611. } elseif (null !== $methods = $this->findAdderAndRemover($reflClass, $singulars)) {
  612. $access[self::ACCESS_TYPE] = self::ACCESS_TYPE_NOT_FOUND;
  613. $access[self::ACCESS_NAME] = sprintf(
  614. 'The property "%s" in class "%s" can be defined with the methods "%s()" but '.
  615. 'the new value must be an array or an instance of \Traversable, '.
  616. '"%s" given.',
  617. $property,
  618. $reflClass->name,
  619. implode('()", "', $methods),
  620. is_object($value) ? get_class($value) : gettype($value)
  621. );
  622. } else {
  623. $access[self::ACCESS_TYPE] = self::ACCESS_TYPE_NOT_FOUND;
  624. $access[self::ACCESS_NAME] = sprintf(
  625. 'Neither the property "%s" nor one of the methods %s"%s()", "%s()", '.
  626. '"__set()" or "__call()" exist and have public access in class "%s".',
  627. $property,
  628. implode('', array_map(function ($singular) {
  629. return '"add'.$singular.'()"/"remove'.$singular.'()", ';
  630. }, $singulars)),
  631. $setter,
  632. $getsetter,
  633. $reflClass->name
  634. );
  635. }
  636. }
  637. $this->writePropertyCache[$key] = $access;
  638. }
  639. return $access;
  640. }
  641. /**
  642. * Returns whether a property is writable in the given object.
  643. *
  644. * @param object $object The object to write to
  645. * @param string $property The property to write
  646. *
  647. * @return bool Whether the property is writable
  648. */
  649. private function isPropertyWritable($object, $property)
  650. {
  651. if (!is_object($object)) {
  652. return false;
  653. }
  654. $access = $this->getWriteAccessInfo(get_class($object), $property, array());
  655. return self::ACCESS_TYPE_METHOD === $access[self::ACCESS_TYPE]
  656. || self::ACCESS_TYPE_PROPERTY === $access[self::ACCESS_TYPE]
  657. || self::ACCESS_TYPE_ADDER_AND_REMOVER === $access[self::ACCESS_TYPE]
  658. || (!$access[self::ACCESS_HAS_PROPERTY] && property_exists($object, $property))
  659. || self::ACCESS_TYPE_MAGIC === $access[self::ACCESS_TYPE];
  660. }
  661. /**
  662. * Camelizes a given string.
  663. *
  664. * @param string $string Some string
  665. *
  666. * @return string The camelized version of the string
  667. */
  668. private function camelize($string)
  669. {
  670. return str_replace(' ', '', ucwords(str_replace('_', ' ', $string)));
  671. }
  672. /**
  673. * Searches for add and remove methods.
  674. *
  675. * @param \ReflectionClass $reflClass The reflection class for the given object
  676. * @param array $singulars The singular form of the property name or null
  677. *
  678. * @return array|null An array containing the adder and remover when found, null otherwise
  679. */
  680. private function findAdderAndRemover(\ReflectionClass $reflClass, array $singulars)
  681. {
  682. foreach ($singulars as $singular) {
  683. $addMethod = 'add'.$singular;
  684. $removeMethod = 'remove'.$singular;
  685. $addMethodFound = $this->isMethodAccessible($reflClass, $addMethod, 1);
  686. $removeMethodFound = $this->isMethodAccessible($reflClass, $removeMethod, 1);
  687. if ($addMethodFound && $removeMethodFound) {
  688. return array($addMethod, $removeMethod);
  689. }
  690. }
  691. }
  692. /**
  693. * Returns whether a method is public and has the number of required parameters.
  694. *
  695. * @param \ReflectionClass $class The class of the method
  696. * @param string $methodName The method name
  697. * @param int $parameters The number of parameters
  698. *
  699. * @return bool Whether the method is public and has $parameters required parameters
  700. */
  701. private function isMethodAccessible(\ReflectionClass $class, $methodName, $parameters)
  702. {
  703. if ($class->hasMethod($methodName)) {
  704. $method = $class->getMethod($methodName);
  705. if ($method->isPublic()
  706. && $method->getNumberOfRequiredParameters() <= $parameters
  707. && $method->getNumberOfParameters() >= $parameters) {
  708. return true;
  709. }
  710. }
  711. return false;
  712. }
  713. }