<?php
declare(strict_types=1);
namespace App\EventsSubscriber\Device;
use ApiPlatform\Symfony\EventListener\EventPriorities;
use ApiPlatform\Validator\ValidatorInterface;
use App\Dto\Creator\Device\DeviceDto;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Serializer\SerializerInterface;
class DeviceEventSubscriber implements EventSubscriberInterface
{
private ?DeviceDto $deviceDto = null;
public function __construct(
private readonly SerializerInterface $serializer,
private readonly ValidatorInterface $validator,
) {
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => ['serialize', EventPriorities::PRE_READ],
KernelEvents::VIEW => ['write', EventPriorities::PRE_WRITE],
];
}
public function serialize(RequestEvent $event): void
{
$request = $event->getRequest();
if (
DeviceDto::class !== $request->attributes->get('_api_resource_class')
|| Request::METHOD_PUT !== $request->getMethod()
) {
return;
}
$dto = $this->serializer->deserialize(
$request->getContent(),
$request->attributes->get('_api_resource_class'),
'json'
);
$this->validator->validate($dto);
$this->deviceDto = $dto;
}
public function write(ViewEvent $event): void
{
$dto = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if (!$dto instanceof DeviceDto || Request::METHOD_PUT !== $method) {
return;
}
if ($this->deviceDto !== null) {
$event->setControllerResult($this->deviceDto);
}
}
}