src/EventSubscriber/ResolveUndanitaMediaObjectContentUrlSubscriber.php line 38

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\UndanitaMediaObject;
  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. class ResolveUndanitaMediaObjectContentUrlSubscriber implements EventSubscriberInterface
  12. {
  13.     /**
  14.      * @var StorageInterface
  15.      */
  16.     private $storage;
  17.     public function __construct(StorageInterface $storage)
  18.     {
  19.         $this->storage $storage;
  20.     }
  21.     /**
  22.      * @inheritDoc
  23.      */
  24.     public static function getSubscribedEvents(): array
  25.     {
  26.         return [
  27.             KernelEvents::VIEW => ['onPreSerialize'EventPriorities::PRE_SERIALIZE],
  28.         ];
  29.     }
  30.     public function onPreSerialize(ViewEvent $event): void
  31.     {
  32.         $controllerResult $event->getControllerResult();
  33.         $request $event->getRequest();
  34.         if ($controllerResult instanceof Response || !$request->attributes->getBoolean('_api_respond'true)) {
  35.             return;
  36.         }
  37.         if (!($attributes RequestAttributesExtractor::extractAttributes($request))
  38.             || !\is_a($attributes['resource_class'], UndanitaMediaObject::class, true)) {
  39.             return;
  40.         }
  41.         $undanitaMediaObjects $controllerResult;
  42.         if (!is_iterable($undanitaMediaObjects)) {
  43.             $undanitaMediaObjects = [$undanitaMediaObjects];
  44.         }
  45.         foreach ($undanitaMediaObjects as $undanitaMediaObject) {
  46.             if (!$undanitaMediaObject instanceof UndanitaMediaObject) {
  47.                 continue;
  48.             }
  49.             $undanitaMediaObject->setContentUrl($this->storage->resolveUri($undanitaMediaObject'file'));
  50.         }
  51.     }
  52. }