Created
October 4, 2012 22:10
-
-
Save alexandresalome/3836801 to your computer and use it in GitHub Desktop.
Normalizer for Doctrine entities
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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