Goal-Calibration/app/Text/TextController.php

71 lines
2 KiB
PHP

<?php
namespace App\Text;
use App\Exceptions\BadRequestException;
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(function ($text) {
return [
'id' => $text->getId(),
'name' => $text->getName(),
];
}, $texts);
$response->getBody()->write(json_encode($data));
return $response->withHeader('Content-Type', 'application/json');
}
public function getText(Response $response, int $textId): Response
{
$text = $this->textRepository->find($textId);
if ($text === null) {
return $response->withStatus(404);
}
$response->getBody()->write(json_encode([
'id' => $text->getId(),
'name' => $text->getName(),
]));
return $response->withHeader('Content-Type', 'application/json');
}
public function createText(
Request $request,
Response $response,
CreateText $createTextUseCase,
): Response {
$data = $request->getParsedBody();
$name = $data['name'] ?? null;
try {
$text = $createTextUseCase->execute(new CreateTextRequest(
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([
'id' => $text->getId(),
'name' => $text->getName(),
]));
return $response->withHeader('Content-Type', 'application/json');
}
}