-
Notifications
You must be signed in to change notification settings - Fork 17
/
NgView.php
380 lines (339 loc) · 10.7 KB
/
NgView.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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
<?php
namespace dee\angular;
use Yii;
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;
use yii\helpers\Inflector;
use yii\web\View as WebView;
use yii\base\Widget;
use yii\helpers\Url;
use yii\web\AssetBundle;
/**
* Description of NgView
*
*
* @author Misbahul D Munir <[email protected]>
* @since 1.0
*/
class NgView extends Widget
{
/**
*
* @var array
*/
public $routes = [];
/**
*
* @var array
*/
public $resources = [];
/**
*
* @var string
*/
public $name = 'dApp';
/**
* @var boolean If `true` will render attribute `ng-app="appName"` in widget.
*/
public $useNgApp = true;
/**
* @var array
*/
public $requires = [];
/**
* @var string
*/
public $tag = 'ng-view';
/**
*
* @var string
*/
public $js;
/**
*
* @var string
*/
public $controller;
/**
* @var array
*/
public $clientOptions;
/**
* @var array
*/
public $injection = ['$scope', '$injector'];
/**
* @var boolean
*/
public $remote;
/**
* @var string
*/
public $queryParam = '_ng-view';
/**
* @var array
*/
public static $requireAssets = [
'ui.bootstrap' => 'dee\angular\AngularBootstrapAsset',
'dee.ui' => 'dee\angular\DeeAngularUiAsset',
'dee.rest' => 'dee\angular\DeeAngularRestAsset',
'ngRoute' => 'dee\angular\AngularRouteAsset',
'ngResource' => 'dee\angular\AngularResourceAsset',
'ngAnimate' => 'dee\angular\AngularAnimateAsset',
'ngAria' => 'dee\angular\AngularAnimateAsset',
'ngTouch' => 'dee\angular\AngularAnimateAsset',
'validation' => 'dee\angular\AngularValidationAsset',
'validation.rule' => 'dee\angular\AngularValidationAsset',
];
private $_varName;
/**
*
* @var static
*/
public static $instance;
/**
* @inheritdoc
*/
public function init()
{
static::$instance = $this;
$this->_varName = Inflector::variablize($this->name);
$this->requires[] = 'ngRoute';
if (!empty($this->resources)) {
$this->requires[] = 'ngResource';
}
$this->requires = array_unique($this->requires);
}
/**
* @inheritdoc
*/
public function run()
{
$view = $this->getView();
if (!$this->remote || Yii::$app->getRequest()->get($this->queryParam) === 'script') {
$js = $this->generate();
if ($this->remote) {
$response = Yii::$app->getResponse();
$response->format = 'raw';
$response->getHeaders()->set('Content-Type', 'application/javascript');
$response->content = $js;
$response->send();
Yii::$app->end();
} else {
$view->registerJs($js, WebView::POS_END);
}
}
// Asset Dependency
$key = md5(Yii::$app->controller->route . $this->name);
$bundle = [
'baseUrl' => '',
'depends' => [AngularAsset::className()],
'js' => [],
];
foreach ($this->requires as $module) {
if (isset(static::$requireAssets[$module])) {
$bundle['depends'][] = static::$requireAssets[$module];
}
}
if ($this->remote) {
$key = md5(Yii::$app->controller->route . $this->name);
$url = Url::current([$this->queryParam => 'script']);
$bundle['js'][] = strncmp($url, '//', 2) === 0 ? $url : ltrim($url, '/');
}
Yii::$app->getAssetManager()->bundles[$key] = new AssetBundle($bundle);
$view->registerAssetBundle($key);
static::$instance = null;
return Html::tag($this->tag, '', ['ng-app' => $this->useNgApp ? $this->name : false, 'ng-view' => $this->tag != 'ng-view']);
}
protected function generate()
{
$view = $this->getView();
$routeProviders = [];
$controllers = [];
$templates = [];
foreach ($this->routes as $path => $route) {
$visible = ArrayHelper::remove($route, 'visible', true);
list($routeProvider, $controller, $template) = $this->applyRoute($route, $path);
if ($path === 'otherwise') {
$routeProviders[] = "\$routeProvider.otherwise({$routeProvider});";
} elseif ($visible) {
$p = Json::htmlEncode($path);
$routeProviders[] = "\$routeProvider.when({$p},{$routeProvider});";
}
if ($controller) {
$controllers[$controller[0]] = $controller[1];
}
if ($template) {
$templates[$path] = $template;
}
}
$js = [];
$js[] = "{$this->_varName} = (function(options){";
$js[] = $this->renderModule();
$js[] = $this->renderTemplates($templates);
$js[] = $this->renderRouteProviders($routeProviders);
$js[] = $this->renderControllers($controllers);
$js[] = $this->renderResources();
if ($this->js !== null) {
foreach ((array) $this->js as $file) {
$js[] = "\n" . static::parseBlockJs($view->render($file));
}
}
$options = empty($this->clientOptions) ? '{}' : Json::htmlEncode($this->clientOptions);
$js[] = "\nreturn module;\n})({$options});";
return implode("\n", $js);
}
protected function applyRoute($route, $path)
{
$view = $this->getView();
$routeProvider = $controller = $template = null;
if (is_string($route)) {
$routeProvider = Json::htmlEncode(['redirectTo' => $route]);
} elseif (isset($route['link'])) {
$link = Json::htmlEncode($route['link']);
unset($route['link'], $route['view'], $route['controller'], $route['visible']);
$route = Json::htmlEncode($route);
$routeProvider = "angular.extend({},module.templates[{$link}],{$route})";
} else {
$injection = ArrayHelper::remove($route, 'injection', []);
if (empty($route['controller'])) {
$route['controller'] = Inflector::camelize($path) . 'Ctrl';
}
$this->controller = $route['controller'];
$controller = [$this->controller, $injection];
if (isset($route['js'])) {
$this->renderJs($route['js']);
unset($route['js']);
}
if (isset($route['view'])) {
$route['template'] = $view->render($route['view'], ['widget' => $this]);
unset($route['view']);
}
$template = $route;
$path = Json::htmlEncode($path);
$routeProvider = "module.templates[{$path}]";
}
$this->controller = null;
return [$routeProvider, $controller, $template];
}
/**
* Render script create module. The result are
* ```javascript
* module = angular.module('appName',[requires,...]);
* ```
*/
protected function renderModule()
{
$js = "var module = angular.module('{$this->name}'," . Json::htmlEncode($this->requires) . ");\n"
. "var {$this->_varName} = module;";
return $js;
}
protected function renderTemplates($templates)
{
return "module.templates = " . Json::htmlEncode($templates) . ';';
}
/**
* Render script config for $routeProvider
* @param array $routeProviders
*/
protected function renderRouteProviders($routeProviders)
{
$routeProviders = implode("\n", $routeProviders);
return "module.config(['\$routeProvider',function(\$routeProvider){\n{$routeProviders}\n}]);";
}
/**
* Render script create controllers
* ```javascript
* module.controller('CtrlName',['$scope',...,
* function($scope,...){
* ...
* }]);
* ```
* @param array $controllers
*/
protected function renderControllers($controllers)
{
$js = [];
$view = $this->getView();
foreach ($controllers as $name => $injection) {
$injection = array_unique(array_merge($this->injection, (array) $injection));
$injectionStr = rtrim(Json::htmlEncode($injection), ']');
$injectionVar = implode(", ", $injection);
$function = implode("\n", ArrayHelper::getValue($view->js, $name, []));
$js[] = "module.controller('$name',{$injectionStr},\nfunction($injectionVar){\n{$function}\n}]);";
}
return implode("\n", $js);
}
/**
* Render script resource
* ```javascript
* module.factory(ResName,['$resource',function($resource){
* return ...;
* }]);
* ```
*/
protected function renderResources()
{
if (!empty($this->resources)) {
$js = [];
foreach ($this->resources as $name => $config) {
$url = Json::htmlEncode($config['url']);
if (empty($config['paramDefaults'])) {
$paramDefaults = '{}';
} else {
$paramDefaults = Json::htmlEncode($config['paramDefaults']);
}
if (empty($config['actions'])) {
$actions = '{}';
} else {
$actions = Json::htmlEncode($config['actions']);
}
$js[] = <<<JS
module.factory('$name',['\$resource',function(\$resource){
return \$resource({$url},{$paramDefaults},{$actions});
}]);
JS;
}
return implode("\n", $js);
}
return '';
}
/**
* Only get script inner of `script` tag.
* @param string $js
* @return string
*/
public static function parseBlockJs($js)
{
$jsBlockPattern = '|^<script[^>]*>(?P<block_content>.+?)</script>$|is';
if (preg_match($jsBlockPattern, trim($js), $matches)) {
$js = trim($matches['block_content']);
}
return $js;
}
/**
* Register script to controller.
*
* @param string $viewFile
* @param array $params
* @param integer|string $pos
*/
public function renderJs($viewFile, $params = [], $pos = null)
{
$params['widget'] = $this;
$js = $this->view->render($viewFile, $params);
$this->registerJs($js, $pos);
}
/**
* Register script to controller.
*
* @param string $js
* @param integer|string $pos
*/
public function registerJs($js, $pos = null)
{
$pos = $pos ? : ($this->controller ? : WebView::POS_END);
$this->view->registerJs(static::parseBlockJs($js), $pos);
}
}