Skip to content

Instantly share code, notes, and snippets.

@pchelk1n
Last active October 30, 2019 07:21
Show Gist options
  • Save pchelk1n/7ec1869ee523b6119cf302f3779d69d6 to your computer and use it in GitHub Desktop.
Save pchelk1n/7ec1869ee523b6119cf302f3779d69d6 to your computer and use it in GitHub Desktop.
Symfony Request argument resolver
<?php
namespace App\ArgumentResolver;
use Symfony\Component\Validator\ConstraintViolationListInterface;
class AbstractRequestData
{
/**
* @var ConstraintViolationListInterface
*/
public $errors;
}
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class ExampleController extends AbstractController
{
/**
* @Route("/example", name="example")
*/
public function exampleAction(ExampleFormRequest $exampleFormRequest, Request $request): Response
{
if (Request::METHOD_POST === $request->getMethod() && 0 === count($exampleFormRequest->errors)) {
//..... do some logic
}
// return Response;
}
}
<?php
namespace App\Controller;
use App\Service\ArgumentResolver\AbstractRequestData;
use Symfony\Component\Validator\Constraints as Assert;
class ExampleFormRequest extends AbstractRequestData
{
/**
* @Assert\NotBlank(message="Укажите ваше имя")
*/
public $name;
/**
* @Assert\NotBlank(message="Укажите телефон")
*/
public $phone;
}
<?php
namespace App\ArgumentResolver;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
class RequestDataResolver implements ArgumentValueResolverInterface
{
private $validator;
private $denormalizer;
public function __construct(ValidatorInterface $validator, DenormalizerInterface $denormalizer)
{
$this->validator = $validator;
$this->denormalizer = $denormalizer;
}
public function supports(Request $request, ArgumentMetadata $argument): bool
{
return is_subclass_of($argument->getType(), AbstractRequestData::class);
}
public function resolve(Request $request, ArgumentMetadata $argument): \Generator
{
$class = $argument->getType();
$data = new $class();
if (Request::METHOD_POST === $request->getMethod()) {
$requestData = array_map('trim', $request->request->all());
$requestData = array_merge($requestData, $request->files->all());
/** @var AbstractRequestData $data */
$data = $this->denormalizer->denormalize($requestData, $argument->getType());
$data->errors = $this->validator->validate($data);
}
yield $data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment