3 namespace BookStack\Entities\Tools;
5 use BookStack\Entities\Models\Book;
6 use BookStack\Entities\Models\BookChild;
7 use BookStack\Entities\Models\Chapter;
8 use BookStack\Entities\Models\Entity;
9 use BookStack\Entities\Models\Page;
10 use BookStack\Entities\Queries\EntityQueries;
11 use BookStack\Sorting\BookSortMap;
12 use BookStack\Sorting\BookSortMapItem;
13 use Illuminate\Support\Collection;
17 protected EntityQueries $queries;
19 public function __construct(
22 $this->queries = app()->make(EntityQueries::class);
26 * Get the current priority of the last item at the top-level of the book.
28 public function getLastPriority(): int
30 $maxPage = $this->book->pages()
31 ->where('draft', '=', false)
32 ->where('chapter_id', '=', 0)
35 $maxChapter = $this->book->chapters()
38 return max($maxChapter, $maxPage, 1);
42 * Get the contents as a sorted collection tree.
44 public function getTree(bool $showDrafts = false, bool $renderPages = false): Collection
46 $pages = $this->getPages($showDrafts, $renderPages);
47 $chapters = $this->book->chapters()->scopes('visible')->get();
48 $all = collect()->concat($pages)->concat($chapters);
49 $chapterMap = $chapters->keyBy('id');
50 $lonePages = collect();
52 $pages->groupBy('chapter_id')->each(function ($pages, $chapter_id) use ($chapterMap, &$lonePages) {
53 $chapter = $chapterMap->get($chapter_id);
55 $chapter->setAttribute('visible_pages', collect($pages)->sortBy($this->bookChildSortFunc()));
57 $lonePages = $lonePages->concat($pages);
61 $chapters->whereNull('visible_pages')->each(function (Chapter $chapter) {
62 $chapter->setAttribute('visible_pages', collect([]));
65 $all->each(function (Entity $entity) use ($renderPages) {
66 $entity->setRelation('book', $this->book);
68 if ($renderPages && $entity instanceof Page) {
69 $entity->html = (new PageContent($entity))->render();
73 return collect($chapters)->concat($lonePages)->sortBy($this->bookChildSortFunc());
77 * Function for providing a sorting score for an entity in relation to the
78 * other items within the book.
80 protected function bookChildSortFunc(): callable
82 return function (Entity $entity) {
83 if (isset($entity['draft']) && $entity['draft']) {
87 return $entity['priority'] ?? 0;
92 * Get the visible pages within this book.
94 protected function getPages(bool $showDrafts = false, bool $getPageContent = false): Collection
96 if ($getPageContent) {
97 $query = $this->queries->pages->visibleWithContents();
99 $query = $this->queries->pages->visibleForList();
103 $query->where('draft', '=', false);
106 return $query->where('book_id', '=', $this->book->id)->get();