src/EventSubscriber/ResolveMediaObjectContentUrlSubscriber.php line 27

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use ApiPlatform\Symfony\EventListener\EventPriorities;
  4. use ApiPlatform\Util\RequestAttributesExtractor;
  5. use App\Entity\MediaObject;
  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 Vich\UploaderBundle\Storage\StorageInterface;
  11. final class ResolveMediaObjectContentUrlSubscriber implements EventSubscriberInterface
  12. {
  13.     public function __construct(private readonly StorageInterface $storage)
  14.     {
  15.     }
  16.     public static function getSubscribedEvents(): array
  17.     {
  18.         return [
  19.             KernelEvents::VIEW => ['onPreSerialize'EventPriorities::PRE_SERIALIZE],
  20.         ];
  21.     }
  22.     public function onPreSerialize(ViewEvent $event): void
  23.     {
  24.         $controllerResult $event->getControllerResult();
  25.         $request $event->getRequest();
  26.         if ($controllerResult instanceof Response || !$request->attributes->getBoolean('_api_respond'true)) {
  27.             return;
  28.         }
  29.         if (!($attributes RequestAttributesExtractor::extractAttributes($request)) || !\is_a($attributes['resource_class'], MediaObject::class, true)) {
  30.             return;
  31.         }
  32.         $mediaObjects $controllerResult;
  33.         if (!is_iterable($mediaObjects)) {
  34.             $mediaObjects = [$mediaObjects];
  35.         }
  36.         foreach ($mediaObjects as $mediaObject) {
  37.             if (!$mediaObject instanceof MediaObject) {
  38.                 continue;
  39.             }
  40.             $mediaObject->contentUrl $this->storage->resolveUri($mediaObject'file');
  41.         }
  42.     }
  43. }