refactor create text controller to catch BadRequestException

This commit is contained in:
Yisroel Baum 2026-04-19 23:38:23 +03:00
parent 82dab3b90f
commit 6009fb7ddd
Signed by: yisroelbaum
GPG key ID: 0FA60884F75520A9

View file

@ -2,6 +2,7 @@
namespace App\Text; namespace App\Text;
use App\Exceptions\BadRequestException;
use App\Text\TextRepository; use App\Text\TextRepository;
use App\Text\UseCases\CreateText; use App\Text\UseCases\CreateText;
use App\Text\UseCases\CreateTextRequest; use App\Text\UseCases\CreateTextRequest;
@ -50,12 +51,16 @@ class TextController
CreateText $createTextUseCase, CreateText $createTextUseCase,
): Response { ): Response {
$data = $request->getParsedBody(); $data = $request->getParsedBody();
$name = $data['name'] ?? ''; $name = $data['name'] ?? null;
if (!empty($name)) { try {
$text = $createTextUseCase->execute(new CreateTextRequest( $text = $createTextUseCase->execute(new CreateTextRequest(
name: $name, name: $name,
)); ));
} catch (BadRequestException $e) {
$response->getBody()->write(json_encode(['error' => $e->getMessage()]));
return $response->withStatus(400)->withHeader('Content-Type', 'application/json');
}
$response->getBody()->write(json_encode([ $response->getBody()->write(json_encode([
'id' => $text->getId(), 'id' => $text->getId(),
@ -63,8 +68,4 @@ class TextController
])); ]));
return $response->withHeader('Content-Type', 'application/json'); return $response->withHeader('Content-Type', 'application/json');
} }
$response->getBody()->write(json_encode(['error' => 'Name is required']));
return $response->withStatus(400);
}
} }