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
45 * @param Comment[] $comments
47 protected function createTree(array $comments): array
50 foreach ($comments as $comment) {
51 $byId[$comment->local_id] = $comment;
55 foreach ($comments as $comment) {
56 $parent = $comment->parent_id;
57 if (is_null($parent) || !isset($byId[$parent])) {
61 if (!isset($childMap[$parent])) {
62 $childMap[$parent] = [];
64 $childMap[$parent][] = $comment->local_id;
68 foreach ($childMap[0] as $childId) {
69 $tree[] = $this->createTreeForId($childId, 0, $byId, $childMap);
75 protected function createTreeForId(int $id, int $depth, array &$byId, array &$childMap): array
77 $childIds = $childMap[$id] ?? [];
80 foreach ($childIds as $childId) {
81 $children[] = $this->createTreeForId($childId, $depth + 1, $byId, $childMap);
85 'comment' => $byId[$id],
87 'children' => $children,
91 protected function loadComments(): array
93 if (!$this->enabled()) {
97 return $this->page->comments()