mirror of
https://gitlab.com/Chill-Projet/chill-bundles.git
synced 2025-07-05 16:36:13 +00:00
72 lines
2.5 KiB
PHP
72 lines
2.5 KiB
PHP
<?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;
|
|
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
|
|
use Symfony\Component\Serializer\Mapping\ClassMetadataInterface as SerializerMetadata;
|
|
|
|
|
|
class DoctrineExistingEntityNormalizer implements DenormalizerInterface
|
|
{
|
|
private EntityManagerInterface $em;
|
|
|
|
private ClassMetadataFactoryInterface $serializerMetadataFactory;
|
|
|
|
|
|
public function __construct(EntityManagerInterface $em, ClassMetadataFactoryInterface $serializerMetadataFactory)
|
|
{
|
|
$this->em = $em;
|
|
$this->serializerMetadataFactory = $serializerMetadataFactory;
|
|
}
|
|
|
|
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)
|
|
{
|
|
if (FALSE === \is_array($data)) {
|
|
return false;
|
|
}
|
|
|
|
if (FALSE === \array_key_exists('id', $data)) {
|
|
return false;
|
|
}
|
|
|
|
if (FALSE === $this->em->getClassMetadata($type) instanceof ClassMetadata) {
|
|
return false;
|
|
}
|
|
|
|
// does have serializer metadata, and class discriminator ?
|
|
if ($this->serializerMetadataFactory->hasMetadataFor($type)) {
|
|
|
|
$classDiscriminator = $this->serializerMetadataFactory
|
|
->getMetadataFor($type)->getClassDiscriminatorMapping();
|
|
|
|
if ($classDiscriminator) {
|
|
$typeProperty = $classDiscriminator->getTypeProperty();
|
|
|
|
// check that only 2 keys
|
|
// that the second key is property
|
|
// and that the type match the class for given type property
|
|
return count($data) === 2
|
|
&& \array_key_exists($typeProperty, $data)
|
|
&& $type === $classDiscriminator->getClassForType($data[$typeProperty]);
|
|
}
|
|
}
|
|
|
|
// we do not have any class discriminator. Check that the id is the only one key
|
|
return count($data) === 1;
|
|
}
|
|
}
|