<?php
namespace App\Normalizer;
use App\Entity\AbstractCollaborator;
use App\Entity\AgentsOptions;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Serializer\Normalizer\CacheableSupportsMethodInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\Exception\ExceptionInterface;
use Symfony\Component\Serializer\Normalizer\ContextAwareNormalizerInterface;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\HttpFoundation\Request;
class AgentsOptionsNormalizer implements NormalizerInterface, CacheableSupportsMethodInterface
{
/**
* @var ObjectNormalizer
*/
private ObjectNormalizer $normalizer;
/**
* @var TranslatorInterface
*/
private TranslatorInterface $translator;
/**
* @var Security
*/
private Security $security;
/**
* @var SessionInterface
*/
private SessionInterface $session;
/**
* @param ObjectNormalizer $normalizer
* @param Security $security
*/
public function __construct(
ObjectNormalizer $normalizer,
Security $security,
TranslatorInterface $translator,
SessionInterface $session
) {
$this->normalizer = $normalizer;
$this->security = $security;
$this->translator = $translator;
$this->session = $session;
}
public function normalize($object, string $format = null, array $context = []): array
{
$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['option']['name']?? null, [], 'option', $locale);
$data['code'] = $data['option']['code'] ?? null;
$data['type'] = $data['option']['type'] ?? null;
$data['value'] = filter_var($data['optionValue'], FILTER_VALIDATE_BOOLEAN) ?? null;
}
$data = array_filter($data, function ($value) {
return $value !== null;
});
unset($data['option']);
unset($data['agent']);
unset($data['optionValue']);
return $data;
}
public function supportsNormalization($data, string $format = null, array $context = []): bool
{
return $data instanceof AgentsOptions;
}
public function hasCacheableSupportsMethod(): bool
{
return true;
}
}