Skip to content

Instantly share code, notes, and snippets.

@ismail1432
Last active December 25, 2022 20:06
Show Gist options
  • Save ismail1432/feb241cb99862a767c69e9a3349af6fc to your computer and use it in GitHub Desktop.
Save ismail1432/feb241cb99862a767c69e9a3349af6fc to your computer and use it in GitHub Desktop.
<?php
namespace App\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class CreateAUserController
{
/**
* @Route("/users",
* name="create",
* methods="POST",
* defaults={
* "_validator": { // the " _validator" name is totally custom, choose what you want.
* "name":"NotBlank",
* "email":"Email"
* }
* })
*/
public function create(Request $request): JsonResponse
{
// retrieve errors that are set in the our listener
$errors = $request->attributes->get('_errors');
// return 400 in case of errors
if ([] !== $errors) {
return new JsonResponse($this->formatError($errors), 400);
}
// boring stuff to create the user
return new JsonResponse($user, 201);
}
// Helper to properly return the errors
private function formatError(ConstraintViolationList $constraintViolationList): array
{
$format = [];
foreach ($constraintViolationList as $violation) {
$format[] = [
'property' => $violation->getPropertyPath(),
'message' => $violation->getMessage()
];
}
return $format;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment