BookStack/app/Entities/Tools/SiblingFetcher.php

51 lines
1.5 KiB
PHP
Raw Normal View History

2021-06-26 11:23:15 -04:00
<?php
namespace BookStack\Entities\Tools;
use BookStack\Entities\EntityProvider;
use BookStack\Entities\Models\Book;
use BookStack\Entities\Models\Bookshelf;
use BookStack\Entities\Models\Chapter;
2021-11-05 20:32:01 -04:00
use BookStack\Entities\Models\Page;
use Illuminate\Support\Collection;
class SiblingFetcher
{
/**
* Search among the siblings of the entity of given type and id.
*/
public function fetch(string $entityType, int $entityId): Collection
{
2021-06-26 11:23:15 -04:00
$entity = (new EntityProvider())->get($entityType)->visible()->findOrFail($entityId);
$entities = [];
// Page in chapter
2021-11-05 20:32:01 -04:00
if ($entity instanceof Page && $entity->chapter) {
$entities = $entity->chapter->getVisiblePages();
}
// Page in book or chapter
if (($entity instanceof Page && !$entity->chapter) || $entity instanceof Chapter) {
$entities = $entity->book->getDirectChildren();
}
// Book
// Gets just the books in a shelf if shelf is in context
2021-11-05 20:32:01 -04:00
if ($entity instanceof Book) {
2021-06-26 11:23:15 -04:00
$contextShelf = (new ShelfContext())->getContextualShelfForBook($entity);
if ($contextShelf) {
$entities = $contextShelf->visibleBooks()->get();
} else {
$entities = Book::visible()->get();
}
}
2021-11-05 20:32:01 -04:00
// Shelf
if ($entity instanceof Bookshelf) {
$entities = Bookshelf::visible()->get();
}
return $entities;
}
}