src/EventSubscriber/ResolveAbsenceSupportingDocumentContentUrlSubscriber.php line 34

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\AbsenceSupportingDocument;
  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. use function is_a;
  12. class ResolveAbsenceSupportingDocumentContentUrlSubscriber implements EventSubscriberInterface
  13. {
  14.     private $storage;
  15.     public function __construct(StorageInterface $storage)
  16.     {
  17.         $this->storage $storage;
  18.     }
  19.     public static function getSubscribedEvents(): array
  20.     {
  21.         return [
  22.             KernelEvents::VIEW => ['onPreSerialize'EventPriorities::PRE_SERIALIZE],
  23.         ];
  24.     }
  25.     public function onPreSerialize(ViewEvent $event): void
  26.     {
  27.         $controllerResult $event->getControllerResult();
  28.         $request $event->getRequest();
  29.         if ($controllerResult instanceof Response || !$request->attributes->getBoolean('_api_respond'true)) {
  30.             return;
  31.         }
  32.         if (!($attributes RequestAttributesExtractor::extractAttributes($request))
  33.             || !is_a($attributes['resource_class'], AbsenceSupportingDocument::class, true)) {
  34.             return;
  35.         }
  36.         $absenceSupportingDocuments $controllerResult;
  37.         if (!is_iterable($absenceSupportingDocuments)) {
  38.             $absenceSupportingDocuments = [$absenceSupportingDocuments];
  39.         }
  40.         foreach ($absenceSupportingDocuments as $absenceSupportingDocument) {
  41.             if (!$absenceSupportingDocument instanceof AbsenceSupportingDocument) {
  42.                 continue;
  43.             }
  44.             $absenceSupportingDocument->setContentUrl($this->storage->resolveUri($absenceSupportingDocument'file'));
  45.         }
  46.     }
  47. }