ObjectProperty.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 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. // Extract data
  38. $data[$name] = $this->extractValue($name, $value);
  39. }
  40. return $data;
  41. }
  42. /**
  43. * Hydrate an object by populating public properties
  44. *
  45. * Hydrates an object by setting public properties of the object.
  46. *
  47. * @param array $data
  48. * @param object $object
  49. * @return object
  50. * @throws Exception\BadMethodCallException for a non-object $object
  51. */
  52. public function hydrate(array $data, $object)
  53. {
  54. if (!is_object($object)) {
  55. throw new Exception\BadMethodCallException(sprintf(
  56. '%s expects the provided $object to be a PHP object)', __METHOD__
  57. ));
  58. }
  59. foreach ($data as $property => $value) {
  60. $object->$property = $this->hydrateValue($property, $value, $data);
  61. }
  62. return $object;
  63. }
  64. }