-
Notifications
You must be signed in to change notification settings - Fork 18
/
Module.php
120 lines (103 loc) · 2.87 KB
/
Module.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
<?php
/**
* Module.php
* @author Revin Roman
* @link https://rmrevin.ru
*/
namespace rmrevin\yii\module\Comments;
use rmrevin\yii\module\Comments;
use yii\helpers\ArrayHelper;
/**
* Class Module
* @package rmrevin\yii\module\Comments
*/
class Module extends \yii\base\Module
{
/** @var string module name */
public static $moduleName = 'comments';
/** @var string|null */
public $userIdentityClass = null;
/** @var bool */
public $useRbac = true;
/**
* Array that will store the models used in the package
* e.g. :
* [
* 'Comment' => 'frontend/models/comments/CommentModel'
* ]
*
* The classes defined here will be merged with getDefaultModels()
* having he manually defined by the user preference.
*
* @var array
*/
public $modelMap = [];
public function init()
{
parent::init();
if ($this->userIdentityClass === null) {
$this->userIdentityClass = \Yii::$app->getUser()->identityClass;
}
// Merge the default model classes
// with the user defined ones.
$this->defineModelClasses();
}
/**
* @return static
*/
public static function instance()
{
return \Yii::$app->getModule(static::$moduleName);
}
/**
* Merges the default and user defined model classes
* Also let's the developer to set new ones with the
* parameter being those the ones with most preference.
*
* @param array $modelClasses
*/
public function defineModelClasses($modelClasses = [])
{
$this->modelMap = ArrayHelper::merge(
$this->getDefaultModels(),
$this->modelMap,
$modelClasses
);
}
/**
* Get default model classes
*/
protected function getDefaultModels()
{
return [
'Comment' => Comments\models\Comment::className(),
'CommentQuery' => Comments\models\queries\CommentQuery::className(),
'CommentCreateForm' => Comments\forms\CommentCreateForm::className(),
];
}
/**
* Get defined className of model
*
* Returns an string or array compatible
* with the Yii::createObject method.
*
* @param string $name
* @param array $config // You should never send an array with a key defined as "class" since this will
* // overwrite the main className defined by the system.
* @return string|array
*/
public function model($name, $config = [])
{
$modelData = $this->modelMap[ucfirst($name)];
if (!empty($config)) {
if (is_string($modelData)) {
$modelData = ['class' => $modelData];
}
$modelData = ArrayHelper::merge(
$modelData,
$config
);
}
return $modelData;
}
}