<?php
namespace App\EventListener\PostValidate;
use ApiPlatform\Core\Metadata\Resource\ToggleableOperationAttributeTrait;
use ApiPlatform\Core\Util\RequestAttributesExtractor;
use ApiPlatform\Core\Validator\EventListener\ValidateListener;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class PostValidateListener implements EventSubscriberInterface
{
use ToggleableOperationAttributeTrait;
const POST_VALIDATE_TRANSFORMATION = 'POST_VALIDATE_TRANSFORMATION';
/**
* @var EventDispatcherInterface
*/
private $eventDispatcher;
public function __construct(EventDispatcherInterface $eventDispatcher)
{
$this->eventDispatcher = $eventDispatcher;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => 'onKernelView',
];
}
public function onKernelView(ViewEvent $event)
{
$controllerResult = $event->getControllerResult();
$request = $event->getRequest();
if ($controllerResult instanceof Response
|| $request->isMethodSafe()
|| $request->isMethod('DELETE')
|| !($attributes = RequestAttributesExtractor::extractAttributes($request))
|| !$attributes['receive']
|| $this->isOperationAttributeDisabled($attributes, ValidateListener::OPERATION_ATTRIBUTE_KEY)
) {
return;
}
$this->eventDispatcher->dispatch($event, self::POST_VALIDATE_TRANSFORMATION);
}
}