Reflection.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. /**
  3. * Zend Framework (http://framework.zend.com/)
  4. *
  5. * @link http://github.com/zendframework/zf2 for the canonical source repository
  6. * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
  7. * @license http://framework.zend.com/license/new-bsd New BSD License
  8. */
  9. namespace Zend\Stdlib\Hydrator;
  10. use ReflectionClass;
  11. use Zend\Stdlib\Exception;
  12. class Reflection extends AbstractHydrator
  13. {
  14. /**
  15. * Simple in-memory array cache of ReflectionProperties used.
  16. * @var array
  17. */
  18. protected static $reflProperties = array();
  19. /**
  20. * Extract values from an object
  21. *
  22. * @param object $object
  23. * @return array
  24. */
  25. public function extract($object)
  26. {
  27. $result = array();
  28. foreach (self::getReflProperties($object) as $property) {
  29. $propertyName = $property->getName();
  30. if (!$this->filterComposite->filter($propertyName)) {
  31. continue;
  32. }
  33. $value = $property->getValue($object);
  34. $result[$propertyName] = $this->extractValue($propertyName, $value, $object);
  35. }
  36. return $result;
  37. }
  38. /**
  39. * Hydrate $object with the provided $data.
  40. *
  41. * @param array $data
  42. * @param object $object
  43. * @return object
  44. */
  45. public function hydrate(array $data, $object)
  46. {
  47. $reflProperties = self::getReflProperties($object);
  48. foreach ($data as $key => $value) {
  49. if (isset($reflProperties[$key])) {
  50. $reflProperties[$key]->setValue($object, $this->hydrateValue($key, $value, $data));
  51. }
  52. }
  53. return $object;
  54. }
  55. /**
  56. * Get a reflection properties from in-memory cache and lazy-load if
  57. * class has not been loaded.
  58. *
  59. * @param string|object $input
  60. * @throws Exception\InvalidArgumentException
  61. * @return array
  62. */
  63. protected static function getReflProperties($input)
  64. {
  65. if (is_object($input)) {
  66. $input = get_class($input);
  67. } elseif (!is_string($input)) {
  68. throw new Exception\InvalidArgumentException('Input must be a string or an object.');
  69. }
  70. if (isset(static::$reflProperties[$input])) {
  71. return static::$reflProperties[$input];
  72. }
  73. static::$reflProperties[$input] = array();
  74. $reflClass = new ReflectionClass($input);
  75. $reflProperties = $reflClass->getProperties();
  76. foreach ($reflProperties as $property) {
  77. $property->setAccessible(true);
  78. static::$reflProperties[$input][$property->getName()] = $property;
  79. }
  80. return static::$reflProperties[$input];
  81. }
  82. }