]> BookStack Code Mirror - bookstack/blob - app/References/ReferenceFetcher.php
Opensearch: Fixed XML declaration when php short tags enabled
[bookstack] / app / References / ReferenceFetcher.php
1 <?php
2
3 namespace BookStack\References;
4
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;
10
11 class ReferenceFetcher
12 {
13     public function __construct(
14         protected PermissionApplicator $permissions,
15         protected MixedEntityListLoader $mixedEntityListLoader,
16     ) {
17     }
18
19     /**
20      * Query and return the references pointing to the given entity.
21      * Loads the commonly required relations while taking permissions into account.
22      */
23     public function getReferencesToEntity(Entity $entity): Collection
24     {
25         $references = $this->queryReferencesToEntity($entity)->get();
26         $this->mixedEntityListLoader->loadIntoRelations($references->all(), 'from', true);
27
28         return $references;
29     }
30
31     /**
32      * Returns the count of references pointing to the given entity.
33      * Takes permissions into account.
34      */
35     public function getReferenceCountToEntity(Entity $entity): int
36     {
37         return $this->queryReferencesToEntity($entity)->count();
38     }
39
40     protected function queryReferencesToEntity(Entity $entity): Builder
41     {
42         $baseQuery = Reference::query()
43             ->where('to_type', '=', $entity->getMorphClass())
44             ->where('to_id', '=', $entity->id)
45             ->whereHas('from');
46
47         return $this->permissions->restrictEntityRelationQuery(
48             $baseQuery,
49             'references',
50             'from_id',
51             'from_type'
52         );
53     }
54 }