Goal-Calibration/app/Node/NodeController.php

78 lines
2.5 KiB
PHP

<?php
namespace App\Node;
use App\Node\NodeRepository;
use App\Node\UseCases\CreateNode;
use App\Node\UseCases\CreateNodeRequest;
use App\Text\TextRepository;
use DomainException;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
class NodeController
{
public function __construct(
private NodeRepository $nodeRepository,
private TextRepository $textRepository,
) {}
public function getNodesOfText(Response $response, int $textId): Response
{
$text = $this->textRepository->find($textId);
if ($text === null) {
return $response->withStatus(404);
}
$nodes = $this->nodeRepository->findByTextId($textId);
$data = array_map(function ($node) {
return [
'id' => $node->getId(),
'title' => $node->getTitle(),
'parentNodeId' => $node->getParentNode()?->getId(),
];
}, $nodes);
$response->getBody()->write(json_encode(array_values($data)));
return $response->withHeader('Content-Type', 'application/json');
}
public function createNode(
Request $request,
Response $response,
CreateNode $createNodeUseCase,
): Response {
$data = json_decode((string) $request->getBody(), true) ?? [];
$title = $data['title'] ?? '';
if (empty($title)) {
$response->getBody()->write(json_encode(['error' => 'Title is required']));
return $response->withStatus(400)->withHeader('Content-Type', 'application/json');
}
$textId = (int) ($data['textId'] ?? 0);
$parentNodeId = isset($data['parentNodeId']) && $data['parentNodeId'] !== null
? (int) $data['parentNodeId']
: null;
try {
$node = $createNodeUseCase->execute(new CreateNodeRequest(
textId: $textId,
title: $title,
parentNodeId: $parentNodeId,
));
} catch (DomainException $e) {
$response->getBody()->write(json_encode(['error' => $e->getMessage()]));
return $response->withStatus(404)->withHeader('Content-Type', 'application/json');
}
$response->getBody()->write(json_encode([
'id' => $node->getId(),
'title' => $node->getTitle(),
'parentNodeId' => $node->getParentNode()?->getId(),
]));
return $response->withStatus(201)->withHeader('Content-Type', 'application/json');
}
}