3 namespace BookStack\References;
5 use BookStack\Entities\Models\Entity;
6 use BookStack\Entities\Tools\MixedEntityListLoader;
7 use BookStack\Permissions\PermissionApplicator;
8 use Illuminate\Database\Eloquent\Builder;
9 use Illuminate\Database\Eloquent\Collection;
11 class ReferenceFetcher
13 public function __construct(
14 protected PermissionApplicator $permissions,
15 protected MixedEntityListLoader $mixedEntityListLoader,
20 * Query and return the references pointing to the given entity.
21 * Loads the commonly required relations while taking permissions into account.
23 public function getReferencesToEntity(Entity $entity): Collection
25 $references = $this->queryReferencesToEntity($entity)->get();
26 $this->mixedEntityListLoader->loadIntoRelations($references->all(), 'from', true);
32 * Returns the count of references pointing to the given entity.
33 * Takes permissions into account.
35 public function getReferenceCountToEntity(Entity $entity): int
37 return $this->queryReferencesToEntity($entity)->count();
40 protected function queryReferencesToEntity(Entity $entity): Builder
42 $baseQuery = Reference::query()
43 ->where('to_type', '=', $entity->getMorphClass())
44 ->where('to_id', '=', $entity->id)
47 return $this->permissions->restrictEntityRelationQuery(