src/EventSubscriber/CompanyConfigurationSubscriber.php line 23

  1. <?php
  2. namespace App\EventSubscriber;
  3. use ApiPlatform\Symfony\EventListener\EventPriorities;
  4. use ApiPlatform\Util\RequestAttributesExtractor;
  5. use App\Document\Company\CompanyConfiguration;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\HttpFoundation\Request;
  8. use Symfony\Component\HttpKernel\Event\ViewEvent;
  9. use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
  10. use Symfony\Component\HttpKernel\KernelEvents;
  11. class CompanyConfigurationSubscriber implements EventSubscriberInterface
  12. {
  13.     public static function getSubscribedEvents(): array
  14.     {
  15.         return [
  16.             KernelEvents::VIEW => ['checkConfiguration'EventPriorities::POST_VALIDATE],
  17.         ];
  18.     }
  19.     public function checkConfiguration(ViewEvent $event): void
  20.     {
  21.         $request $event->getRequest();
  22.         $attributes RequestAttributesExtractor::extractAttributes($request);
  23.         $resourceClass $attributes['resource_class'] ?? null;
  24.         $configuration $event->getControllerResult();
  25.         if (CompanyConfiguration::class !== $resourceClass
  26.             or !$configuration instanceof CompanyConfiguration
  27.             or !$request->isMethod(Request::METHOD_POST)
  28.         ) {
  29.             return;
  30.         }
  31.         $company $configuration->getCompany();
  32.         if ($company->getConfiguration()?->getId()) {
  33.             throw new ConflictHttpException('The company already has a configuration.');
  34.         }
  35.     }
  36. }