3 namespace BookStack\Entities\Tools;
5 use BookStack\Entities\Models\BookChild;
6 use BookStack\Entities\Models\Entity;
7 use Illuminate\Support\Collection;
10 * Finds the next or previous content of a book element (page or chapter).
12 class NextPreviousContentLocator
14 protected $relativeBookItem;
16 protected $currentIndex = null;
19 * NextPreviousContentLocator constructor.
21 public function __construct(BookChild $relativeBookItem, Collection $bookTree)
23 $this->relativeBookItem = $relativeBookItem;
24 $this->flatTree = $this->treeToFlatOrderedCollection($bookTree);
25 $this->currentIndex = $this->getCurrentIndex();
29 * Get the next logical entity within the book hierarchy.
31 public function getNext(): ?Entity
33 return $this->flatTree->get($this->currentIndex + 1);
37 * Get the next logical entity within the book hierarchy.
39 public function getPrevious(): ?Entity
41 return $this->flatTree->get($this->currentIndex - 1);
45 * Get the index of the current relative item.
47 protected function getCurrentIndex(): ?int
49 $index = $this->flatTree->search(function (Entity $entity) {
50 return get_class($entity) === get_class($this->relativeBookItem)
51 && $entity->id === $this->relativeBookItem->id;
54 return $index === false ? null : $index;
58 * Convert a book tree collection to a flattened version
59 * where all items follow the expected order of user flow.
61 protected function treeToFlatOrderedCollection(Collection $bookTree): Collection
63 $flatOrdered = collect();
64 /** @var Entity $item */
65 foreach ($bookTree->all() as $item) {
66 $flatOrdered->push($item);
67 $childPages = $item->visible_pages ?? [];
68 $flatOrdered = $flatOrdered->concat($childPages);