Skip to content

Instantly share code, notes, and snippets.

@alexandresalome
Created October 4, 2012 22:10
Show Gist options
  • Save alexandresalome/3836801 to your computer and use it in GitHub Desktop.
Save alexandresalome/3836801 to your computer and use it in GitHub Desktop.
Normalizer for Doctrine entities
<?php
namespace Gitonomy\Bundle\CoreBundle\Serializer\Normalizer;
use Symfony\Bridge\Doctrine\RegistryInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
class EntitiesNormalizer implements NormalizerInterface, DenormalizerInterface
{
protected $classes;
protected $doctrineRegistry;
public function __construct(RegistryInterface $doctrineRegistry)
{
$this->doctrineRegistry = $doctrineRegistry;
$this->classes = array(
'Gitonomy\Bundle\CoreBundle\Entity\Project',
'Gitonomy\Bundle\CoreBundle\Entity\User',
);
}
public function normalize($object, $format = null)
{
return $this->doctrineRegistry
->getEntityManager()
->getMetadataFactory()
->getMetadataFor(get_class($object))
->getIdentifierValues($object)
;
}
public function denormalize($data, $class, $format = null)
{
return $this->doctrineRegistry
->getEntityManager()
->getRepository($class)
->find($data)
;
}
public function supportsNormalization($data, $format = null)
{
foreach ($this->classes as $class) {
if ($data instanceof $class) {
return true;
}
}
return false;
}
public function supportsDenormalization($data, $type, $format = null)
{
$refClass = new \ReflectionClass($type);
foreach ($this->classes as $class) {
if ($type == $class || $refClass->isSubclassOf($class)) {
return true;
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment