-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Policy.php
71 lines (58 loc) · 2.23 KB
/
Policy.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?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\Extend;
use Flarum\Extension\Extension;
use Flarum\User\Access\AbstractPolicy;
use Illuminate\Contracts\Container\Container;
class Policy implements ExtenderInterface
{
private $globalPolicies = [];
private $modelPolicies = [];
/**
* Add a custom policy for when an ability check is ran without a model instance.
*
* @param string $policy: ::class attribute of policy class, which must extend Flarum\User\Access\AbstractPolicy
* @return self
*/
public function globalPolicy(string $policy): self
{
$this->globalPolicies[] = $policy;
return $this;
}
/**
* Add a custom policy for when an ability check is ran on an instance of a model.
*
* @param string $modelClass: The ::class attribute of the model you are applying policies to.
* This model should extend from \Flarum\Database\AbstractModel.
* @param string $policy: ::class attribute of policy class, which must extend Flarum\User\Access\AbstractPolicy
* @return self
*/
public function modelPolicy(string $modelClass, string $policy): self
{
if (! array_key_exists($modelClass, $this->modelPolicies)) {
$this->modelPolicies[$modelClass] = [];
}
$this->modelPolicies[$modelClass][] = $policy;
return $this;
}
public function extend(Container $container, Extension $extension = null)
{
$container->extend('flarum.policies', function ($existingPolicies) {
foreach ($this->modelPolicies as $modelClass => $addPolicies) {
if (! array_key_exists($modelClass, $existingPolicies)) {
$existingPolicies[$modelClass] = [];
}
foreach ($addPolicies as $policy) {
$existingPolicies[$modelClass][] = $policy;
}
}
$existingPolicies[AbstractPolicy::GLOBAL] = array_merge($existingPolicies[AbstractPolicy::GLOBAL], $this->globalPolicies);
return $existingPolicies;
});
}
}