src/Normalizer/GenderNormalizer.php line 56

Open in your IDE?
  1. <?php
  2. namespace App\Normalizer;
  3. use App\Entity\Gender;
  4. use ArrayObject;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  7. use Symfony\Component\Serializer\Exception\ExceptionInterface;
  8. use Symfony\Component\Serializer\Normalizer\ContextAwareNormalizerInterface;
  9. use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
  10. use Symfony\Contracts\Translation\TranslatorInterface;
  11. class GenderNormalizer implements ContextAwareNormalizerInterface
  12. {
  13.     /**
  14.      * @var ObjectNormalizer
  15.      */
  16.     private ObjectNormalizer $normalizer;
  17.     /**
  18.      * @var TranslatorInterface
  19.      */
  20.     private TranslatorInterface $translator;
  21.     /**
  22.      * @var SessionInterface
  23.      */
  24.     private SessionInterface $session;
  25.     /**
  26.      * @param ObjectNormalizer $normalizer
  27.      * @param TranslatorInterface $translator
  28.      * @param SessionInterface $session
  29.      */
  30.     public function __construct(
  31.         ObjectNormalizer $normalizer,
  32.         TranslatorInterface $translator,
  33.         SessionInterface $session
  34.     ) {
  35.         $this->normalizer $normalizer;
  36.         $this->translator $translator;
  37.         $this->session $session;
  38.     }
  39.     /**
  40.      * @param
  41.      * @param $format
  42.      * @param array $context
  43.      * @return array|ArrayObject|bool|float|int|mixed|string|null
  44.      * @throws ExceptionInterface
  45.      */
  46.     public function normalize($object$format null, array $context = [])
  47.     {
  48.         $data $this->normalizer->normalize($object$format$context);
  49.         $request Request::createFromGlobals();
  50.         $locale = isset($request->getLanguages()[0]) ? $request->getLanguages()[0] : $this->session->get('_locale');
  51.         foreach ($data as $item) {
  52.             $data['name'] = $this->translator->trans($data['name'], [], 'gender'$locale);
  53.         }
  54.         return $data;
  55.     }
  56.     public function supportsNormalization($data$format null, array $context = []): bool
  57.     {
  58.         return $data instanceof Gender;
  59.     }
  60. }