<?php
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use ApiPlatform\Core\Util\RequestAttributesExtractor;
use App\Entity\UndanewsMediaObject;
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 ResolveUndanewsMediaObjectContentUrlSubscriber 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'], UndanewsMediaObject::class, true)) {
return;
}
$undanewsMediaObjects = $controllerResult;
if (!is_iterable($undanewsMediaObjects)) {
$undanewsMediaObjects = [$undanewsMediaObjects];
}
foreach ($undanewsMediaObjects as $undanewsMediaObject) {
if (!$undanewsMediaObject instanceof UndanewsMediaObject) {
continue;
}
$undanewsMediaObject->setContentUrl($this->storage->resolveUri($undanewsMediaObject, 'file'));
}
}
}