Skip to content

Instantly share code, notes, and snippets.

@sasezaki
Last active August 29, 2015 14:03
Show Gist options
  • Save sasezaki/cd70e05bb28b0734a15a to your computer and use it in GitHub Desktop.
Save sasezaki/cd70e05bb28b0734a15a to your computer and use it in GitHub Desktop.
frolic with zf-fr Hydrator
<?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"
@bakura10
Copy link

bakura10 commented Jul 2, 2014

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment