]> BookStack Code Mirror - bookstack/blob - app/Entities/Tools/SiblingFetcher.php
Opensearch: Fixed XML declaration when php short tags enabled
[bookstack] / app / Entities / Tools / SiblingFetcher.php
1 <?php
2
3 namespace BookStack\Entities\Tools;
4
5 use BookStack\Entities\EntityProvider;
6 use BookStack\Entities\Models\Book;
7 use BookStack\Entities\Models\Bookshelf;
8 use BookStack\Entities\Models\Chapter;
9 use BookStack\Entities\Models\Page;
10 use BookStack\Entities\Queries\EntityQueries;
11 use Illuminate\Support\Collection;
12
13 class SiblingFetcher
14 {
15     public function __construct(
16         protected EntityQueries $queries,
17         protected ShelfContext $shelfContext,
18     ) {
19     }
20
21     /**
22      * Search among the siblings of the entity of given type and id.
23      */
24     public function fetch(string $entityType, int $entityId): Collection
25     {
26         $entity = (new EntityProvider())->get($entityType)->visible()->findOrFail($entityId);
27         $entities = [];
28
29         // Page in chapter
30         if ($entity instanceof Page && $entity->chapter) {
31             $entities = $entity->chapter->getVisiblePages();
32         }
33
34         // Page in book or chapter
35         if (($entity instanceof Page && !$entity->chapter) || $entity instanceof Chapter) {
36             $entities = $entity->book->getDirectVisibleChildren();
37         }
38
39         // Book
40         // Gets just the books in a shelf if shelf is in context
41         if ($entity instanceof Book) {
42             $contextShelf = $this->shelfContext->getContextualShelfForBook($entity);
43             if ($contextShelf) {
44                 $entities = $contextShelf->visibleBooks()->get();
45             } else {
46                 $entities = $this->queries->books->visibleForList()->orderBy('name', 'asc')->get();
47             }
48         }
49
50         // Shelf
51         if ($entity instanceof Bookshelf) {
52             $entities = $this->queries->shelves->visibleForList()->orderBy('name', 'asc')->get();
53         }
54
55         return $entities;
56     }
57 }