<?php
declare(strict_types=1);
namespace App\Serializer;
use App\Service\EncryptorDataUtils;
use App\Service\InvoiceFilesService;
use App\Utils\InvoiceUtils;
use Evo\Infrastructure\MappingORM\Invoice;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Serializer\Normalizer\ContextAwareNormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
final class InvoiceNormalizer implements ContextAwareNormalizerInterface, NormalizerAwareInterface
{
use NormalizerAwareTrait;
private const ALREADY_CALLED = 'INVOICE_NORMALIZER_ALREADY_CALLED';
private InvoiceUtils $invoiceUtils;
private UrlGeneratorInterface $router;
private EncryptorDataUtils $encryptor;
private InvoiceFilesService $invoiceFilesService;
private Security $security;
public function __construct(
EncryptorDataUtils $encryptor,
InvoiceUtils $invoiceUtils,
UrlGeneratorInterface $router,
InvoiceFilesService $invoiceFilesService,
Security $security
) {
$this->encryptor = $encryptor;
$this->invoiceUtils = $invoiceUtils;
$this->router = $router;
$this->invoiceFilesService = $invoiceFilesService;
$this->security = $security;
}
public function supportsNormalization($data, $format = null, array $context = []): bool
{
if (isset($context[self::ALREADY_CALLED])) {
return false;
}
return $data instanceof Invoice;
}
public function normalize($object, $format = null, array $context = [])
{
$context[self::ALREADY_CALLED] = true;
$normalizedData = $this->normalizer->normalize($object, $format, $context);
if (is_array($normalizedData) && !in_array('read_letter_forward', $context['groups'], true)) {
$isWaiting = $this->invoiceUtils->isWaiting($object);
$normalizedData['isWaiting'] = $isWaiting;
$normalizedData['numberWithPrefix'] = 'FA-'.$object->getNumber();
$url = $this->router->generate(
'app_invoice_view',
['id' => $this->encryptor->encrypt($object->getId())],
UrlGeneratorInterface::ABSOLUTE_URL
);
if (!empty($context['groups']) &&
(in_array('read_zappier_invoice', $context['groups'], true)
|| in_array('admin:invoice:read', $context['groups'], true))
) {
$normalizedData['viewInvoicePath'] = $url.'/'.($object->getOrganization() ? $object->getOrganization()->getInvoiceToken() : '');
}
$normalizedData['path'] = $url;
$user = $this->security->getUser();
if (null !== $user) {
if (isset($context['groups']) && in_array('read_zappier_invoice', $context['groups'], true)) {
unset($normalizedData['path'], $normalizedData['isWaiting']);
} else {
$normalizedData['invoiceDownloadLink'] = $this->invoiceFilesService->downloadInvoice($object->getPath(), true);
}
}
}
return $normalizedData;
}
}