mirror of
https://github.com/AnimeThemes/animethemes-server.git
synced 2026-07-25 08:14:29 +02:00
48 lines
1.3 KiB
PHP
48 lines
1.3 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Scopes;
|
|
|
|
use App\Enums\Auth\Role as RoleEnum;
|
|
use App\Models\Auth\Role;
|
|
use App\Models\Document\Page;
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Scope;
|
|
use Illuminate\Support\Facades\Auth;
|
|
|
|
class ReadablePagesScope implements Scope
|
|
{
|
|
/**
|
|
* Apply the scope to a given Eloquent query builder.
|
|
*/
|
|
public function apply(Builder $builder, Model $model): void
|
|
{
|
|
if (! Auth::check()) {
|
|
$builder->whereDoesntHave(Page::RELATION_VIEWER_ROLES);
|
|
|
|
return;
|
|
}
|
|
|
|
// Bypass for admins.
|
|
if (Auth::user()->hasRole(RoleEnum::ADMIN->value)) {
|
|
return;
|
|
}
|
|
|
|
$builder->where(function (Builder $query): void {
|
|
$query
|
|
// Public pages.
|
|
->whereDoesntHave(Page::RELATION_VIEWER_ROLES)
|
|
// Pages the user can view via their roles.
|
|
->orWhereHas(
|
|
Page::RELATION_VIEWER_ROLES,
|
|
fn (Builder $relationQuery) => $relationQuery->whereIn(
|
|
Role::TABLE.'.'.Role::ATTRIBUTE_ID,
|
|
Auth::user()->roles()->select(Role::ATTRIBUTE_ID)
|
|
)
|
|
);
|
|
});
|
|
}
|
|
}
|