src/EventSubscriber/ResolveElementoImagenContentUrlSubscriber.php line 31

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\ElementoImagen;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
  9. use Symfony\Component\HttpKernel\KernelEvents;
  10. use Vich\UploaderBundle\Storage\StorageInterface;
  11. class ResolveElementoImagenContentUrlSubscriber implements EventSubscriberInterface
  12. {
  13.     private $storage;
  14.     public function __construct(StorageInterface $storage)
  15.     {
  16.         $this->storage $storage;
  17.     }
  18.     public static function getSubscribedEvents(): array
  19.     {
  20.         return [
  21.             KernelEvents::VIEW => ['onPreSerialize'EventPriorities::PRE_SERIALIZE],
  22.         ];
  23.     }
  24.     public function onPreSerialize(GetResponseForControllerResultEvent $event): void
  25.     {
  26.         $controllerResult $event->getControllerResult();
  27.         $request $event->getRequest();
  28.         if ($controllerResult instanceof Response || !$request->attributes->getBoolean('_api_respond'true)) {
  29.             return;
  30.         }
  31.         if (!($attributes RequestAttributesExtractor::extractAttributes($request)) || !\is_a($attributes['resource_class'], ElementoImagen::class, true)) {
  32.             return;
  33.         }
  34.         $mediaObjects $controllerResult;
  35.         if (!is_iterable($mediaObjects)) {
  36.             $mediaObjects = [$mediaObjects];
  37.         }
  38.         foreach ($mediaObjects as $mediaObject) {
  39.             if (!$mediaObject instanceof ElementoImagen) {
  40.                 continue;
  41.             }
  42.             $mediaObject->imageURL $this->storage->resolveUri($mediaObject'imageFile');
  43.         }
  44.     }
  45. }