src/EventsSubscriber/Device/DeviceEventSubscriber.php line 35

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventsSubscriber\Device;
  4. use ApiPlatform\Symfony\EventListener\EventPriorities;
  5. use ApiPlatform\Validator\ValidatorInterface;
  6. use App\Dto\Creator\Device\DeviceDto;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\HttpFoundation\Request;
  9. use Symfony\Component\HttpKernel\Event\RequestEvent;
  10. use Symfony\Component\HttpKernel\Event\ViewEvent;
  11. use Symfony\Component\HttpKernel\KernelEvents;
  12. use Symfony\Component\Serializer\SerializerInterface;
  13. class DeviceEventSubscriber implements EventSubscriberInterface
  14. {
  15.     private ?DeviceDto $deviceDto null;
  16.     public function __construct(
  17.         private readonly SerializerInterface $serializer,
  18.         private readonly ValidatorInterface $validator,
  19.     ) {
  20.     }
  21.     public static function getSubscribedEvents(): array
  22.     {
  23.         return [
  24.             KernelEvents::REQUEST => ['serialize'EventPriorities::PRE_READ],
  25.             KernelEvents::VIEW => ['write'EventPriorities::PRE_WRITE],
  26.         ];
  27.     }
  28.     public function serialize(RequestEvent $event): void
  29.     {
  30.         $request $event->getRequest();
  31.         if (
  32.             DeviceDto::class !== $request->attributes->get('_api_resource_class')
  33.             || Request::METHOD_PUT !== $request->getMethod()
  34.         ) {
  35.             return;
  36.         }
  37.         $dto $this->serializer->deserialize(
  38.             $request->getContent(),
  39.             $request->attributes->get('_api_resource_class'),
  40.             'json'
  41.         );
  42.         $this->validator->validate($dto);
  43.         $this->deviceDto $dto;
  44.     }
  45.     public function write(ViewEvent $event): void
  46.     {
  47.         $dto $event->getControllerResult();
  48.         $method $event->getRequest()->getMethod();
  49.         if (!$dto instanceof DeviceDto || Request::METHOD_PUT !== $method) {
  50.             return;
  51.         }
  52.         if ($this->deviceDto !== null) {
  53.             $event->setControllerResult($this->deviceDto);
  54.         }
  55.     }
  56. }