]> BookStack Code Mirror - bookstack/blob - app/Activity/Tools/CommentTree.php
Uploads: Explicitly disabled s3 streaming in config
[bookstack] / app / Activity / Tools / CommentTree.php
1 <?php
2
3 namespace BookStack\Activity\Tools;
4
5 use BookStack\Activity\Models\Comment;
6 use BookStack\Entities\Models\Page;
7
8 class CommentTree
9 {
10     /**
11      * The built nested tree structure array.
12      * @var array{comment: Comment, depth: int, children: array}[]
13      */
14     protected array $tree;
15     protected array $comments;
16
17     public function __construct(
18         protected Page $page
19     ) {
20         $this->comments = $this->loadComments();
21         $this->tree = $this->createTree($this->comments);
22     }
23
24     public function enabled(): bool
25     {
26         return !setting('app-disable-comments');
27     }
28
29     public function empty(): bool
30     {
31         return count($this->tree) === 0;
32     }
33
34     public function count(): int
35     {
36         return count($this->comments);
37     }
38
39     public function get(): array
40     {
41         return $this->tree;
42     }
43
44     /**
45      * @param Comment[] $comments
46      */
47     protected function createTree(array $comments): array
48     {
49         $byId = [];
50         foreach ($comments as $comment) {
51             $byId[$comment->local_id] = $comment;
52         }
53
54         $childMap = [];
55         foreach ($comments as $comment) {
56             $parent = $comment->parent_id;
57             if (is_null($parent) || !isset($byId[$parent])) {
58                 $parent = 0;
59             }
60
61             if (!isset($childMap[$parent])) {
62                 $childMap[$parent] = [];
63             }
64             $childMap[$parent][] = $comment->local_id;
65         }
66
67         $tree = [];
68         foreach ($childMap[0] ?? [] as $childId) {
69             $tree[] = $this->createTreeForId($childId, 0, $byId, $childMap);
70         }
71
72         return $tree;
73     }
74
75     protected function createTreeForId(int $id, int $depth, array &$byId, array &$childMap): array
76     {
77         $childIds = $childMap[$id] ?? [];
78         $children = [];
79
80         foreach ($childIds as $childId) {
81             $children[] = $this->createTreeForId($childId, $depth + 1, $byId, $childMap);
82         }
83
84         return [
85             'comment' => $byId[$id],
86             'depth' => $depth,
87             'children' => $children,
88         ];
89     }
90
91     protected function loadComments(): array
92     {
93         if (!$this->enabled()) {
94             return [];
95         }
96
97         return $this->page->comments()
98             ->with('createdBy')
99             ->get()
100             ->all();
101     }
102 }