BookStack\Repos\BookRepo::getChildren PHP Method

getChildren() public method

Returns a sorted collection of Pages and Chapters. Loads the book slug onto child elements to prevent access database access for getting the slug.
public getChildren ( Book $book, boolean $filterDrafts = false ) : mixed
$book BookStack\Book
$filterDrafts boolean
return mixed
    public function getChildren(Book $book, $filterDrafts = false)
    {
        $pageQuery = $book->pages()->where('chapter_id', '=', 0);
        $pageQuery = $this->permissionService->enforcePageRestrictions($pageQuery, 'view');
        if ($filterDrafts) {
            $pageQuery = $pageQuery->where('draft', '=', false);
        }
        $pages = $pageQuery->get();
        $chapterQuery = $book->chapters()->with(['pages' => function ($query) use($filterDrafts) {
            $this->permissionService->enforcePageRestrictions($query, 'view');
            if ($filterDrafts) {
                $query->where('draft', '=', false);
            }
        }]);
        $chapterQuery = $this->permissionService->enforceChapterRestrictions($chapterQuery, 'view');
        $chapters = $chapterQuery->get();
        $children = $pages->values();
        foreach ($chapters as $chapter) {
            $children->push($chapter);
        }
        $bookSlug = $book->slug;
        $children->each(function ($child) use($bookSlug) {
            $child->setAttribute('bookSlug', $bookSlug);
            if ($child->isA('chapter')) {
                $child->pages->each(function ($page) use($bookSlug) {
                    $page->setAttribute('bookSlug', $bookSlug);
                });
                $child->pages = $child->pages->sortBy(function ($child, $key) {
                    $score = $child->priority;
                    if ($child->draft) {
                        $score -= 100;
                    }
                    return $score;
                });
            }
        });
        // Sort items with drafts first then by priority.
        return $children->sortBy(function ($child, $key) {
            $score = $child->priority;
            if ($child->isA('page') && $child->draft) {
                $score -= 100;
            }
            return $score;
        });
    }