2022-08-20 07:07:38 -04:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace BookStack\References;
|
|
|
|
|
|
|
|
use BookStack\Entities\Models\Entity;
|
2023-12-18 11:23:40 -05:00
|
|
|
use BookStack\Entities\Tools\MixedEntityListLoader;
|
2023-05-17 12:56:55 -04:00
|
|
|
use BookStack\Permissions\PermissionApplicator;
|
2023-01-24 09:55:34 -05:00
|
|
|
use Illuminate\Database\Eloquent\Builder;
|
2022-08-20 07:07:38 -04:00
|
|
|
use Illuminate\Database\Eloquent\Collection;
|
|
|
|
|
|
|
|
class ReferenceFetcher
|
|
|
|
{
|
2023-12-18 11:23:40 -05:00
|
|
|
public function __construct(
|
|
|
|
protected PermissionApplicator $permissions,
|
|
|
|
protected MixedEntityListLoader $mixedEntityListLoader,
|
|
|
|
) {
|
2022-08-20 07:07:38 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2023-12-18 11:23:40 -05:00
|
|
|
* Query and return the references pointing to the given entity.
|
2022-08-20 07:07:38 -04:00
|
|
|
* Loads the commonly required relations while taking permissions into account.
|
|
|
|
*/
|
2023-12-18 11:23:40 -05:00
|
|
|
public function getReferencesToEntity(Entity $entity): Collection
|
2022-08-20 07:07:38 -04:00
|
|
|
{
|
2023-12-18 11:23:40 -05:00
|
|
|
$references = $this->queryReferencesToEntity($entity)->get();
|
2024-02-04 09:39:01 -05:00
|
|
|
$this->mixedEntityListLoader->loadIntoRelations($references->all(), 'from', true);
|
2022-08-20 07:07:38 -04:00
|
|
|
|
|
|
|
return $references;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2023-12-18 11:23:40 -05:00
|
|
|
* Returns the count of references pointing to the given entity.
|
2022-08-20 07:07:38 -04:00
|
|
|
* Takes permissions into account.
|
|
|
|
*/
|
2023-12-18 11:23:40 -05:00
|
|
|
public function getReferenceCountToEntity(Entity $entity): int
|
2022-08-20 07:07:38 -04:00
|
|
|
{
|
2023-12-18 11:23:40 -05:00
|
|
|
return $this->queryReferencesToEntity($entity)->count();
|
2022-08-20 07:07:38 -04:00
|
|
|
}
|
2023-01-24 09:55:34 -05:00
|
|
|
|
2023-12-18 11:23:40 -05:00
|
|
|
protected function queryReferencesToEntity(Entity $entity): Builder
|
2023-01-24 09:55:34 -05:00
|
|
|
{
|
2023-12-18 11:23:40 -05:00
|
|
|
$baseQuery = Reference::query()
|
2023-01-24 09:55:34 -05:00
|
|
|
->where('to_type', '=', $entity->getMorphClass())
|
2024-04-01 12:08:53 -04:00
|
|
|
->where('to_id', '=', $entity->id)
|
|
|
|
->whereHas('from');
|
2023-12-18 11:23:40 -05:00
|
|
|
|
|
|
|
return $this->permissions->restrictEntityRelationQuery(
|
|
|
|
$baseQuery,
|
|
|
|
'references',
|
|
|
|
'from_id',
|
|
|
|
'from_type'
|
|
|
|
);
|
2023-01-24 09:55:34 -05:00
|
|
|
}
|
2022-08-29 12:46:41 -04:00
|
|
|
}
|