BookStack/app/Actions/CommentRepo.php

99 lines
2.3 KiB
PHP
Raw Normal View History

2021-06-26 23:23:15 +08:00
<?php
namespace BookStack\Actions;
use BookStack\Entities\Models\Entity;
2020-11-08 07:15:13 +08:00
use BookStack\Facades\Activity as ActivityService;
2021-06-26 23:23:15 +08:00
use League\CommonMark\CommonMarkConverter;
/**
2021-06-26 23:23:15 +08:00
* Class CommentRepo.
*/
class CommentRepo
{
/**
2021-06-26 23:23:15 +08:00
* @var Comment
*/
protected $comment;
public function __construct(Comment $comment)
{
$this->comment = $comment;
}
/**
* Get a comment by ID.
*/
public function getById(int $id): Comment
{
return $this->comment->newQuery()->findOrFail($id);
}
/**
* Create a new comment on an entity.
*/
public function create(Entity $entity, string $text, ?int $parent_id): Comment
{
$userId = user()->id;
$comment = $this->comment->newInstance();
$comment->text = $text;
$comment->html = $this->commentToHtml($text);
$comment->created_by = $userId;
$comment->updated_by = $userId;
$comment->local_id = $this->getNextLocalId($entity);
$comment->parent_id = $parent_id;
$entity->comments()->save($comment);
2020-11-08 07:15:13 +08:00
ActivityService::addForEntity($entity, ActivityType::COMMENTED_ON);
2021-06-26 23:23:15 +08:00
return $comment;
}
/**
* Update an existing comment.
*/
public function update(Comment $comment, string $text): Comment
{
$comment->updated_by = user()->id;
$comment->text = $text;
$comment->html = $this->commentToHtml($text);
$comment->save();
2021-06-26 23:23:15 +08:00
return $comment;
}
/**
* Delete a comment from the system.
*/
public function delete(Comment $comment): void
{
$comment->delete();
}
/**
* Convert the given comment Markdown to HTML.
*/
public function commentToHtml(string $commentText): string
{
$converter = new CommonMarkConverter([
2021-06-26 23:23:15 +08:00
'html_input' => 'strip',
'max_nesting_level' => 10,
'allow_unsafe_links' => false,
]);
return $converter->convertToHtml($commentText);
}
/**
* Get the next local ID relative to the linked entity.
*/
protected function getNextLocalId(Entity $entity): int
{
2021-11-06 08:32:01 +08:00
/** @var Comment $comment */
$comment = $entity->comments(false)->orderBy('local_id', 'desc')->first();
2021-06-26 23:23:15 +08:00
2021-11-06 08:32:01 +08:00
return ($comment->local_id ?? 0) + 1;
}
}