public
Created

Normalizer for Doctrine entities

  • Download Gist
normalizer.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
<?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;
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.