<?php
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use ApiPlatform\Core\Util\RequestAttributesExtractor;
use App\Entity\UndanitaMediaObject;
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 ResolveUndanitaMediaObjectContentUrlSubscriber implements EventSubscriberInterface
{
/**
* @var StorageInterface
*/
private $storage;
public function __construct(StorageInterface $storage)
{
$this->storage = $storage;
}
/**
* @inheritDoc
*/
public static function getSubscribedEvents(): array
{
return [
KernelEvents::VIEW => ['onPreSerialize', EventPriorities::PRE_SERIALIZE],
];
}
public function onPreSerialize(ViewEvent $event): void
{
$controllerResult = $event->getControllerResult();
$request = $event->getRequest();
if ($controllerResult instanceof Response || !$request->attributes->getBoolean('_api_respond', true)) {
return;
}
if (!($attributes = RequestAttributesExtractor::extractAttributes($request))
|| !\is_a($attributes['resource_class'], UndanitaMediaObject::class, true)) {
return;
}
$undanitaMediaObjects = $controllerResult;
if (!is_iterable($undanitaMediaObjects)) {
$undanitaMediaObjects = [$undanitaMediaObjects];
}
foreach ($undanitaMediaObjects as $undanitaMediaObject) {
if (!$undanitaMediaObject instanceof UndanitaMediaObject) {
continue;
}
$undanitaMediaObject->setContentUrl($this->storage->resolveUri($undanitaMediaObject, 'file'));
}
}
}