Skip to content

Instantly share code, notes, and snippets.

@thatside
Last active September 27, 2019 13:44
Show Gist options
  • Save thatside/43763e71fb8c8c8a4dffb3385e0927fa to your computer and use it in GitHub Desktop.
Save thatside/43763e71fb8c8c8a4dffb3385e0927fa to your computer and use it in GitHub Desktop.
<?php declare(strict_types=1);
namespace Common\ArgumentResolver;
use Common\Exception\ValidationErrorException;
use Common\Request\RequestData;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
use Symfony\Component\Validator\Validator\ValidatorInterface;
class RequestResolver implements ArgumentValueResolverInterface
{
private $validator;
public function __construct(ValidatorInterface $validator)
{
$this->validator = $validator;
}
public function supports(Request $request, ArgumentMetadata $argumentMetadata): bool
{
return is_subclass_of($argumentMetadata->getType(), RequestData::class);
}
public function resolve(Request $request, ArgumentMetadata $argumentMetadata): \Generator
{
/** @var RequestData $requestData */
$requestData = $argumentMetadata->getType();
/** @var RequestData $mapped */
$mapped = $requestData::create($request->request);
$errors = $this->validator->validate($mapped);
if (count($errors)) {
throw new ValidationErrorException($errors);
}
yield $mapped;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment