Skip to content

Instantly share code, notes, and snippets.

@dlegatt
Last active April 21, 2024 12:16
Show Gist options
  • Save dlegatt/3dc81aeee375d13a3d86b782cdb5a6bf to your computer and use it in GitHub Desktop.
Save dlegatt/3dc81aeee375d13a3d86b782cdb5a6bf to your computer and use it in GitHub Desktop.
Example of how to handle entity deserialization and validation without a form type class in Symfony
<?php
/** DefaultController.php **/
namespace AppBundle\Controller;
use AppBundle\Entity\Person;
use AppBundle\Service\RequestHandler;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Twig\Environment;
class DefaultController
{
/** @var Environment */
private $twig;
/** @var RequestHandler */
private $handler;
/**
* DefaultController constructor.
* @param Environment $twig
* @param RequestHandler $handler
*/
public function __construct(Environment $twig, RequestHandler $handler)
{
$this->twig = $twig;
$this->handler = $handler;
}
/**
* @Route("/", name="homepage")
* @param Request $request
* @return Response
*/
public function indexAction(Request $request)
{
$person = $this->handler->handle($request, Person::class);
// replace this example code with whatever you need
return new Response($this->twig->render('default/index.html.twig', ['person' => $person]));
}
}
/** RequestHandler.php **/
namespace AppBundle\Service;
use Symfony\Component\HttpFoundation\HeaderBag;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
class RequestHandler
{
/** @var ValidatorInterface */
private $validator;
/** @var SerializerInterface */
private $serializer;
/**
* RequestHandler constructor.
* @param ValidatorInterface $validator
* @param SerializerInterface $serializer
*/
public function __construct(ValidatorInterface $validator, SerializerInterface $serializer)
{
$this->validator = $validator;
$this->serializer = $serializer;
}
public function handle(Request $request, string $class)
{
$format = $this->getFormat($request->headers);
$entity = $this->serializer->deserialize($request->getContent(),$class,$format);
$errors = $this->validator->validate($entity);
if ($errors->count() > 0){
throw new BadRequestHttpException('Validation failed!');
}
return $entity;
}
private function getFormat(HeaderBag $headers)
{
$type = $headers->get('content-type');
switch ($type){
case 'application/json':
default:
return 'json';
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment