Passed
Push — v5 ( e348bf...8a8f01 )
by Alexey
06:35
created

View   F

Complexity

Total Complexity 165

Size/Duplication

Total Lines 632
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 632
rs 1.4778
c 0
b 0
f 0
wmc 165

24 Methods

Rating   Name   Duplication   Size   Complexity  
C genScriptArray() 0 52 16
C getMetaTags() 0 22 8
C widget() 0 31 12
B getWidgetPaths() 0 24 3
A getCss() 0 12 4
A page() 0 11 3
B resolveTemplate() 0 17 5
C head() 0 26 11
C paramsParse() 0 22 9
A init() 0 5 2
A setTitle() 0 9 4
C bodyEnd() 0 60 12
C parentContent() 0 25 7
A getScripts() 0 12 4
A content() 0 12 3
D parseSource() 0 37 9
C checkNeedLibs() 0 21 12
C ResolveCssHref() 0 39 13
C parseCss() 0 58 11
A customAsset() 0 6 4
B getHref() 0 10 7
A cutTag() 0 4 1
A parseRaw() 0 7 2
A addMetaTag() 0 5 3

How to fix   Complexity   

Complex Class

Complex classes like View often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use View, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 * View module
5
 *
6
 * Rendering pages, contents and widgets
7
 *
8
 * @author Alexey Krupskiy <[email protected]>
9
 * @link http://inji.ru/
10
 * @copyright 2015 Alexey Krupskiy
11
 * @license https://github.com/injitools/cms-Inji/blob/master/LICENSE
12
 */
13
class View extends \Module {
14
15
    public $title = 'No title';
16
17
    /**
18
     * @var View\Template
19
     */
20
    public $template = null;
21
    public $libAssets = ['css' => [], 'js' => []];
22
    public $dynAssets = ['css' => [], 'js' => []];
23
    public $dynMetas = [];
24
    public $viewedContent = '';
25
    public $contentData = [];
26
    public $templatesPath = '';
27
    public $loadedCss = [];
28
    public $loadedJs = [];
29
30
    public function init() {
31
        if (!empty($this->app->config['site']['name'])) {
32
            $this->title = $this->app->config['site']['name'];
33
        }
34
        $this->resolveTemplate();
35
    }
36
37
    public function resolveTemplate() {
38
        $templateName = 'default';
39
        if (!empty($this->config[$this->app->type]['current'])) {
40
            $templateName = $this->config[$this->app->type]['current'];
41
            if (!empty($this->config[$this->app->type]['installed'][$templateName]['location'])) {
42
                $this->templatesPath = App::$primary->path . "/templates";
43
            }
44
        }
45
        if (!$this->templatesPath) {
46
            $this->templatesPath = $this->app->path . "/templates";
47
        }
48
        $this->template = \View\Template::get($templateName, $this->app, $this->templatesPath);
49
        if (!$this->template) {
50
            $this->template = new \View\Template([
51
                'name' => 'default',
52
                'path' => $this->templatesPath . '/default',
53
                'app' => $this->app
54
            ]);
55
        }
56
    }
57
58
    public function page($params = []) {
59
        $this->paramsParse($params);
60
        App::$cur->log->template_parsed = true;
61
        if (file_exists($this->template->pagePath)) {
62
            $source = file_get_contents($this->template->pagePath);
63
            if (strpos($source, 'BODYEND') === false) {
64
                $source = str_replace('</body>', '{BODYEND}</body>', $source);
65
            }
66
            $this->parseSource($source);
67
        } else {
68
            $this->content();
69
        }
70
    }
71
72
    public function paramsParse($params) {
73
        // set template
74
        if (!empty($params['template']) && $params['template'] != 'current') {
75
            $this->template = \View\Template::get($params['template']);
76
        }
77
        //set page
78
        if (!empty($params['page']) && $params['page'] != 'current') {
79
            $this->template->setPage($params['page']);
80
        }
81
        //set module
82
        if (!empty($params['module'])) {
83
            $this->template->setModule($params['module']);
84
        }
85
        //set content
86
        if (!empty($params['content'])) {
87
            $this->template->setContent($params['content']);
88
        } elseif (!$this->template->contentPath) {
89
            $this->template->setContent();
90
        }
91
        //set data
92
        if (!empty($params['data'])) {
93
            $this->contentData = array_merge($this->contentData, $params['data']);
94
        }
95
    }
96
97
    public function content($params = []) {
98
99
        $this->paramsParse($params);
100
101
        if (empty($this->template->config['noSysMsgAutoShow'])) {
102
            Msg::show();
0 ignored issues
show
Bug introduced by
The type Msg was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
103
        }
104
        if (!file_exists($this->template->contentPath)) {
105
            echo 'Content not found';
106
        } else {
107
            extract($this->contentData);
108
            include $this->template->contentPath;
109
        }
110
    }
111
112
    public function parentContent($contentName = '') {
113
        if (!$contentName) {
114
            $contentName = $this->template->content;
115
        }
116
117
        $paths = $this->template->getContentPaths($contentName);
118
119
        $data = [];
120
        $exist = false;
121
        foreach ($paths as $type => $path) {
0 ignored issues
show
Bug introduced by
The expression $paths of type string is not traversable.
Loading history...
122
            if (substr($path, 0, strrpos($path, '/')) == substr($this->template->contentPath, 0, strrpos($this->template->contentPath, '/'))) {
123
                $exist = true;
124
                continue;
125
            }
126
            if (file_exists($path) && $exist) {
127
                $data['contentPath'] = $path;
128
                $data['content'] = $contentName;
129
                break;
130
            }
131
        }
132
        if (!$data) {
133
            echo 'Content not found';
134
        } else {
135
            extract($this->contentData);
136
            include $data['contentPath'];
137
        }
138
    }
139
140
    private function parseRaw($source) {
141
        if (!$source) {
142
            return [];
143
        }
144
145
        preg_match_all("|{([^}]+)}|", $source, $result);
146
        return $result[1];
147
    }
148
149
    public function parseSource($source) {
150
        $tags = $this->parseRaw($source);
151
        foreach ($tags as $rawTag) {
152
            $tag = explode(':', $rawTag);
153
            switch ($tag[0]) {
154
                case 'CONTENT':
155
                    $source = $this->cutTag($source, $rawTag);
156
                    $this->content();
157
                    break;
158
                case 'TITLE':
159
                    $source = $this->cutTag($source, $rawTag);
160
                    echo $this->title;
161
                    break;
162
                case 'WIDGET':
163
                    $source = $this->cutTag($source, $rawTag);
164
                    $params = array_slice($tag, 2);
165
                    $this->widget($tag[1], ['params' => $params], ':' . implode(':', $params));
166
                    break;
167
                case 'HEAD':
168
                    $source = $this->cutTag($source, $rawTag);
169
                    $this->head();
170
                    break;
171
                case 'PAGE':
172
                    $source = $this->cutTag($source, $rawTag);
173
                    $this->page(['page' => $tag[1]]);
174
                    break;
175
                case 'BODYEND':
176
                    $source = $this->cutTag($source, $rawTag);
177
                    $this->bodyEnd();
178
                    break;
179
                case 'TEMPLATE_PATH':
180
                    $source = $this->cutTag($source, $rawTag);
181
                    echo "/static/templates/{$this->template->name}";
182
                    break;
183
            }
184
        }
185
        echo $source;
186
    }
187
188
    public function cutTag($source, $rawTag) {
189
        $pos = strpos($source, $rawTag) - 1;
190
        echo substr($source, 0, $pos);
191
        return substr($source, ($pos + strlen($rawTag) + 2));
192
    }
193
194
    public function getHref($type, $params) {
195
        $href = '';
196
        if (is_string($params)) {
197
            $href = $params;
198
        } elseif (empty($params['template']) && !empty($params['file'])) {
199
            $href = ($this->app->type != 'app' ? '/' . $this->app->name : '') . $params['file'];
200
        } elseif (!empty($params['template']) && !empty($params['file'])) {
201
            $href = $this->app->templatesPath . "/{$this->template->name}/{$type}/{$params['file']}";
202
        }
203
        return $href;
204
    }
205
206
    public function checkNeedLibs() {
207
        if (!empty($this->template->config['libs'])) {
208
            foreach ($this->template->config['libs'] as $libName => $libOptions) {
209
                if (!is_array($libOptions)) {
210
                    $libName = $libOptions;
211
                    $libOptions = [];
212
                }
213
                $this->app->libs->loadLib($libName, $libOptions);
214
            }
215
        }
216
        foreach ($this->dynAssets['js'] as $asset) {
217
            if (is_array($asset) && !empty($asset['libs'])) {
218
                foreach ($asset['libs'] as $libName) {
219
                    $this->app->libs->loadLib($libName);
220
                }
221
            }
222
        }
223
        foreach ($this->libAssets['js'] as $asset) {
224
            if (is_array($asset) && !empty($asset['libs'])) {
225
                foreach ($asset['libs'] as $libName) {
226
                    $this->app->libs->loadLib($libName);
227
                }
228
            }
229
        }
230
    }
231
232
    public function head() {
233
234
        echo "<title>{$this->title}</title>\n";
235
        if (!empty(\App::$primary->config['site']['favicon']) && file_exists(\App::$primary->path . '/' . \App::$primary->config['site']['favicon'])) {
236
            echo "        <link rel='shortcut icon' href='" . \App::$primary->config['site']['favicon'] . "' />";
237
        } elseif (!empty($this->template->config['favicon']) && file_exists($this->template->path . "/{$this->template->config['favicon']}")) {
238
            echo "        <link rel='shortcut icon' href='/templates/{$this->template->name}/{$this->template->config['favicon']}' />";
239
        } elseif (!empty($this->template->config['favicon']) && file_exists($this->app->path . "/static/images/{$this->template->config['favicon']}")) {
240
            echo "        <link rel='shortcut icon' href='/static/images/{$this->template->config['favicon']}' />";
241
        } elseif (file_exists($this->app->path . '/static/images/favicon.ico')) {
242
            echo "        <link rel='shortcut icon' href='/static/images/favicon.ico' />";
243
        }
244
245
        foreach ($this->getMetaTags() as $meta) {
246
            echo "\n        " . Html::el('meta', $meta, '', null);
0 ignored issues
show
Bug introduced by
The type Html was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
247
        }
248
249
        if (!empty(Inji::$config['assets']['js'])) {
250
            foreach (Inji::$config['assets']['js'] as $js) {
251
                $this->customAsset('js', $js);
252
            }
253
        }
254
255
        $this->checkNeedLibs();
256
        $this->parseCss();
257
        echo "\n        <script src='" . Statics::file("/static/system/js/Inji.js") . "'></script>";
0 ignored issues
show
Bug introduced by
The type Statics was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
258
    }
259
260
    public function parseCss() {
261
        $css = $this->getCss();
262
        $urls = [];
263
        $timeStr = '';
264
        $cssAll = '';
265
        $exclude = ['^http:', '^https:', '^//'];
266
        foreach ($css as $href) {
267
            if (!empty($this->loadedCss[$href])) {
268
                continue;
269
            }
270
            foreach ($exclude as $item) {
271
                if (preg_match("!{$item}!", $href)) {
272
                    echo "\n        <link href='{$href}' rel='stylesheet' type='text/css' />";
273
                    continue;
274
                }
275
            }
276
            $path = $this->app->staticLoader->parsePath($href);
277
            if (file_exists($path)) {
278
                $this->loadedCss[$href] = $href;
279
                $urls[$href] = $path;
280
                $timeStr .= filemtime($path);
281
            } else {
282
                echo "\n        <link href='{$href}' rel='stylesheet' type='text/css' />";
283
            }
284
        }
285
        if (!$urls) {
286
            return;
287
        }
288
        $timeMd5 = md5($timeStr);
289
        $cacheDir = Cache::getDir('static');
0 ignored issues
show
Bug introduced by
The type Cache was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
290
        if (!file_exists($cacheDir . 'all' . $timeMd5 . '.css')) {
291
            foreach ($urls as $primaryUrl => $url) {
292
                $source = file_get_contents($url);
293
                $rootPath = substr($primaryUrl, 0, strrpos($primaryUrl, '/'));
294
                $levelUpPath = substr($rootPath, 0, strrpos($rootPath, '/'));
295
                $source = preg_replace('!url\((\'?"?)[\.]{2}!isU', 'url($1' . $levelUpPath, $source);
296
                $source = preg_replace('!url\((\'?"?)[\.]{1}!isU', 'url($1' . $rootPath, $source);
297
                $source = preg_replace('#url\(([\'"]){1}(?!http|https|/|data\:)([^/])#isU', 'url($1' . $rootPath . '/$2', $source);
298
                $source = preg_replace('#url\((?!http|https|/|data\:|\'|")([^/])#isU', 'url(' . $rootPath . '/$1$2', $source);
299
                $cssAll .= $source . "\n";
300
            }
301
            file_put_contents($cacheDir . 'all' . $timeMd5 . '.css', $cssAll);
302
        }
303
        $id = 'css' . Tools::randomString();
0 ignored issues
show
Bug introduced by
The type Tools was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
304
        echo "\n        <link id='{$id}' href='/{$cacheDir}all{$timeMd5}.css' rel='stylesheet' type='text/css' />";
305
        if (!empty($this->template->config['staticUpdater'])) {
306
            $hash = json_encode(array_keys($urls));
307
            if (!empty($this->template->config['staticUpdaterSalt'])) {
308
                $hash .= $this->template->config['staticUpdaterSalt'];
309
            }
310
            $hash = md5($hash);
311
            ?>
312
            <script>
313
              setInterval(function () {
314
                var hash = '<?=$hash;?>';
315
                var files = '<?=http_build_query(['files' => array_keys($urls)]);?>';
316
                var timeHash = '<?=$timeMd5?>';
317
                var id = '<?=$id;?>';
318
                // 1. Создаём новый объект XMLHttpRequest
319
                var xhr = new XMLHttpRequest();
320
321
                // 2. Конфигурируем его: GET-запрос на URL 'phones.json'
322
                xhr.open('GET', '/view/checkStaticUpdates/' + hash + '/' + timeHash + '?' + files, false);
323
324
                // 3. Отсылаем запрос
325
                xhr.send();
326
327
                // 4. Если код ответа сервера не 200, то это ошибка
328
                if (xhr.status != 200) {
329
                  // обработать ошибку
330
                  //alert(xhr.status + ': ' + xhr.statusText); // пример вывода: 404: Not Found
331
                } else {
332
                  if (xhr.responseText.length > 0) {
333
                    var result = JSON.parse(xhr.responseText);
334
                    document.getElementById(id).href = result.path;
335
                    timeHash = result.timeHash;
336
                  }
337
                  // вывести результат
338
                  //alert(xhr.responseText); // responseText -- текст ответа.
339
                }
340
              }, 2000);
341
            </script>
342
            <?php
343
        }
344
345
    }
346
347
    public function getCss() {
348
        $css = [];
349
        if (!empty($this->libAssets['css'])) {
350
            $this->ResolveCssHref($this->libAssets['css'], 'libs', $css);
351
        }
352
        if (!empty($this->template->config['css'])) {
353
            $this->ResolveCssHref($this->template->config['css'], 'template', $css);
354
        }
355
        if (!empty($this->dynAssets['css'])) {
356
            $this->ResolveCssHref($this->dynAssets['css'], 'custom', $css);
357
        }
358
        return $css;
359
    }
360
361
    public function ResolveCssHref($cssArray, $type = 'custom', &$hrefs) {
362
        switch ($type) {
363
            case 'libs':
364
                foreach ($cssArray as $css) {
365
                    if (is_array($css)) {
366
                        $this->ResolveCssHref($css, $type, $hrefs);
367
                        continue;
368
                    }
369
                    $hrefs[$css] = $css;
370
                }
371
                break;
372
            case 'template':
373
                foreach ($cssArray as $css) {
374
                    if (is_array($css)) {
375
                        $this->ResolveCssHref($css, $type, $hrefs);
376
                        continue;
377
                    }
378
                    if (strpos($css, '://') !== false) {
379
                        $href = $css;
380
                    } else {
381
                        $href = $this->app->templatesPath . "/{$this->template->name}/css/{$css}";
382
                    }
383
                    $hrefs[$href] = $href;
384
                }
385
                break;
386
            case 'custom':
387
                foreach ($cssArray as $css) {
388
                    if (is_array($css)) {
389
                        $this->ResolveCssHref($css, $type, $hrefs);
390
                        continue;
391
                    }
392
                    if (strpos($css, '//') !== false) {
393
                        $href = $css;
394
                    } else {
395
                        $href = ($this->app->type != 'app' ? '/' . $this->app->name : '') . $css;
396
                    }
397
                    $hrefs[$href] = $href;
398
                }
399
                break;
400
        }
401
    }
402
403
    public function getMetaTags() {
404
        $metas = [];
405
406
        if (!empty($this->app->config['site']['keywords'])) {
407
            $metas['metaName:keywords'] = ['name' => 'keywords', 'content' => $this->app->config['site']['keywords']];
408
        }
409
        if (!empty($this->app->config['site']['description'])) {
410
            $metas['metaName:description'] = ['name' => 'description', 'content' => $this->app->config['site']['description']];
411
        }
412
        if (!empty($this->app->config['site']['metatags'])) {
413
            foreach ($this->app->config['site']['metatags'] as $meta) {
414
                if (!empty($meta['name'])) {
415
                    $metas['metaName:' . $meta['name']] = $meta;
416
                } elseif (!empty($meta['property'])) {
417
                    $metas['metaProperty:' . $meta['property']] = $meta;
418
                }
419
            }
420
        }
421
        if ($this->dynMetas) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->dynMetas of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
422
            $metas = array_merge($metas, $this->dynMetas);
423
        }
424
        return $metas;
425
    }
