implement create node method in node controller

This commit is contained in:
Yisroel Baum 2026-04-18 21:33:41 +03:00
parent 571c0d1196
commit bdf386e510
Signed by: yisroelbaum
GPG key ID: 0FA60884F75520A9

View file

@ -3,8 +3,12 @@
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
{
@ -34,4 +38,41 @@ class NodeController
$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 = $request->getParsedBody();
$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');
}
}