designtopack/public/site/config/routes/add-comment.php

47 lines
No EOL
1.4 KiB
PHP

<?php
return [
'pattern' => '(:all)add-comment.json',
'method' => 'POST',
'action' => function () {
$json = file_get_contents('php://input');
$data = json_decode($json);
// return json_encode($data->pageUri);
$page = page($data->pageUri);
$file = $page->file($data->fileName);
$user = kirby()->user($data->userUuid);
$comments = $file->comments()->isEmpty() == true ? [] : Data::decode($file->comments()->toArray()['comments'], 'yaml');
$newComment = [
'text' => $data->text,
'username' => $user->name()->isNotEmpty() ? (string) $user->name() : (string) $user->email(),
'date' => (string) $data->date,
'id' => $data->id
];
$comments[$data->targetPage][$data->id] = $newComment;
$newFile = $file->update([
'comments' => $comments
]);
foreach (kirby()->users()->without($user) as $otherUser) {
try {
$notifications = $otherUser->notifications()->isNotEmpty() ? $otherUser->notifications()->toArray() : ["comments" => []];
$notifications['comments'][$data->id] = $newComment;
$otherUser->update([
"notifications" => $notifications
]);
} catch (\Throwable $th) {
throw new Exception($th->getMessage(), 1);
}
}
return getFileData($newFile);
}
];