Goal-Calibration/app/Text/TextController.php
Yisroel Baum bac8323806
extract user from session in text controller
prevent payload from spoofing ownership by reading the user
from the request attribute set by auth middleware. respond 401
when unauthenticated.
2026-05-02 21:27:36 +03:00

94 lines
2.6 KiB
PHP

<?php
namespace App\Text;
use App\User\User;
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;
$user = $request->getAttribute('user');
if (!$user instanceof User) {
return $this->errorResponse(
$response,
401,
'unauthenticated'
);
}
try {
$text = $createTextUseCase->execute(new CreateTextRequest(
name: $name,
user: $user,
));
} 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');
}
private function errorResponse(
Response $response,
int $status,
string $message,
): Response {
$response->getBody()->write(
json_encode(['error' => $message])
);
return $response->withStatus($status)
->withHeader('Content-Type', 'application/json');
}
}