Goal-Calibration/app/Text/TextController.php

55 lines
1.5 KiB
PHP

<?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(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 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);
}
}