<?php
namespace App\Service\Serializer;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Model\CustomerFile\CustomerFile;
use App\Model\CustomerFolder\CustomerFolder;
use App\Model\Prospect\Prospect;
use App\Model\Quote\Quote;
use App\Model\Task\Task;
use Lexik\Bundle\JWTAuthenticationBundle\TokenExtractor\TokenExtractorInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RouterInterface;
/**
* Class ResolveCustomerFileContentUrlSubscriber.
*/
final class ResolveCustomerFileContentUrlSubscriber implements EventSubscriberInterface
{
/**
* @var RouterInterface
*/
private $router;
/**
* @var RequestStack
*/
private $requestStack;
/**
* @var TokenExtractorInterface
*/
private $tokenExtractor;
/**
* ResolveCustomerFileContentUrlSubscriber constructor.
*
* @param RouterInterface $router
* @param RequestStack $requestStack
* @param TokenExtractorInterface $tokenExtractor
*/
public function __construct(
RouterInterface $router,
RequestStack $requestStack,
TokenExtractorInterface $tokenExtractor
) {
$this->router = $router;
$this->requestStack = $requestStack;
$this->tokenExtractor = $tokenExtractor;
}
/**
* @return array
*/
public static function getSubscribedEvents(): array
{
return [
KernelEvents::VIEW => ['onPreSerialize', EventPriorities::PRE_SERIALIZE],
];
}
/**
* @param ViewEvent $event
*/
public function onPreSerialize(ViewEvent $event): void
{
$controllerResult = $event->getControllerResult();
$request = $event->getRequest();
if ($controllerResult instanceof Response || !$request->attributes->getBoolean('_api_respond', true)) {
return;
}
if (!$controllerResult instanceof Prospect && !$controllerResult instanceof Task
&& !$controllerResult instanceof Quote) {
return;
}
$customerFiles = $controllerResult->getCustomerFiles();
if (!is_iterable($customerFiles)) {
$customerFiles = [$customerFiles];
}
foreach ($customerFiles as $customerFile) {
if (!$customerFile instanceof CustomerFile && !$customerFile instanceof CustomerFolder) {
continue;
}
if ($customerFile instanceof CustomerFile) {
$customerFile->setDownloadLink(
$this->router->generate(
'files_download_route',
['id' => $customerFile->getId()],
UrlGeneratorInterface::ABSOLUTE_URL
)
);
$customerFile->setDeleteLink(
$this->router->generate(
'customer_files_delete_route',
['id' => $customerFile->getId()],
UrlGeneratorInterface::ABSOLUTE_URL
)
);
}
}
}
}