3 namespace BookStack\Activity\Tools;
5 use BookStack\Activity\Models\Comment;
6 use BookStack\Entities\Models\Page;
11 * The built nested tree structure array.
12 * @var CommentTreeNode[]
14 protected array $tree;
15 protected array $comments;
17 public function __construct(
20 $this->comments = $this->loadComments();
21 $this->tree = $this->createTree($this->comments);
24 public function enabled(): bool
26 return !setting('app-disable-comments');
29 public function empty(): bool
31 return count($this->tree) === 0;
34 public function count(): int
36 return count($this->comments);
39 public function getActive(): array
41 return array_filter($this->tree, fn (CommentTreeNode $node) => !$node->comment->archived);
44 public function getArchived(): array
46 return array_filter($this->tree, fn (CommentTreeNode $node) => $node->comment->archived);
49 public function getCommentNodeForId(int $commentId): ?CommentTreeNode
51 foreach ($this->tree as $node) {
52 if ($node->comment->id === $commentId) {
60 public function canUpdateAny(): bool
62 foreach ($this->comments as $comment) {
63 if (userCan('comment-update', $comment)) {
72 * @param Comment[] $comments
73 * @return CommentTreeNode[]
75 protected function createTree(array $comments): array
78 foreach ($comments as $comment) {
79 $byId[$comment->local_id] = $comment;
83 foreach ($comments as $comment) {
84 $parent = $comment->parent_id;
85 if (is_null($parent) || !isset($byId[$parent])) {
89 if (!isset($childMap[$parent])) {
90 $childMap[$parent] = [];
92 $childMap[$parent][] = $comment->local_id;
96 foreach ($childMap[0] ?? [] as $childId) {
97 $tree[] = $this->createTreeNodeForId($childId, 0, $byId, $childMap);
103 protected function createTreeNodeForId(int $id, int $depth, array &$byId, array &$childMap): CommentTreeNode
105 $childIds = $childMap[$id] ?? [];
108 foreach ($childIds as $childId) {
109 $children[] = $this->createTreeNodeForId($childId, $depth + 1, $byId, $childMap);
112 return new CommentTreeNode($byId[$id], $depth, $children);
115 protected function loadComments(): array
117 if (!$this->enabled()) {
121 return $this->page->comments()