Skip to content

Instantly share code, notes, and snippets.

@ismail1432
Last active December 25, 2022 20:06
Show Gist options
  • Save ismail1432/37df494c0badb0f986a95d981522f44f to your computer and use it in GitHub Desktop.
Save ismail1432/37df494c0badb0f986a95d981522f44f to your computer and use it in GitHub Desktop.
<?php
namespace App\Application;
use App\Domain\CreateAUserHandler;
use App\Domain\CreateAUserInput;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Validator\ValidatorInterface;
final class CreateAUserAction
{
private ValidatorInterface $validator;
private CreateAUserHandler $handler;
public function __construct(ValidatorInterface $validator, CreateAUserHandler $handler)
{
$this->validator = $validator;
$this->handler = $handler;
}
/**
* @Route("/users", name="user_post", methods={"POST"}))
*/
public function __invoke(Request $request)
{
$payload = new CreateAUserPayload($request->request('name'), $request->request('age'));
$errors = $this->validator->validate($payload);
if ($errors->count() > 0) {
throw new BadRequestHttpException("Invalid payload blabla...");
}
$input = new CreateAUserInput($payload->name, $payload->age);
$output = $this->handler->execute($input);
return new JsonResponse([
'id' => $output->getId(),
'name' => $output->getName(),
'age' => $output->getAge(),
], 201);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment