-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
ScopeVisibilityTrait.php
54 lines (44 loc) · 1.46 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
<?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;
trait ScopeVisibilityTrait
{
protected static $visibilityScopers = [];
public static function registerVisibilityScoper($scoper, $ability = null)
{
$model = static::class;
if ($ability === null) {
$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.
*
* @param Builder $query
* @param User $actor
*/
public function scopeWhereVisibleTo(Builder $query, User $actor, string $ability = 'view')
{
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;
}
}