<?php
namespace App\Normalizer;
use App\Entity\Gender;
use ArrayObject;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Serializer\Exception\ExceptionInterface;
use Symfony\Component\Serializer\Normalizer\ContextAwareNormalizerInterface;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Contracts\Translation\TranslatorInterface;
class GenderNormalizer implements ContextAwareNormalizerInterface
{
/**
* @var ObjectNormalizer
*/
private ObjectNormalizer $normalizer;
/**
* @var TranslatorInterface
*/
private TranslatorInterface $translator;
/**
* @var SessionInterface
*/
private SessionInterface $session;
/**
* @param ObjectNormalizer $normalizer
* @param TranslatorInterface $translator
* @param SessionInterface $session
*/
public function __construct(
ObjectNormalizer $normalizer,
TranslatorInterface $translator,
SessionInterface $session
) {
$this->normalizer = $normalizer;
$this->translator = $translator;
$this->session = $session;
}
/**
* @param
* @param $format
* @param array $context
* @return array|ArrayObject|bool|float|int|mixed|string|null
* @throws ExceptionInterface
*/
public function normalize($object, $format = null, array $context = [])
{
$data = $this->normalizer->normalize($object, $format, $context);
$request = Request::createFromGlobals();
$locale = isset($request->getLanguages()[0]) ? $request->getLanguages()[0] : $this->session->get('_locale');
foreach ($data as $item) {
$data['name'] = $this->translator->trans($data['name'], [], 'gender', $locale);
}
return $data;
}
public function supportsNormalization($data, $format = null, array $context = []): bool
{
return $data instanceof Gender;
}
}