<?php
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\Template;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Vich\UploaderBundle\Storage\StorageInterface;
class ResolveTemplateUrl implements EventSubscriberInterface
{
private $storage;
public function __construct(StorageInterface $storage)
{
$this->storage = $storage;
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::VIEW => ["onPreSerialize", EventPriorities::PRE_SERIALIZE],
];
}
public function onPreSerialize(ViewEvent $event)
{
$controllerResult = $event->getControllerResult();
$request = $event->getRequest();
if ($controllerResult instanceof Response || !$request->attributes->getBoolean('_api_respond', true)) {
return;
}
$mediaObjects = $controllerResult;
if (!is_iterable($mediaObjects)) {
$mediaObjects = [$mediaObjects];
}
foreach ($mediaObjects as $mediaObject) {
if (!$mediaObject instanceof Template)
continue;
if ($filePath = $this->storage->resolveUri($mediaObject, "file"))
$mediaObject->setFilePath($filePath);
}
}
}