src/EventSubscriber/ResolveMediaObjectContentUrlSubscriber.php line 34

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