|
| 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-2015 Zend Technologies USA Inc. (http://www.zend.com) |
| 7 | + * @license http://framework.zend.com/license/new-bsd New BSD License |
| 8 | + */ |
| 9 | + |
| 10 | +namespace Zend\Stdlib\Hydrator\Iterator; |
| 11 | + |
| 12 | +use Iterator; |
| 13 | +use IteratorIterator; |
| 14 | +use Zend\Stdlib\Exception\InvalidArgumentException; |
| 15 | +use Zend\Stdlib\Hydrator\HydratorInterface; |
| 16 | + |
| 17 | +class HydratingIteratorIterator extends IteratorIterator implements HydratingIteratorInterface |
| 18 | +{ |
| 19 | + /** |
| 20 | + * @var HydratorInterface |
| 21 | + */ |
| 22 | + protected $hydrator; |
| 23 | + |
| 24 | + /** |
| 25 | + * @var object |
| 26 | + */ |
| 27 | + protected $prototype; |
| 28 | + |
| 29 | + /** |
| 30 | + * @param HydratorInterface $hydrator |
| 31 | + * @param Iterator $data |
| 32 | + * @param string|object $prototype Object or class name to use for prototype. |
| 33 | + */ |
| 34 | + public function __construct(HydratorInterface $hydrator, Iterator $data, $prototype) |
| 35 | + { |
| 36 | + $this->setHydrator($hydrator); |
| 37 | + $this->setPrototype($prototype); |
| 38 | + parent::__construct($data); |
| 39 | + } |
| 40 | + |
| 41 | + /** |
| 42 | + * @inheritdoc |
| 43 | + */ |
| 44 | + public function setPrototype($prototype) |
| 45 | + { |
| 46 | + if (is_object($prototype)) { |
| 47 | + $this->prototype = $prototype; |
| 48 | + return; |
| 49 | + } |
| 50 | + |
| 51 | + if (!class_exists($prototype)) { |
| 52 | + throw new InvalidArgumentException( |
| 53 | + sprintf('Method %s was passed an invalid class name: %s', __METHOD__, $prototype) |
| 54 | + ); |
| 55 | + } |
| 56 | + |
| 57 | + $this->prototype = new $prototype; |
| 58 | + } |
| 59 | + |
| 60 | + /** |
| 61 | + * @inheritdoc |
| 62 | + */ |
| 63 | + public function setHydrator(HydratorInterface $hydrator) |
| 64 | + { |
| 65 | + $this->hydrator = $hydrator; |
| 66 | + } |
| 67 | + |
| 68 | + /** |
| 69 | + * @return object Returns hydrated clone of $prototype |
| 70 | + */ |
| 71 | + public function current() |
| 72 | + { |
| 73 | + $currentValue = parent::current(); |
| 74 | + $object = clone $this->prototype; |
| 75 | + $this->hydrator->hydrate($currentValue, $object); |
| 76 | + return $object; |
| 77 | + } |
| 78 | +} |
0 commit comments