ArraySerializable.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-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 ArraySerializable extends AbstractHydrator
  12. {
  13. /**
  14. * Extract values from the provided object
  15. *
  16. * Extracts values via the object's getArrayCopy() method.
  17. *
  18. * @param object $object
  19. * @return array
  20. * @throws Exception\BadMethodCallException for an $object not implementing getArrayCopy()
  21. */
  22. public function extract($object)
  23. {
  24. if (!is_callable(array($object, 'getArrayCopy'))) {
  25. throw new Exception\BadMethodCallException(sprintf(
  26. '%s expects the provided object to implement getArrayCopy()', __METHOD__
  27. ));
  28. }
  29. $data = $object->getArrayCopy();
  30. foreach ($data as $name => $value) {
  31. if (!$this->getFilter()->filter($name)) {
  32. unset($data[$name]);
  33. continue;
  34. }
  35. $data[$name] = $this->extractValue($name, $value);
  36. }
  37. return $data;
  38. }
  39. /**
  40. * Hydrate an object
  41. *
  42. * Hydrates an object by passing $data to either its exchangeArray() or
  43. * populate() method.
  44. *
  45. * @param array $data
  46. * @param object $object
  47. * @return object
  48. * @throws Exception\BadMethodCallException for an $object not implementing exchangeArray() or populate()
  49. */
  50. public function hydrate(array $data, $object)
  51. {
  52. $self = $this;
  53. array_walk($data, function (&$value, $name) use ($self) {
  54. $value = $self->hydrateValue($name, $value);
  55. });
  56. if (is_callable(array($object, 'exchangeArray'))) {
  57. $object->exchangeArray($data);
  58. } elseif (is_callable(array($object, 'populate'))) {
  59. $object->populate($data);
  60. } else {
  61. throw new Exception\BadMethodCallException(sprintf(
  62. '%s expects the provided object to implement exchangeArray() or populate()', __METHOD__
  63. ));
  64. }
  65. return $object;
  66. }
  67. }