426
427
    public function addMetaTag($meta) {
428
        if (!empty($meta['name'])) {
429
            $this->dynMetas['metaName:' . $meta['name']] = $meta;
430
        } elseif (!empty($meta['property'])) {
431
            $this->dynMetas['metaProperty:' . $meta['property']] = $meta;
432
        }
433
    }
434
435
    public function bodyEnd() {
436
        $this->checkNeedLibs();
437
        $this->parseCss();
438
        $scripts = $this->getScripts();
439
        $onLoadModules = [];
440
        $scriptAll = '';
441
        $urls = [];
442
        $nativeUrl = [];
443
        $timeStr = '';
444
        $noParsedScripts = [];
445
        foreach ($scripts as $script) {
446
            if (is_string($script)) {
447
                if (!empty($urls[$script])) {
448
                    continue;
449
                }
450
451
                $path = $this->app->staticLoader->parsePath($script);
452
                if (file_exists($path)) {
453
                    $nativeUrl[$script] = $script;
454
                    $urls[$script] = $path;
455
                    $timeStr .= filemtime($path);
456
                } else {
457
                    $noParsedScripts[$script] = $script;
458
                }
459
            } elseif (!empty($script['file'])) {
460
                if (!empty($urls[$script['file']])) {
461
                    continue;
462
                }
463
464
                $path = $this->app->staticLoader->parsePath($script['file']);
465
                if (file_exists($path)) {
466
                    $nativeUrl[$script['file']] = $script['file'];
467
                    $urls[$script['file']] = $path;
468
                    if (!empty($script['name'])) {
469
                        $onLoadModules[$script['name']] = $script['name'];
470
                    }
471
                    $timeStr .= filemtime($path);
472
                } else {
473
                    $noParsedScripts[$script['file']] = $script['file'];
474
                }
475
            }
476
        }
477
478
        $timeMd5 = md5($timeStr);
479
        $cacheDir = Cache::getDir('static');
480
        if (!file_exists($cacheDir . 'all' . $timeMd5 . '.js')) {
481
            foreach ($urls as $url) {
482
                $scriptAll .= ";\n" . file_get_contents($url);
483
            }
484
            file_put_contents($cacheDir . 'all' . $timeMd5 . '.js', $scriptAll);
485
        }
486
        $options = [
487
            'scripts' => array_values($noParsedScripts),
488
            'compresedScripts' => $nativeUrl,
489
            'styles' => [],
490
            'appRoot' => $this->app->type == 'app' ? '/' : '/' . $this->app->name . '/',
491
            'onLoadModules' => $onLoadModules
492
        ];
493
        $options['scripts'][] = '/' . $cacheDir . 'all' . $timeMd5 . '.js';
494
        $this->widget('View\bodyEnd', compact('options'));
495
    }
