]> BookStack Code Mirror - bookstack/blob - app/References/ReferenceFetcher.php
Implemented alternate approach to current joint_permissions
[bookstack] / app / References / ReferenceFetcher.php
1 <?php
2
3 namespace BookStack\References;
4
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;
11
12 class ReferenceFetcher
13 {
14     protected PermissionApplicator $permissions;
15
16     public function __construct(PermissionApplicator $permissions)
17     {
18         $this->permissions = $permissions;
19     }
20
21     /**
22      * Query and return the page references pointing to the given entity.
23      * Loads the commonly required relations while taking permissions into account.
24      */
25     public function getPageReferencesToEntity(Entity $entity): Collection
26     {
27         $baseQuery = $this->queryPageReferencesToEntity($entity)
28             ->with([
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'),
32             ]);
33
34         $references = $this->permissions->restrictEntityRelationQuery(
35             $baseQuery,
36             'references',
37             'from_id',
38             'from_type'
39         )->get();
40
41         return $references;
42     }
43
44     /**
45      * Returns the count of page references pointing to the given entity.
46      * Takes permissions into account.
47      */
48     public function getPageReferenceCountToEntity(Entity $entity): int
49     {
50         $count = $this->permissions->restrictEntityRelationQuery(
51             $this->queryPageReferencesToEntity($entity),
52             'references',
53             'from_id',
54             'from_type'
55         )->count();
56
57         return $count;
58     }
59
60     protected function queryPageReferencesToEntity(Entity $entity): Builder
61     {
62         return Reference::query()
63             ->where('to_type', '=', $entity->getMorphClass())
64             ->where('to_id', '=', $entity->id)
65             ->where('from_type', '=', (new Page())->getMorphClass());
66     }
67 }