DefaultNormalizer.php 2.5 KB

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