src/Shop/EventSubscriber/CollectionSubscriber.php line 30

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Shop\EventSubscriber;
  4. use ApiPlatform\Core\EventListener\EventPriorities;
  5. use App\Shop\Doctrine\Entity\Brand;
  6. use App\Shop\Doctrine\Entity\Product;
  7. use App\Shop\Doctrine\Entity\Taxonomy;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  10. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  11. use Symfony\Component\HttpKernel\KernelEvents;
  12. final class CollectionSubscriber implements EventSubscriberInterface
  13. {
  14.     /**
  15.      * {@inheritdoc}
  16.      */
  17.     public static function getSubscribedEvents(): array
  18.     {
  19.         return [
  20.             KernelEvents::CONTROLLER => [
  21.                 ['hasFilter'EventPriorities::PRE_READ],
  22.             ],
  23.         ];
  24.     }
  25.     public function hasFilter(ControllerEvent $event): void
  26.     {
  27.         $resource $event->getRequest()->attributes->get('_api_resource_class');
  28.         if (!in_array($resource, [Brand::class, Taxonomy::class, Product::class], true)) {
  29.             return;
  30.         }
  31.         $controller $event->getRequest()->attributes->get('_controller');
  32.         if ('api_platform.action.get_collection' !== $controller) {
  33.             return;
  34.         }
  35.         if (
  36.             !$event->getRequest()->query->has('profile')
  37.             || '' === $event->getRequest()->query->get('profile')
  38.         ) {
  39.             throw new BadRequestHttpException('Filter `profile` is required');
  40.         }
  41.     }
  42. }