<?php
declare(strict_types=1);
namespace App\Serializer;
use App\Enum\LetterTypeEnum;
use App\Service\EncryptorDataUtils;
use Evo\Infrastructure\MappingORM\Letter;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Serializer\Normalizer\ContextAwareNormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
use Symfony\Contracts\Translation\TranslatorInterface;
final class LetterNormalizer implements ContextAwareNormalizerInterface, NormalizerAwareInterface
{
use NormalizerAwareTrait;
private const ALREADY_CALLED = 'LETTER_NORMALIZER_ALREADY_CALLED';
private UrlGeneratorInterface $router;
private EncryptorDataUtils $encryptor;
private TranslatorInterface $translator;
public function __construct(
EncryptorDataUtils $encryptor,
UrlGeneratorInterface $router,
TranslatorInterface $translator
) {
$this->encryptor = $encryptor;
$this->router = $router;
$this->translator = $translator;
}
public function supportsNormalization($data, $format = null, array $context = []): bool
{
if (isset($context[self::ALREADY_CALLED])) {
return false;
}
return $data instanceof Letter;
}
public function normalize($object, $format = null, array $context = [])
{
$context[self::ALREADY_CALLED] = true;
$normalizedData = $this->normalizer->normalize($object, $format, $context);
if (is_array($normalizedData)) {
$id = $this->encryptor->encrypt($object->getId());
$urlFront = $this->router->generate(
'app_letter_view',
['id' => $id, 'type' => 'recto'],
UrlGeneratorInterface::ABSOLUTE_URL
);
$urlFront = str_replace('http://', 'https://', $urlFront);
$urlBack = $this->router->generate(
'app_letter_view',
['id' => $id, 'type' => 'verso'],
UrlGeneratorInterface::ABSOLUTE_URL
);
$urlBack = str_replace('http://', 'https://', $urlBack);
$urlContent = $this->router->generate(
'app_letter_view',
['id' => $id, 'type' => 'content'],
UrlGeneratorInterface::ABSOLUTE_URL
);
$urlContent = str_replace('http://', 'https://', $urlContent);
if (isset($normalizedData['envelopeFrontPathAWS'])) {
$normalizedData['envelopeFrontUrl'] = $urlFront;
}
if (isset($normalizedData['envelopeBackPathAWS'])) {
$normalizedData['envelopeBackUrl'] = $urlBack;
}
if (isset($normalizedData['contentPathAWS'])) {
$normalizedData['contentUrl'] = $urlContent;
}
if (isset($context['groups']) && in_array('read_zappier_letter', $context['groups'], true)) {
unset(
$normalizedData['contentPathAWS'],
$normalizedData['envelopeFrontPathAWS'],
$normalizedData['envelopeBackPathAWS']
);
$normalizedData['type'] = $this->translator->trans(LetterTypeEnum::getReadableValue($normalizedData['type']));
}
}
return $normalizedData;
}
}