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