-
Notifications
You must be signed in to change notification settings - Fork 0
/
View.php
116 lines (102 loc) · 2.55 KB
/
View.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
<?php
namespace h8every1\requirejsview;
use yii\base\InvalidConfigException;
/**
* Class View
*
* Adds ability to register RequireJS modules inside view files
*
* @package h8every1\requirejsview
*
* @property string|array $mainJsUrl URL of main.js file with list of all modules available for require.js
*/
class View extends \yii\web\View
{
public $mainJsUrl;
private $requireJSModules = [];
public function init()
{
parent::init();
if (!$this->mainJsUrl) {
throw new InvalidConfigException('You must provide path to main.js file with list of all RequireJS modules');
}
}
/**
* Get all registered RequireJS Modules
*
* @return array
*/
public function getModules()
{
return $this->requireJSModules;
}
/**
*
* Get string with list of modules for inserting inside <script> tag
*
* @return string
*/
public function getModulesList()
{
return implode(',', $this->getModules());
}
/**
* Register single RequireJS module into view
*
* @param $moduleName
*
* @internal param array $requireJSModules
*/
public function addModule($moduleName)
{
if ( ! array_key_exists($moduleName, $this->getModules())) {
$this->requireJSModules[$moduleName] = $moduleName;
}
}
/**
* Register list of modules in view
*
* @param array $modules
*/
public function addModules($modules = [])
{
foreach ($modules as $module) {
$this->addModule($module);
}
}
/**
* Remove module form registered modules list
*
* @param $moduleName
*/
public function removeModule($moduleName)
{
if (array_key_exists($moduleName, $this->getModules())) {
unset($this->requireJSModules[$moduleName]);
}
}
/**
* Remove list of modules from registered modules list
*
* @param array $modules
*/
public function removeModules($modules = [])
{
foreach ($modules as $module) {
$this->removeModule($module);
}
}
/**
* @inheritdoc
*/
public function endBody()
{
$assetBundle = $this->registerAssetBundle('h8every1\requirejsview\RequireJSAsset');
$assetBundle->jsOptions = [
'data-main' => \yii\helpers\Url::to($this->mainJsUrl, true),
'data-modules' => $this->getModulesList(),
'position' => self::POS_END,
];
parent::endBody();
}
}