mirror of
https://gitlab.com/Chill-Projet/chill-bundles.git
synced 2025-08-21 15:13:50 +00:00
Add a denormalizer for fetching entities by id
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace Chill\MainBundle\Serializer\Normalizer;
|
||||
|
||||
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
|
||||
use Doctrine\ORM\Mapping\ClassMetadata;
|
||||
|
||||
|
||||
class DoctrineExistingEntityNormalizer implements DenormalizerInterface
|
||||
{
|
||||
private EntityManagerInterface $em;
|
||||
|
||||
public function __construct(EntityManagerInterface $em)
|
||||
{
|
||||
$this->em = $em;
|
||||
}
|
||||
|
||||
public function denormalize($data, string $type, string $format = null, array $context = [])
|
||||
{
|
||||
if (\array_key_exists(AbstractNormalizer::OBJECT_TO_POPULATE, $context)) {
|
||||
return $context[AbstractNormalizer::OBJECT_TO_POPULATE];
|
||||
}
|
||||
|
||||
return $this->em->getRepository($type)
|
||||
->find($data['id']);
|
||||
}
|
||||
|
||||
public function supportsDenormalization($data, string $type, string $format = null)
|
||||
{
|
||||
return \is_array($data)
|
||||
&& count($data) === 1
|
||||
&& \array_key_exists('id', $data)
|
||||
&& $this->em->getClassMetadata($type) instanceof ClassMetadata;
|
||||
}
|
||||
|
||||
}
|
Reference in New Issue
Block a user