3 namespace BookStack\References;
5 use BookStack\Auth\Permissions\PermissionApplicator;
6 use BookStack\Entities\Models\Entity;
7 use BookStack\Entities\Models\Page;
8 use Illuminate\Database\Eloquent\Builder;
9 use Illuminate\Database\Eloquent\Collection;
10 use Illuminate\Database\Eloquent\Relations\Relation;
12 class ReferenceFetcher
14 protected PermissionApplicator $permissions;
16 public function __construct(PermissionApplicator $permissions)
18 $this->permissions = $permissions;
22 * Query and return the page references pointing to the given entity.
23 * Loads the commonly required relations while taking permissions into account.
25 public function getPageReferencesToEntity(Entity $entity): Collection
27 $baseQuery = $this->queryPageReferencesToEntity($entity)
29 'from' => fn (Relation $query) => $query->select(Page::$listAttributes),
30 'from.book' => fn (Relation $query) => $query->scopes('visible'),
31 'from.chapter' => fn (Relation $query) => $query->scopes('visible'),
34 $references = $this->permissions->restrictEntityRelationQuery(
45 * Returns the count of page references pointing to the given entity.
46 * Takes permissions into account.
48 public function getPageReferenceCountToEntity(Entity $entity): int
50 $count = $this->permissions->restrictEntityRelationQuery(
51 $this->queryPageReferencesToEntity($entity),
60 protected function queryPageReferencesToEntity(Entity $entity): Builder
62 return Reference::query()
63 ->where('to_type', '=', $entity->getMorphClass())
64 ->where('to_id', '=', $entity->id)
65 ->where('from_type', '=', (new Page())->getMorphClass());