src/EventSubscriber/ResolveUndanewsMediaObjectContentUrlSubscriber.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\UndanewsMediaObject;
  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 ResolveUndanewsMediaObjectContentUrlSubscriber 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'], UndanewsMediaObject::class, true)) {
  39.             return;
  40.         }
  41.         $undanewsMediaObjects $controllerResult;
  42.         if (!is_iterable($undanewsMediaObjects)) {
  43.             $undanewsMediaObjects = [$undanewsMediaObjects];
  44.         }
  45.         foreach ($undanewsMediaObjects as $undanewsMediaObject) {
  46.             if (!$undanewsMediaObject instanceof UndanewsMediaObject) {
  47.                 continue;
  48.             }
  49.             $undanewsMediaObject->setContentUrl($this->storage->resolveUri($undanewsMediaObject'file'));
  50.         }
  51.     }
  52. }