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\Collection;
9 use Illuminate\Database\Eloquent\Relations\Relation;
11 class ReferenceFetcher
13 protected PermissionApplicator $permissions;
15 public function __construct(PermissionApplicator $permissions)
17 $this->permissions = $permissions;
21 * Query and return the page references pointing to the given entity.
22 * Loads the commonly required relations while taking permissions into account.
24 public function getPageReferencesToEntity(Entity $entity): Collection
26 $baseQuery = $entity->referencesTo()
27 ->where('from_type', '=', (new Page())->getMorphClass())
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 $baseQuery = $entity->referencesTo()
51 ->where('from_type', '=', (new Page())->getMorphClass());
53 $count = $this->permissions->restrictEntityRelationQuery(