<?php
declare(strict_types=1);
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use ApiPlatform\Core\Util\RequestAttributesExtractor;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use App\Entity\Media;
use App\Model\Utility\S3Utility;
final class ResolveMediaContentUrlSubscriber implements EventSubscriberInterface {
private $s3Utility;
public function __construct(S3Utility $s3Utility) {
$this->s3Utility = $s3Utility;
}
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'], Media::class, true)) {
return;
}
$medias = $controllerResult;
if (!is_iterable($medias)) {
$medias = [$medias];
}
foreach ($medias as $media) {
if (!$media instanceof Media) {
continue;
}
$media->contentUrl = $this->s3Utility->getPresignedUrl($media);
}
}
}