designtopack/public/site/plugins/comments/routes/delete.php
2024-11-05 14:26:37 +01:00

61 lines
1.8 KiB
PHP

<?php
return [
'pattern' => '(:all)delete-comment.json',
'method' => 'POST',
'action' => function () {
$json = file_get_contents('php://input');
$data = json_decode($json);
$page = page($data->page->uri);
$file = $page->file($data->file->uuid);
$isReply = $data->parentId ?? false;
$comments = $file->comments()->isEmpty() == true ? [] : Yaml::decode($file->comments()->value());
foreach ($comments as $key => &$comment) {
if ($isReply) {
if ($comment['id'] === $data->parentId) {
foreach ($comment['replies'] as $replyKey => $reply) {
if ($reply['id'] === $data->id) {
unset($comment['replies'][$replyKey]);
$comment['replies'] = array_values($comment['replies']);
}
}
}
} else {
if ($comment['id'] === $data->id) {
unset($comments[$key]);
}
}
}
$comments = array_values($comments); // Réindexe les commentaires
foreach (kirby()->users() as $user) {
try {
$notifications = $user->notifications()->isNotEmpty()
? Yaml::decode($user->notifications()->value())
: [];
foreach ($notifications as $key => $notification) {
if ($notification['id'] === $data->id) {
unset($notifications[$key]);
}
}
$user->update([
'notifications' => $notifications
]);
} catch (\Throwable $th) {
throw new Exception("Error updating notifications: " . $th->getMessage() . ' line ' . $th->getLine(), 1);
}
}
$newFile = $file->update([
'comments' => $comments
]);
return getFileData($newFile);
}
];