Created
March 14, 2015 17:20
-
-
Save manuakasam/803cdd6b0ee56dcaa09c to your computer and use it in GitHub Desktop.
See class header. A basic hydration component to easily deliver OneToOne Hydrations for entities without much development time.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @author Manuel Stosic <[email protected]> | |
*/ | |
namespace Zf2demo\Hydrator; | |
use Zend\Stdlib\Hydrator\ClassMethods; | |
/** | |
* Class OneToOneHydrator | |
* | |
* Basic Hydrator to properly hydrate OneToOne tables | |
* | |
* <code> | |
* $data = [ | |
* 'foo_one' => 'FOO_1', | |
* 'foo_two' => 'FOO_2', | |
* 'bar_one' => 'BAR_1', | |
* 'bar_two' => 'BAR_2Ä | |
* ]; | |
* | |
* $hydrator = new AggregateHydrator(); | |
* $hydrator->add(new OneToOneHydrator('foo_', 'setFoo', new Foo())); | |
* $hydrator->add(new OneToOneHydrator('bar_', 'setBar', new Bar())); | |
* | |
* $object = $hydrator->hydrate($data, new Dummy()); | |
* | |
* var_dump($object); | |
* | |
* object(Dummy)#38 (5) { | |
* ["foo":protected]=> | |
* object(Foo)#24 (2) { | |
* ["one":protected]=> | |
* string(5) "FOO_1" | |
* ["two":protected]=> | |
* string(5) "FOO_2" | |
* } | |
* ["bar":protected]=> | |
* object(Bar)#24 (2) { | |
* ["one":protected]=> | |
* string(5) "BAR_1" | |
* ["two":protected]=> | |
* string(5) "BAR_2" | |
* } | |
* } | |
* </code> | |
* | |
* @author Manuel Stosic <[email protected]> | |
* @package Zf2demo\Hydrator | |
*/ | |
class OneToOneHydrator extends ClassMethods | |
{ | |
protected $needle; | |
protected $setter; | |
protected $prototype; | |
/** | |
* @param string $needle What substring identifies the related object | |
* @param string $setter What function to call to populate the object | |
* @param mixed $objectPrototype Prototype Object to be used for the Hydration | |
* @param bool $underscoreSeparatedKeys | |
*/ | |
public function __construct($needle, $setter, $objectPrototype, $underscoreSeparatedKeys = true) | |
{ | |
parent::__construct($underscoreSeparatedKeys); | |
$this->needle = $needle; | |
$this->setter = $setter; | |
$this->prototype = $objectPrototype; | |
} | |
/** | |
* @param array $data | |
* @param object $object | |
* | |
* @return object | |
*/ | |
public function hydrate(array $data, $object) | |
{ | |
$toHydrate = []; | |
$lenNeedle = strlen($this->needle); | |
foreach ($data as $key => $value) { | |
if ($this->needle === substr($key, 0, $lenNeedle)) { | |
$toHydrate[substr($key, $lenNeedle)] = $value; | |
} | |
} | |
$aggregatedObject = parent::hydrate($toHydrate, $this->prototype); | |
$object->{$this->setter}($aggregatedObject); | |
return $object; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment