<?php
declare(strict_types=1);
namespace App\Shop\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Shop\Doctrine\Entity\Brand;
use App\Shop\Doctrine\Entity\Product;
use App\Shop\Doctrine\Entity\Taxonomy;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
final class CollectionSubscriber implements EventSubscriberInterface
{
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array
{
return [
KernelEvents::CONTROLLER => [
['hasFilter', EventPriorities::PRE_READ],
],
];
}
public function hasFilter(ControllerEvent $event): void
{
$resource = $event->getRequest()->attributes->get('_api_resource_class');
if (!in_array($resource, [Brand::class, Taxonomy::class, Product::class], true)) {
return;
}
$controller = $event->getRequest()->attributes->get('_controller');
if ('api_platform.action.get_collection' !== $controller) {
return;
}
if (
!$event->getRequest()->query->has('profile')
|| '' === $event->getRequest()->query->get('profile')
) {
throw new BadRequestHttpException('Filter `profile` is required');
}
}
}