ArraySerializable.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 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. $filter = $this->getFilter();
  31. foreach ($data as $name => $value) {
  32. if (!$filter->filter($name)) {
  33. unset($data[$name]);
  34. continue;
  35. }
  36. $extractedName = $this->extractName($name, $object);
  37. // replace the original key with extracted, if differ
  38. if ($extractedName !== $name) {
  39. unset($data[$name]);
  40. $name = $extractedName;
  41. }
  42. $data[$name] = $this->extractValue($name, $value, $object);
  43. }
  44. return $data;
  45. }
  46. /**
  47. * Hydrate an object
  48. *
  49. * Hydrates an object by passing $data to either its exchangeArray() or
  50. * populate() method.
  51. *
  52. * @param array $data
  53. * @param object $object
  54. * @return object
  55. * @throws Exception\BadMethodCallException for an $object not implementing exchangeArray() or populate()
  56. */
  57. public function hydrate(array $data, $object)
  58. {
  59. $replacement = array();
  60. foreach ($data as $key => $value) {
  61. $name = $this->hydrateName($key, $data);
  62. $replacement[$name] = $this->hydrateValue($name, $value, $data);
  63. }
  64. if (is_callable(array($object, 'exchangeArray'))) {
  65. $object->exchangeArray($replacement);
  66. } elseif (is_callable(array($object, 'populate'))) {
  67. $object->populate($replacement);
  68. } else {
  69. throw new Exception\BadMethodCallException(sprintf(
  70. '%s expects the provided object to implement exchangeArray() or populate()', __METHOD__
  71. ));
  72. }
  73. return $object;
  74. }
  75. }