]> BookStack Code Mirror - bookstack/blob - app/Entities/Tools/NextPreviousContentLocator.php
Added more complexity in an attempt to make ldap host failover fit
[bookstack] / app / Entities / Tools / NextPreviousContentLocator.php
1 <?php
2
3 namespace BookStack\Entities\Tools;
4
5 use BookStack\Entities\Models\BookChild;
6 use BookStack\Entities\Models\Entity;
7 use Illuminate\Support\Collection;
8
9 /**
10  * Finds the next or previous content of a book element (page or chapter).
11  */
12 class NextPreviousContentLocator
13 {
14     protected $relativeBookItem;
15     protected $flatTree;
16     protected $currentIndex = null;
17
18     /**
19      * NextPreviousContentLocator constructor.
20      */
21     public function __construct(BookChild $relativeBookItem, Collection $bookTree)
22     {
23         $this->relativeBookItem = $relativeBookItem;
24         $this->flatTree = $this->treeToFlatOrderedCollection($bookTree);
25         $this->currentIndex = $this->getCurrentIndex();
26     }
27
28     /**
29      * Get the next logical entity within the book hierarchy.
30      */
31     public function getNext(): ?Entity
32     {
33         return $this->flatTree->get($this->currentIndex + 1);
34     }
35
36     /**
37      * Get the next logical entity within the book hierarchy.
38      */
39     public function getPrevious(): ?Entity
40     {
41         return $this->flatTree->get($this->currentIndex - 1);
42     }
43
44     /**
45      * Get the index of the current relative item.
46      */
47     protected function getCurrentIndex(): ?int
48     {
49         $index = $this->flatTree->search(function (Entity $entity) {
50             return get_class($entity) === get_class($this->relativeBookItem)
51                 && $entity->id === $this->relativeBookItem->id;
52         });
53
54         return $index === false ? null : $index;
55     }
56
57     /**
58      * Convert a book tree collection to a flattened version
59      * where all items follow the expected order of user flow.
60      */
61     protected function treeToFlatOrderedCollection(Collection $bookTree): Collection
62     {
63         $flatOrdered = collect();
64         /** @var Entity $item */
65         foreach ($bookTree->all() as $item) {
66             $flatOrdered->push($item);
67             $childPages = $item->getAttribute('visible_pages') ?? [];
68             $flatOrdered = $flatOrdered->concat($childPages);
69         }
70
71         return $flatOrdered;
72     }
73 }