496
497
    public function getScripts() {
498
        $scripts = [];
499
        if (!empty($this->libAssets['js'])) {
500
            $this->genScriptArray($this->libAssets['js'], 'libs', $scripts);
501
        }
502
        if (!empty($this->dynAssets['js'])) {
503
            $this->genScriptArray($this->dynAssets['js'], 'custom', $scripts);
504
        }
505
        if (!empty($this->template->config['js'])) {
506
            $this->genScriptArray($this->template->config['js'], 'template', $scripts);
507
        }
508
        return $scripts;
509
    }
510
511
    public function genScriptArray($jsArray, $type = 'custom', &$resultArray) {
512
        switch ($type) {
513
            case 'libs':
514
                foreach ($jsArray as $js) {
515
                    if (is_array($js)) {
516
                        $this->genScriptArray($js, $type, $resultArray);
517
                        continue;
518
                    }
519
                    if (strpos($js, '//') !== false) {
520
                        $href = $js;
521
                    } else {
522
                        $href = $this->getHref('js', $js);
523
                    }
524
                    if (!$href) {
525
                        continue;
526
                    }
527
528
                    $resultArray[] = $href;
529
                }
530
                break;
531
            case 'template':
532
                foreach ($jsArray as $js) {
533
                    if (is_array($js)) {
534
                        $this->genScriptArray($js, $type, $resultArray);
535
                        continue;
536
                    }
537
                    if (strpos($js, '//') !== false) {
538
                        $href = $js;
539
                    } else {
540
                        $href = $this->app->templatesPath . "/{$this->template->name}/js/{$js}";
541
                    }
542
                    $resultArray[] = $href;
543
                }
544
                break;
545
            case 'custom':
546
                foreach ($jsArray as $js) {
547
                    if (is_array($js)) {
548
                        if (!empty($js[0]) && is_array($js[0])) {
549
                            $this->genScriptArray($js, $type, $resultArray);
550
                            continue;
551
                        }
552
                        $asset = $js;
553
                    } else {
554
                        $asset = [];
555
                    }
556
                    $asset['file'] = $this->getHref('js', $js);
557
                    if (!$asset['file']) {
558
                        continue;
559
                    }
560
                    $resultArray[] = $asset;
561
                }
562
                break;
563
        }
564
    }
