src/EventSubscriber/ResolveProductMediaObjectContentUrlSubscriber.php line 28

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use ApiPlatform\Symfony\EventListener\EventPriorities;
  4. use ApiPlatform\Util\RequestAttributesExtractor;
  5. use App\Entity\MediaObject;
  6. use App\Entity\Product;
  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. final class ResolveProductMediaObjectContentUrlSubscriber implements EventSubscriberInterface
  13. {
  14.     public function __construct(private readonly StorageInterface $storage)
  15.     {
  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): void
  24.     {
  25.         $controllerResult $event->getControllerResult();
  26.         $request $event->getRequest();
  27.         if ($controllerResult instanceof Response || !$request->attributes->getBoolean('_api_respond'true)) {
  28.             return;
  29.         }
  30.         if (!($attributes RequestAttributesExtractor::extractAttributes($request)) || !\is_a($attributes['resource_class'], Product::class, true)) {
  31.             return;
  32.         }
  33.         $products $controllerResult;
  34.         if (!is_iterable($products)) {
  35.             $products = [$products];
  36.         }
  37.         foreach ($products as $product) {
  38.             /** @var $product Product */
  39.             if (!$product instanceof Product) {
  40.                 continue;
  41.             }
  42.             $packshot $product->getPackshot();
  43.             if($packshot instanceof MediaObject){
  44.                 $product->packshotUrl $this->storage->resolveUri($packshot'file');
  45.             }
  46.             $producerImage $product->getProducerImage();
  47.             if($producerImage instanceof MediaObject){
  48.                 $product->producerImageUrl $this->storage->resolveUri($producerImage'file');
  49.             }
  50.         }
  51.     }
  52. }