src/EventSubscriber/ResolveTemplateUrl.php line 30

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use ApiPlatform\Core\EventListener\EventPriorities;
  4. use App\Entity\Template;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Symfony\Component\HttpKernel\Event\ViewEvent;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. use Vich\UploaderBundle\Storage\StorageInterface;
  10. class ResolveTemplateUrl implements EventSubscriberInterface
  11. {
  12.     private $storage;
  13.     public function __construct(StorageInterface $storage)
  14.     {
  15.         $this->storage $storage;
  16.     }
  17.     public static function getSubscribedEvents(): array
  18.     {
  19.         return [
  20.             KernelEvents::VIEW => ["onPreSerialize"EventPriorities::PRE_SERIALIZE],
  21.         ];
  22.     }
  23.     public function onPreSerialize(ViewEvent $event)
  24.     {
  25.         $controllerResult $event->getControllerResult();
  26.         $request $event->getRequest();
  27.         if ($controllerResult instanceof Response || !$request->attributes->getBoolean('_api_respond'true)) {
  28.             return;
  29.         }
  30.         $mediaObjects $controllerResult;
  31.         if (!is_iterable($mediaObjects)) {
  32.             $mediaObjects = [$mediaObjects];
  33.         }
  34.         foreach ($mediaObjects as $mediaObject) {
  35.             if (!$mediaObject instanceof Template)
  36.                 continue;
  37.             if ($filePath $this->storage->resolveUri($mediaObject"file"))
  38.                 $mediaObject->setFilePath($filePath);
  39.         }
  40.     }
  41. }