565
566
    public function customAsset($type, $asset, $lib = false) {
567
        if (!$lib) {
568
            $this->dynAssets[$type][] = $asset;
569
        } else {
570
            if (empty($this->libAssets[$type][$lib]) || !in_array($asset, $this->libAssets[$type][$lib])) {
571
                $this->libAssets[$type][$lib][] = $asset;
572
            }
573
        }
574
    }
575
576
    public function setTitle($title, $add = true) {
577
        if ($add && !empty($this->app->config['site']['name'])) {
578
            if ($title) {
579
                $this->title = $title . ' - ' . $this->app->config['site']['name'];
580
            } else {
581
                $this->title = $this->app->config['site']['name'];
582
            }
583
        } else {
584
            $this->title = $title;
585
        }
586
    }
587
588
    public function widget($_widgetName, $_params = [], $lineParams = null) {
589
        $_paths = $this->getWidgetPaths($_widgetName);
590
        $find = false;
591
        foreach ($_paths as $_path) {
592
            if (file_exists($_path)) {
593
                $find = true;
594
                break;
595
            }
596
        }
597
        if ($lineParams === null) {
598
            $lineParams = '';
599
            if ($_params) {
600
                $paramArray = false;
601
                foreach ($_params as $param) {
602
                    if (is_array($param) || is_object($param)) {
603
                        $paramArray = true;
604
                    }
605
                }
606
                if (!$paramArray) {
607
                    $lineParams = ':' . implode(':', $_params);
608
                }
609
            }
610
        }
611
        echo "<!--start:{WIDGET:{$_widgetName}{$lineParams}}-->\n";
612
        if ($find) {
613
            if ($_params && is_array($_params)) {
614
                extract($_params);
615
            }
616
            include $_path;
617
        }
618
        echo "<!--end:{WIDGET:{$_widgetName}{$lineParams}}-->\n";
619
    }
