-
Notifications
You must be signed in to change notification settings - Fork 1
/
DefinitionManager.php
104 lines (85 loc) · 2.51 KB
/
DefinitionManager.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
<?php
namespace artkost\rbac;
use artkost\rbac\models\RbacDefinition;
use Yii;
use yii\base\Component;
use yii\base\InvalidConfigException;
use yii\caching\TagDependency;
/**
* This class finds rules definitions in other modules
* and instantiates it
* @package app\modules\rbac
*/
class DefinitionManager extends Component
{
const DEFINITION_FILE = 'rules.php';
const CACHE_KEY = 'rbacModuleDefinition';
const CACHE_TAG = 'rbacModuleDefinition';
public $cacheDuration = 604800;
/**
* @var RbacDefinition[]
*/
protected $definitions = [];
public function init()
{
parent::init();
$this->createDefinitions();
}
protected function createDefinitions()
{
foreach (Yii::$app->getModules() as $id => $config) {
$this->createDefinition($id, $this->getDefinitionConfig($id, $config));
}
}
/**
* @return models\RbacDefinition[]
*/
public function getDefinitions()
{
return $this->definitions;
}
public function getDefinitionConfig($id, $config = [])
{
$module = Yii::$app->getModule($id);
return $module->getBasePath() . DIRECTORY_SEPARATOR . self::DEFINITION_FILE;
}
/**
* @param $id
* @param $path
* @return RbacDefinition|bool
*/
protected function createDefinition($id, $path)
{
if (!isset($this->definitions[$id])) {
$rules = [];
$cached = $this->getCache()->get(self::CACHE_KEY . ':' . $path);
$dependency = Yii::createObject(TagDependency::className(), ['tags' => [self::CACHE_TAG]]);
if ($cached) {
$rules = $cached;
} else {
if (is_array($path)) {
$rules = $path;
} elseif (file_exists($path)) {
$rules = include $path;
}
}
if (is_array($rules) && !empty($rules)) {
$rules['module'] = $id;
$this->getCache()->set(self::CACHE_KEY . ':' . $path, $rules, $this->cacheDuration, $dependency);
$this->definitions[$id] = new RbacDefinition($rules);
}
}
return isset($this->definitions[$id]) ? $this->definitions[$id] : false;
}
public function refreshDefinitions()
{
TagDependency::invalidate($this->getCache(), [self::CACHE_TAG]);
}
/**
* @return \yii\caching\Cache
*/
protected function getCache()
{
return Yii::$app->cache;
}
}