Skip to content

Instantly share code, notes, and snippets.

@adrianuf22
Last active September 20, 2018 21:10
Show Gist options
  • Save adrianuf22/af043a16a9f565696957933cbacc831e to your computer and use it in GitHub Desktop.
Save adrianuf22/af043a16a9f565696957933cbacc831e to your computer and use it in GitHub Desktop.
Middleware Sample
<?php
declare(strict_types = 1);
class SampleController
{
public function sampleAction()
{
$payload = $request->getAttribute('dataObject');
// Do something
return new JsonResponse(
['actionId' => 1],
204
);
}
}
<?php
declare(strict_types = 1);
namespace Listener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\PropertyInfo\Extractor\PhpDocExtractor;
use Symfony\Component\Routing\Router;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Exception\Domain\Model\Exception\MalformedRequestException;
use Exception\Domain\Model\Exception\SymfonyValidationException;
class SampleRequestListener
{
public function __construct(
Router $router,
ValidatorInterface $validator
) {
$this->router = $router;
$this->validator = $validator;
}
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
$routeCollection = $this->router->getRouteCollection();
$route = $routeCollection->get($request->get('_route'));
$data_object = $route->getOption('data_object');
if (!$data_object) {
return;
}
$payload = json_decode($request->getContent(), true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw MalformedRequestException::fromJsonErrorCode(json_last_error());
}
if (empty($payload)) {
throw MalformedRequestException::forEmptyBody();
}
$serializer = new Serializer([new ObjectNormalizer(null, null, null, new PhpDocExtractor())]);
$dto = $serializer->denormalize($payload, $data_object);
$violations = $this->validator->validate($dto);
if (count($violations) > 0) {
throw SymfonyValidationException::fromConstraintViolations($violations);
}
$request->attributes->add(['dataObject' => $dto]);
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service
id="sample.listener"
class="Listener\SampleRequestListener">
<argument type="service" id="router" />
<argument type="service" id="validator" />
<tag name="kernel.event_listener" event="kernel.controller_arguments" />
<tag name="kernel.event_listener" event="kernel.request" method="onKernelRequest" />
</service>
</services>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment