DefaultNormalizer.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Serializer;
  4. use App\Entity\Access\Access;
  5. use App\Service\Utils\EntityUtils;
  6. use Symfony\Bundle\SecurityBundle\Security;
  7. use Symfony\Component\Serializer\Exception\ExceptionInterface;
  8. use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
  9. use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
  10. use Symfony\Component\Serializer\SerializerAwareInterface;
  11. use Symfony\Component\Serializer\SerializerInterface;
  12. /**
  13. * Serializer par défaut.
  14. */
  15. final class DefaultNormalizer implements NormalizerInterface, DenormalizerInterface, SerializerAwareInterface
  16. {
  17. public function __construct(
  18. private NormalizerInterface $decorated,
  19. private EntityUtils $entityUtils,
  20. private Security $security,
  21. ) {
  22. if (!$this->decorated instanceof DenormalizerInterface) {
  23. throw new \InvalidArgumentException(sprintf('The decorated normalizer must implement the %s.', DenormalizerInterface::class));
  24. }
  25. }
  26. /**
  27. * @param mixed[] $context
  28. */
  29. public function supportsNormalization($data, $format = null, array $context = []): bool
  30. {
  31. return $this->decorated->supportsNormalization($data, $format);
  32. }
  33. /**
  34. * @param mixed[] $context
  35. *
  36. * @throws ExceptionInterface
  37. */
  38. public function normalize($object, $format = null, array $context = []): mixed
  39. {
  40. return $this->decorated->normalize($object, $format, $context);
  41. }
  42. /**
  43. * @param mixed[] $context
  44. */
  45. public function supportsDenormalization($data, $type, $format = null, array $context = []): bool
  46. {
  47. /* @phpstan-ignore-next-line */
  48. return $this->decorated->supportsDenormalization($data, $type, $format);
  49. }
  50. /**
  51. * @param mixed[] $context
  52. *
  53. * @throws \ReflectionException
  54. */
  55. public function denormalize($data, $class, $format = null, array $context = []): mixed
  56. {
  57. /** @phpstan-ignore-next-line */
  58. $entity = $this->decorated->denormalize($data, $class, $format, $context);
  59. /** @var Access $access */
  60. $access = $this->security->getUser();
  61. $this->entityUtils->defaultValueSettersByAccess($entity, $access);
  62. return $entity;
  63. }
  64. public function setSerializer(SerializerInterface $serializer): void
  65. {
  66. if ($this->decorated instanceof SerializerAwareInterface) {
  67. $this->decorated->setSerializer($serializer);
  68. }
  69. }
  70. }