]> BookStack Code Mirror - bookstack/blob - app/Entities/Tools/SiblingFetcher.php
Code cleanup, bug squashing
[bookstack] / app / Entities / Tools / SiblingFetcher.php
1 <?php namespace BookStack\Entities\Tools;
2
3 use BookStack\Entities\EntityProvider;
4 use BookStack\Entities\Models\Book;
5 use BookStack\Entities\Models\Bookshelf;
6 use Illuminate\Support\Collection;
7
8 class SiblingFetcher
9 {
10
11     /**
12      * Search among the siblings of the entity of given type and id.
13      */
14     public function fetch(string $entityType, int $entityId): Collection
15     {
16         $entity = (new EntityProvider)->get($entityType)->visible()->findOrFail($entityId);
17         $entities = [];
18
19         // Page in chapter
20         if ($entity->isA('page') && $entity->chapter) {
21             $entities = $entity->chapter->getVisiblePages();
22         }
23
24         // Page in book or chapter
25         if (($entity->isA('page') && !$entity->chapter) || $entity->isA('chapter')) {
26             $entities = $entity->book->getDirectChildren();
27         }
28
29         // Book
30         // Gets just the books in a shelf if shelf is in context
31         if ($entity->isA('book')) {
32             $contextShelf = (new ShelfContext)->getContextualShelfForBook($entity);
33             if ($contextShelf) {
34                 $entities = $contextShelf->visibleBooks()->get();
35             } else {
36                 $entities = Book::visible()->get();
37             }
38         }
39
40         // Shelve
41         if ($entity->isA('bookshelf')) {
42             $entities = Bookshelf::visible()->get();
43         }
44
45         return $entities;
46     }
47 }