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 array{comment: Comment, depth: int, children: array}[]
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 get(): array
44 public function canUpdateAny(): bool
46 foreach ($this->comments as $comment) {
47 if (userCan('comment-update', $comment)) {
56 * @param Comment[] $comments
58 protected function createTree(array $comments): array
61 foreach ($comments as $comment) {
62 $byId[$comment->local_id] = $comment;
66 foreach ($comments as $comment) {
67 $parent = $comment->parent_id;
68 if (is_null($parent) || !isset($byId[$parent])) {
72 if (!isset($childMap[$parent])) {
73 $childMap[$parent] = [];
75 $childMap[$parent][] = $comment->local_id;
79 foreach ($childMap[0] ?? [] as $childId) {
80 $tree[] = $this->createTreeForId($childId, 0, $byId, $childMap);
86 protected function createTreeForId(int $id, int $depth, array &$byId, array &$childMap): array
88 $childIds = $childMap[$id] ?? [];
91 foreach ($childIds as $childId) {
92 $children[] = $this->createTreeForId($childId, $depth + 1, $byId, $childMap);
96 'comment' => $byId[$id],
98 'children' => $children,
102 protected function loadComments(): array
104 if (!$this->enabled()) {
108 return $this->page->comments()