Add TextController for texts API
This commit is contained in:
parent
cb8c24d078
commit
ec32ca0103
1 changed files with 53 additions and 0 deletions
53
app/Text/TextController.php
Normal file
53
app/Text/TextController.php
Normal file
|
|
@ -0,0 +1,53 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Text;
|
||||||
|
|
||||||
|
use App\Text\TextRepository;
|
||||||
|
use App\Text\UseCases\CreateText;
|
||||||
|
use App\Text\UseCases\CreateTextRequest;
|
||||||
|
use Psr\Http\Message\ResponseInterface as Response;
|
||||||
|
use Psr\Http\Message\ServerRequestInterface as Request;
|
||||||
|
|
||||||
|
class TextController
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private TextRepository $textRepository,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public function getTexts(Response $response): Response
|
||||||
|
{
|
||||||
|
$texts = $this->textRepository->getAll();
|
||||||
|
|
||||||
|
$data = array_map(fn($text) => [
|
||||||
|
'id' => $text->getId(),
|
||||||
|
'name' => $text->getName(),
|
||||||
|
], $texts);
|
||||||
|
|
||||||
|
$response->getBody()->write(json_encode($data));
|
||||||
|
return $response->withHeader('Content-Type', 'application/json');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function createText(
|
||||||
|
Request $request,
|
||||||
|
Response $response,
|
||||||
|
CreateText $createTextUseCase,
|
||||||
|
): Response {
|
||||||
|
$data = $request->getParsedBody();
|
||||||
|
$name = $data['name'] ?? '';
|
||||||
|
|
||||||
|
if (!empty($name)) {
|
||||||
|
$text = $createTextUseCase->execute(new CreateTextRequest(
|
||||||
|
name: $name,
|
||||||
|
));
|
||||||
|
|
||||||
|
$response->getBody()->write(json_encode([
|
||||||
|
'id' => $text->getId(),
|
||||||
|
'name' => $text->getName(),
|
||||||
|
]));
|
||||||
|
return $response->withHeader('Content-Type', 'application/json');
|
||||||
|
}
|
||||||
|
|
||||||
|
$response->getBody()->write(json_encode(['error' => 'Name is required']));
|
||||||
|
return $response->withStatus(400);
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue