-
-
Notifications
You must be signed in to change notification settings - Fork 829
/
ScopeVisibilityTrait.php
57 lines (47 loc) · 1.6 KB
/
ScopeVisibilityTrait.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?php
/*
* This file is part of Flarum.
*
* For detailed copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/
namespace Flarum\Database;
use Flarum\User\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Arr;
/**
* @method static Builder whereVisibleTo(User $user)
*/
trait ScopeVisibilityTrait
{
/**
* @todo: define clear scoper interfaces.
*
* @var array<string, array<string, callable(User, Builder, ?string): void>>
*/
protected static array $visibilityScopers = [];
public static function registerVisibilityScoper(callable $scoper, ?string $ability = null): void
{
$model = static::class;
$ability ??= '*';
if (! Arr::has(static::$visibilityScopers, "$model.$ability")) {
Arr::set(static::$visibilityScopers, "$model.$ability", []);
}
static::$visibilityScopers[$model][$ability][] = $scoper;
}
/**
* Scope a query to only include records that are visible to a user.
*/
public function scopeWhereVisibleTo(Builder $query, User $actor, string $ability = 'view'): Builder
{
foreach (array_reverse(array_merge([static::class], class_parents($this))) as $class) {
foreach (Arr::get(static::$visibilityScopers, "$class.*", []) as $listener) {
$listener($actor, $query, $ability);
}
foreach (Arr::get(static::$visibilityScopers, "$class.$ability", []) as $listener) {
$listener($actor, $query);
}
}
return $query;
}
}