Add ObjectToArrayTransformerInterface with an automatic implementation

This commit is contained in:
ornicar 2011-04-19 20:03:32 -07:00
commit f82d1b191b
2 changed files with 48 additions and 0 deletions

View file

@ -0,0 +1,33 @@
<?php
namespace FOQ\ElasticaBundle\Transformer;
/**
* AutomaticObjectToArrayTransformer
* Tries to convert objects by generating getters
* based on the required keys
*/
class ObjectToArrayAutomaticTransformer implements ObjectToArrayTransformerInterface
{
/**
* Transforms an object into an array having the required keys
*
* @param object $object the object to convert
* @param array $requiredKeys the keys we want to have in the returned array
* @return array
**/
public function transform($object, array $requiredKeys)
{
$class = get_class($object);
$array = array();
foreach ($requiredKeys as $key) {
$getter = 'get'.ucfirst($key);
if (!method_exists($class, $getter)) {
throw new InvalidArgumentException(sprintf('The getter %s::%s does not exist', $this->objectClass, $getter));
}
$array[$key] = $object->$getter();
}
return $array;
}
}