mirror of
https://gitlab.com/Chill-Projet/chill-bundles.git
synced 2025-06-07 18:44:08 +00:00
Add a denormalizer for fetching entities by id
This commit is contained in:
parent
a4989f99d6
commit
a448405ce5
@ -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;
|
||||
}
|
||||
|
||||
}
|
@ -3,6 +3,12 @@ parameters:
|
||||
|
||||
services:
|
||||
|
||||
Chill\MainBundle\Serializer\Normalizer\:
|
||||
resource: '../Serializer/Normalizer'
|
||||
autowire: true
|
||||
tags:
|
||||
- { name: 'serializer.normalizer', priority: 64 }
|
||||
|
||||
chill.main.helper.translatable_string:
|
||||
class: Chill\MainBundle\Templating\TranslatableStringHelper
|
||||
arguments:
|
||||
|
@ -1,21 +1,11 @@
|
||||
---
|
||||
services:
|
||||
Chill\MainBundle\Serializer\Normalizer\CenterNormalizer:
|
||||
tags:
|
||||
- { name: 'serializer.normalizer', priority: 64 }
|
||||
|
||||
# note: the autowiring for serializers and normalizers is declared
|
||||
# into ../services.yaml
|
||||
|
||||
Chill\MainBundle\Serializer\Normalizer\AddressNormalizer:
|
||||
Chill\MainBundle\Serializer\Normalizer\DoctrineExistingEntityNormalizer:
|
||||
autowire: true
|
||||
tags:
|
||||
- { name: 'serializer.normalizer', priority: 64 }
|
||||
- { name: 'serializer.normalizer', priority: 8 }
|
||||
|
||||
Chill\MainBundle\Serializer\Normalizer\DateNormalizer:
|
||||
tags:
|
||||
- { name: 'serializer.normalizer', priority: 64 }
|
||||
|
||||
Chill\MainBundle\Serializer\Normalizer\UserNormalizer:
|
||||
tags:
|
||||
- { name: 'serializer.normalizer', priority: 64 }
|
||||
|
||||
Chill\MainBundle\Serializer\Normalizer\CollectionNormalizer:
|
||||
tags:
|
||||
- { name: 'serializer.normalizer', priority: 64 }
|
||||
|
Loading…
x
Reference in New Issue
Block a user