FOSElasticaBundle/Transformer/ModelToElasticaAutoTransformer.php

87 lines
2.3 KiB
PHP
Raw Normal View History

<?php
namespace FOQ\ElasticaBundle\Transformer;
use Elastica_Document;
use Traversable;
use ArrayAccess;
2011-05-26 21:22:46 +02:00
use RuntimeException;
/**
* Maps Elastica documents with Doctrine objects
* This mapper assumes an exact match between
* elastica documents ids and doctrine object ids
*/
class ModelToElasticaAutoTransformer implements ModelToElasticaTransformerInterface
{
/**
* Optional parameters
*
* @var array
*/
protected $options = array(
'identifier' => 'id'
);
/**
* Instanciates a new Mapper
*
* @param array $options
*/
public function __construct(array $options = array())
{
$this->options = array_merge($this->options, $options);
}
/**
* Transforms an object into an elastica object having the required keys
*
* @param object $object the object to convert
* @param array $fields the keys we want to have in the returned array
* @return Elastica_Document
**/
public function transform($object, array $fields)
{
$array = array();
foreach ($fields as $key) {
$getter = 'get'.ucfirst($key);
2012-04-09 18:14:45 +02:00
if (!is_callable(array($object, $getter))) {
throw new RuntimeException(sprintf('The method %s::%s is not callable', get_class($object), $getter));
}
$array[$key] = $this->normalizeValue($object->$getter());
}
$identifierGetter = 'get'.ucfirst($this->options['identifier']);
$identifier = $object->$identifierGetter();
return new Elastica_Document($identifier, $array);
}
/**
* Attempts to convert any type to a string or an array of strings
*
* @param mixed $value
2011-11-28 17:24:16 +01:00
*
* @return string|array
*/
protected function normalizeValue($value)
{
2011-11-28 17:24:16 +01:00
$normalizeValue = function(&$v) {
if ($v instanceof \DateTime) {
$v = (int) $v->format('U');
} elseif (!is_scalar($v) && !is_null($v)) {
2011-11-28 17:24:16 +01:00
$v = (string) $v;
}
};
if (is_array($value) || $value instanceof Traversable || $value instanceof ArrayAccess) {
2011-11-28 17:24:16 +01:00
$value = is_array($value) ? $value : iterator_to_array($value);
array_walk_recursive($value, $normalizeValue);
} else {
2011-11-28 17:24:16 +01:00
$normalizeValue($value);
}
return $value;
}
}