Reflection.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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-2014 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 = $this->extractName($property->getName(), $object);
  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. $name = $this->hydrateName($key, $data);
  50. if (isset($reflProperties[$name])) {
  51. $reflProperties[$name]->setValue($object, $this->hydrateValue($name, $value, $data));
  52. }
  53. }
  54. return $object;
  55. }
  56. /**
  57. * Get a reflection properties from in-memory cache and lazy-load if
  58. * class has not been loaded.
  59. *
  60. * @param string|object $input
  61. * @throws Exception\InvalidArgumentException
  62. * @return array
  63. */
  64. protected static function getReflProperties($input)
  65. {
  66. if (is_object($input)) {
  67. $input = get_class($input);
  68. } elseif (!is_string($input)) {
  69. throw new Exception\InvalidArgumentException('Input must be a string or an object.');
  70. }
  71. if (isset(static::$reflProperties[$input])) {
  72. return static::$reflProperties[$input];
  73. }
  74. static::$reflProperties[$input] = array();
  75. $reflClass = new ReflectionClass($input);
  76. $reflProperties = $reflClass->getProperties();
  77. foreach ($reflProperties as $property) {
  78. $property->setAccessible(true);
  79. static::$reflProperties[$input][$property->getName()] = $property;
  80. }
  81. return static::$reflProperties[$input];
  82. }
  83. }