src/EventSubscriber/ResolveBenefitMediaObjectContentUrlSubscriber.php line 39

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\BenefitMediaObject;
  6. use phpDocumentor\Reflection\Types\This;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\HttpFoundation\Response;
  9. use Symfony\Component\HttpKernel\Event\ViewEvent;
  10. use Symfony\Component\HttpKernel\KernelEvents;
  11. use Vich\UploaderBundle\Storage\StorageInterface;
  12. class ResolveBenefitMediaObjectContentUrlSubscriber implements EventSubscriberInterface
  13. {
  14.     /**
  15.      * @var StorageInterface
  16.      */
  17.     private $storage;
  18.     public function __construct(StorageInterface $storage)
  19.     {
  20.         $this->storage $storage;
  21.     }
  22.     /**
  23.      * @inheritDoc
  24.      */
  25.     public static function getSubscribedEvents(): array
  26.     {
  27.         return [
  28.             KernelEvents::VIEW => ['onPreSerialize'EventPriorities::PRE_SERIALIZE],
  29.         ];
  30.     }
  31.     public function onPreSerialize(ViewEvent $viewEvent): void
  32.     {
  33.         $controllerResult $viewEvent->getControllerResult();
  34.         $request $viewEvent->getRequest();
  35.         if ($controllerResult instanceof Response || !$request->attributes->getBoolean('_api_respond'true)) {
  36.             return;
  37.         }
  38.         if (!($attributes RequestAttributesExtractor::extractAttributes($request))
  39.             || !\is_a($attributes['resource_class'], BenefitMediaObject::class, true)) {
  40.             return;
  41.         }
  42.         $benefitMediaObjects $controllerResult;
  43.         if (!is_iterable($benefitMediaObjects)) {
  44.             $benefitMediaObjects = [$benefitMediaObjects];
  45.         }
  46.         foreach ($benefitMediaObjects as $benefitMediaObject) {
  47.             if (!$benefitMediaObject instanceof BenefitMediaObject) {
  48.                 continue;
  49.             }
  50.             $benefitMediaObject->setContentUrl($this->storage->resolveUri($benefitMediaObject'file'));
  51.         }
  52.     }
  53. }