designtopack/public/site/plugins/comments/routes/create.php
2024-11-28 14:44:52 +01:00

63 lines
No EOL
1.6 KiB
PHP

<?php
use adrienpayet\comments\Comment;
return [
'pattern' => '(:all)create-comment.json',
'method' => 'POST',
'action' => function () {
$json = file_get_contents('php://input');
$data = json_decode($json);
$parsedUrl = parse_url($data->path);
$query = $parsedUrl['query'] ?? null;
parse_str($query, $queryParams);
$stepSlug = $queryParams['dialog'] ?? null;
$targetPageUri = $stepSlug ? $parsedUrl['path'] . '/' . $stepSlug : $parsedUrl['path'];
$page = page($targetPageUri);
$file = $page->file($data->fileName);
$user = kirby()->user($data->userUuid);
$comments = $file->comments()->isEmpty() == true ? [] : Yaml::decode($file->comments()->value());
$data = [
'href' => $data->path,
'page' => $page,
'file' => $file,
'position' => [
'pageIndex' => $data->position->pageIndex,
'x' => $data->position->x,
'y' => $data->position->y
],
'replies' => [],
'text' => $data->text,
'author' => $user,
'date' => (string) $data->date,
'id' => $data->id,
'type' => 'comment'
];
$newComment = new Comment($data);
$comments[] = $newComment->toArray();
$newFile = $file->update([
'comments' => $comments
]);
echo json_encode(getFileData($newFile));
try {
$user->sendNotification($page->parent(), $newComment->toArray());
} catch (\Throwable $th) {
echo json_encode([
"error" => $th->getMessage() . " in " . $th->getFile() . " line " . $th->getLine(),
]);
}
exit;
}
];