<?php
namespace App\EventListener;
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
use App\Services\MessageResponderService;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ViewEvent;
class DeleteRespondListener
{
/**
* @var MessageResponderService
*/
private $messageResponder;
/**
* @var ResourceMetadataFactoryInterface
*/
private $resourceMetadataFactory;
public function __construct(
MessageResponderService $messageResponder,
ResourceMetadataFactoryInterface $resourceMetadataFactory
) {
$this->messageResponder = $messageResponder;
$this->resourceMetadataFactory = $resourceMetadataFactory;
}
public function onKernelView(ViewEvent $event): void
{
$resourceClass = $event->getRequest()->get('_api_resource_class');
if (!$resourceClass) {
return;
}
$resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
$shortName = (string) $resourceMetadata->getShortName();
$request = $event->getRequest();
if ($request->isMethod('DELETE')) {
$this->messageResponder->setCode(sprintf('%s.itemSuccessfulyRemoved', strtolower($shortName)));
$this->messageResponder->setStatus(Response::HTTP_OK);
$event->setResponse($this->messageResponder->send());
}
}
}