<?php
declare(strict_types=1);
namespace App\Serializer;
use App\Enum\DocumentTypeOrganizationEnum;
use App\Service\EncryptorDataUtils;
use Evo\Infrastructure\MappingORM\Document;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Serializer\Normalizer\ContextAwareNormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
final class DocumentNormalizer implements ContextAwareNormalizerInterface, NormalizerAwareInterface
{
use NormalizerAwareTrait;
private const ALREADY_CALLED = 'DOCUMENT_NORMALIZER_ALREADY_CALLED';
private ?Request $request = null;
private UrlGeneratorInterface $router;
private EncryptorDataUtils $encryptor;
public function __construct(
RequestStack $requestStack,
EncryptorDataUtils $encryptor,
UrlGeneratorInterface $router
) {
$this->encryptor = $encryptor;
$this->request = $requestStack->getMainRequest();
$this->router = $router;
}
public function supportsNormalization($data, $format = null, array $context = []): bool
{
if (isset($context[self::ALREADY_CALLED])) {
return false;
}
return $data instanceof Document;
}
public function normalize($object, $format = null, array $context = [])
{
$context[self::ALREADY_CALLED] = true;
$normalizedData = $this->normalizer->normalize($object, $format, $context);
$urlAPI = $this->router->generate(
'app_document_view',
['id' => $this->encryptor->encrypt($object->getId())]
);
$url = $this->request->getSchemeAndHttpHost().$urlAPI;
if (is_array($normalizedData)) {
$url = str_replace('http://', 'https://', $url);
$normalizedData['url'] = $url;
$normalizedData['extension'] = null;
if (null !== $object->getAwsPath()) {
$_data = explode('.', $object->getAwsPath());
$normalizedData['extension'] = end($_data);
}
if (in_array($normalizedData['type'], DocumentTypeOrganizationEnum::DOMICILIATION, true)) {
$normalizedData['category'] = 'DOMICILIATION';
} elseif (in_array($normalizedData['type'], DocumentTypeOrganizationEnum::ORGANIZATION, true)) {
$normalizedData['category'] = 'ORGANIZATION';
} else {
$normalizedData['category'] = 'OTHER';
}
}
return $normalizedData;
}
}