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