ObjectProperty.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 Zend\Stdlib\Exception;
  11. class ObjectProperty extends AbstractHydrator
  12. {
  13. /**
  14. * Extract values from an object
  15. *
  16. * Extracts the accessible non-static properties of the given $object.
  17. *
  18. * @param object $object
  19. * @return array
  20. * @throws Exception\BadMethodCallException for a non-object $object
  21. */
  22. public function extract($object)
  23. {
  24. if (!is_object($object)) {
  25. throw new Exception\BadMethodCallException(sprintf(
  26. '%s expects the provided $object to be a PHP object)', __METHOD__
  27. ));
  28. }
  29. $data = get_object_vars($object);
  30. $filter = $this->getFilter();
  31. foreach ($data as $name => $value) {
  32. // Filter keys, removing any we don't want
  33. if (!$filter->filter($name)) {
  34. unset($data[$name]);
  35. continue;
  36. }
  37. // Replace name if extracted differ
  38. $extracted = $this->extractName($name, $object);
  39. if ($extracted !== $name) {
  40. unset($data[$name]);
  41. $name = $extracted;
  42. }
  43. $data[$name] = $this->extractValue($name, $value, $object);
  44. }
  45. return $data;
  46. }
  47. /**
  48. * Hydrate an object by populating public properties
  49. *
  50. * Hydrates an object by setting public properties of the object.
  51. *
  52. * @param array $data
  53. * @param object $object
  54. * @return object
  55. * @throws Exception\BadMethodCallException for a non-object $object
  56. */
  57. public function hydrate(array $data, $object)
  58. {
  59. if (!is_object($object)) {
  60. throw new Exception\BadMethodCallException(sprintf(
  61. '%s expects the provided $object to be a PHP object)', __METHOD__
  62. ));
  63. }
  64. foreach ($data as $name => $value) {
  65. $property = $this->hydrateName($name, $data);
  66. $object->$property = $this->hydrateValue($property, $value, $data);
  67. }
  68. return $object;
  69. }
  70. }