620
621
    public function getWidgetPaths($widgetName) {
622
        $paths = [];
623
        if (strpos($widgetName, '\\')) {
624
            $widgetName = explode('\\', $widgetName);
625
626
            $paths['templatePath_widgetDir'] = $this->templatesPath . '/' . $this->template->name . '/widgets/' . $widgetName[0] . '/' . $widgetName[1] . '/' . $widgetName[1] . '.php';
627
            $paths['templatePath'] = $this->templatesPath . '/' . $this->template->name . '/widgets/' . $widgetName[0] . '/' . $widgetName[1] . '.php';
628
            $modulePaths = Module::getModulePaths(ucfirst($widgetName[0]));
629
            foreach ($modulePaths as $pathName => $path) {
630
                $paths[$pathName . '_widgetDir'] = $path . '/widgets/' . $widgetName[1] . '/' . $widgetName[1] . '.php';
631
                $paths[$pathName] = $path . '/widgets/' . $widgetName[1] . '.php';
632
            }
633
            return $paths;
634
        } else {
635
            $paths['templatePath_widgetDir'] = $this->templatesPath . '/' . $this->template->name . '/widgets/' . $widgetName . '/' . $widgetName . '.php';
636
            $paths['templatePath'] = $this->templatesPath . '/' . $this->template->name . '/widgets/' . $widgetName . '.php';
637
638
            $paths['curAppPath_widgetDir'] = $this->app->path . '/widgets/' . $widgetName . '/' . $widgetName . '.php';
639
            $paths['curAppPath'] = $this->app->path . '/widgets/' . $widgetName . '.php';
640
641
            $paths['systemPath_widgetDir'] = INJI_SYSTEM_DIR . '/widgets/' . $widgetName . '/' . $widgetName . '.php';
642
            $paths['systemPath'] = INJI_SYSTEM_DIR . '/widgets/' . $widgetName . '.php';
643
        }
644
        return $paths;
645
    }
646
}