Last active
August 29, 2015 14:03
-
-
Save sasezaki/cd70e05bb28b0734a15a to your computer and use it in GitHub Desktop.
frolic with zf-fr Hydrator
This file contains hidden or 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 | |
use Hydrator\ObjectPropertyHydrator; | |
use Hydrator\Strategy\DateStrategy; | |
use Hydrator\Strategy\StrategyInterface; | |
use Hydrator\Context\ExtractionContext; | |
use Hydrator\Context\HydrationContext; | |
use Zend\Uri\UriInterface; | |
use Zend\Uri\UriFactory; | |
// comosper require zfr/hydrator | |
// https://github.com/zf-fr/hydrator | |
require 'vendor/autoload.php'; | |
class ResolveUriStrategy implements StrategyInterface | |
{ | |
private $baseUri; | |
public function __construct(UriInterface $baseUri, $normalize = true) | |
{ | |
$this->baseUri = $baseUri; | |
$this->normalize = $normalize; | |
} | |
public function extract($value, ExtractionContext $context = null) | |
{ | |
return $value; | |
} | |
public function hydrate($value, HydrationContext $context = null) | |
{ | |
$uri = UriFactory::factory($value, 'http')->resolve($this->baseUri); | |
if ($this->normalize) $uri->normalize(); | |
return $uri; | |
} | |
} | |
$baseUri = UriFactory::factory('http://example.com/foo/bar/baz'); | |
$scraped = [ | |
'entry' => 'Hello', | |
'url' => '../foo', | |
'edited' => '2008-05-16T11:25:30+09:00', // RFC 3339 | |
]; | |
$obj = new stdClass; | |
$hydrator = new ObjectPropertyHydrator; | |
$hydrator->setStrategy('url', new ResolveUriStrategy($baseUri)); | |
$hydrator->setStrategy('edited', new DateStrategy); | |
$hydrator->hydrate($scraped, $obj); | |
var_dump($obj->url->toString()); // string(26) "http://example.com/foo/foo" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What do you think of the new idea of making hydrators final? :) I'm still trying to find the best way for tat, I need people's feedback :d.