src/EventSubscriber/ResolveMediaContentUrlSubscriber.php line 31

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventSubscriber;
  4. use ApiPlatform\Core\EventListener\EventPriorities;
  5. use ApiPlatform\Core\Util\RequestAttributesExtractor;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\HttpKernel\Event\ViewEvent;
  9. use Symfony\Component\HttpKernel\KernelEvents;
  10. use App\Entity\Media;
  11. use App\Model\Utility\S3Utility;
  12. final class ResolveMediaContentUrlSubscriber implements EventSubscriberInterface {
  13.   private $s3Utility;
  14.   public function __construct(S3Utility $s3Utility) {
  15.     $this->s3Utility $s3Utility;
  16.   }
  17.   public static function getSubscribedEvents(): array {
  18.     return [
  19.       KernelEvents::VIEW => ['onPreSerialize'EventPriorities::PRE_SERIALIZE],
  20.     ];
  21.   }
  22.   public function onPreSerialize(ViewEvent $event): void {
  23.     $controllerResult $event->getControllerResult();
  24.     $request $event->getRequest();
  25.     if ($controllerResult instanceof Response || !$request->attributes->getBoolean('_api_respond'true)) {
  26.       return;
  27.     }
  28.     if (!($attributes RequestAttributesExtractor::extractAttributes($request)) || !\is_a($attributes['resource_class'], Media::class, true)) {
  29.       return;
  30.     }
  31.     $medias $controllerResult;
  32.     if (!is_iterable($medias)) {
  33.       $medias = [$medias];
  34.     }
  35.     foreach ($medias as $media) {
  36.       if (!$media instanceof Media) {
  37.         continue;
  38.       }
  39.       $media->contentUrl $this->s3Utility->getPresignedUrl($media);
  40.     }
  41.   }
  42. }