Last active
December 25, 2022 20:06
-
-
Save ismail1432/feb241cb99862a767c69e9a3349af6fc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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