Passed
Pull Request — master (#124)
by Sergei
09:22
created

WebView::setJsVar()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 5
c 1
b 0
f 0
dl 0
loc 7
ccs 0
cts 6
cp 0
rs 10
cc 2
nc 2
nop 1
crap 6
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\View;
6
7
use Yiisoft\Arrays\ArrayHelper;
8
use Yiisoft\Html\Html;
9
use Yiisoft\View\Event\BodyBegin;
10
use Yiisoft\View\Event\BodyEnd;
11
use Yiisoft\View\Event\PageEnd;
12
13
/**
14
 * View represents a view object in the MVC pattern.
15
 *
16
 * View provides a set of methods (e.g. {@see render()} for rendering purpose.
17
 *
18
 * You can modify its configuration by adding an array to your application config under `components` as it is shown in
19
 * the following example:
20
 *
21
 * ```php
22
 * 'view' => [
23
 *     'theme' => 'app\themes\MyTheme',
24
 *     'renderers' => [
25
 *         // you may add Smarty or Twig renderer here
26
 *     ]
27
 *     // ...
28
 * ]
29
 * ```
30
 *
31
 * For more details and usage information on View, see the [guide article on views](guide:structure-views).
32
 */
33
class WebView extends View
34
{
35
    /**
36
     * The location of registered JavaScript code block or files.
37
     * This means the location is in the head section.
38
     */
39
    public const POSITION_HEAD = 1;
40
41
    /**
42
     * The location of registered JavaScript code block or files.
43
     * This means the location is at the beginning of the body section.
44
     */
45
    public const POSITION_BEGIN = 2;
46
47
    /**
48
     * The location of registered JavaScript code block or files.
49
     * This means the location is at the end of the body section.
50
     */
51
    public const POSITION_END = 3;
52
53
    /**
54
     * The location of registered JavaScript code block.
55
     * This means the JavaScript code block will be executed when HTML document composition is ready.
56
     */
57
    public const POSITION_READY = 4;
58
59
    /**
60
     * The location of registered JavaScript code block.
61
     * This means the JavaScript code block will be executed when HTML page is completely loaded.
62
     */
63
    public const POSITION_LOAD = 5;
64
65
    /**
66
     * This is internally used as the placeholder for receiving the content registered for the head section.
67
     */
68
    private const PLACEHOLDER_HEAD = '<![CDATA[YII-BLOCK-HEAD-%s]]>';
69
70
    /**
71
     * This is internally used as the placeholder for receiving the content registered for the beginning of the body
72
     * section.
73
     */
74
    private const PLACEHOLDER_BODY_BEGIN = '<![CDATA[YII-BLOCK-BODY-BEGIN-%s]]>';
75
76
    /**
77
     * This is internally used as the placeholder for receiving the content registered for the end of the body section.
78
     */
79
    private const PLACEHOLDER_BODY_END = '<![CDATA[YII-BLOCK-BODY-END-%s]]>';
80
81
    /**
82
     * @var string the page title
83
     */
84
    private string $title = '';
85
86
    /**
87
     * @var array the registered meta tags.
88
     *
89
     * {@see registerMetaTag()}
90
     */
91
    private array $metaTags = [];
92
93
    /**
94
     * @var array the registered link tags.
95
     *
96
     * {@see registerLinkTag()}
97
     */
98
    private array $linkTags = [];
99
100
    /**
101
     * @var array the registered CSS code blocks.
102
     *
103
     * {@see registerCss()}
104
     */
105
    private array $css = [];
106
107
    /**
108
     * @var array the registered CSS files.
109
     *
110
     * {@see registerCssFile()}
111
     */
112
    private array $cssFiles = [];
113
114
    /**
115
     * @var array the registered JS code blocks
116
     *
117
     * {@see registerJs()}
118
     */
119
    private array $js = [];
120
121
    /**
122
     * @var array the registered JS files.
123
     *
124
     * {@see registerJsFile()}
125
     */
126
    private array $jsFiles = [];
127
128
    /**
129
     * Marks the position of an HTML head section.
130
     */
131 4
    public function head(): void
132
    {
133 4
        echo sprintf(self::PLACEHOLDER_HEAD, $this->getPlaceholderSignature());
134 4
    }
135
136
    /**
137
     * Marks the beginning of an HTML body section.
138
     */
139 4
    public function beginBody(): void
140
    {
141 4
        echo sprintf(self::PLACEHOLDER_BODY_BEGIN, $this->getPlaceholderSignature());
142 4
        $this->eventDispatcher->dispatch(new BodyBegin($this->getViewFile()));
0 ignored issues
show
Bug introduced by
It seems like $this->getViewFile() can also be of type boolean; however, parameter $file of Yiisoft\View\Event\BodyBegin::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

142
        $this->eventDispatcher->dispatch(new BodyBegin(/** @scrutinizer ignore-type */ $this->getViewFile()));
Loading history...
143 4
    }
144
145
    /**
146
     * Marks the ending of an HTML body section.
147
     */
148 4
    public function endBody(): void
149
    {
150 4
        $this->eventDispatcher->dispatch(new BodyEnd($this->getViewFile()));
0 ignored issues
show
Bug introduced by
It seems like $this->getViewFile() can also be of type boolean; however, parameter $file of Yiisoft\View\Event\BodyEnd::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

150
        $this->eventDispatcher->dispatch(new BodyEnd(/** @scrutinizer ignore-type */ $this->getViewFile()));
Loading history...
151 4
        echo sprintf(self::PLACEHOLDER_BODY_END, $this->getPlaceholderSignature());
152 4
    }
153
154
    /**
155
     * Marks the ending of an HTML page.
156
     *
157
     * @param bool $ajaxMode whether the view is rendering in AJAX mode. If true, the JS scripts registered at
158
     * {@see POSITION_READY} and {@see POSITION_LOAD} positions will be rendered at the end of the view like
159
     * normal scripts.
160
     */
161 4
    public function endPage($ajaxMode = false): void
162
    {
163 4
        $this->eventDispatcher->dispatch(new PageEnd($this->getViewFile()));
0 ignored issues
show
Bug introduced by
It seems like $this->getViewFile() can also be of type boolean; however, parameter $file of Yiisoft\View\Event\PageEnd::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

163
        $this->eventDispatcher->dispatch(new PageEnd(/** @scrutinizer ignore-type */ $this->getViewFile()));
Loading history...
164
165 4
        $content = ob_get_clean();
166
167 4
        echo strtr($content, [
168 4
            sprintf(self::PLACEHOLDER_HEAD, $this->getPlaceholderSignature()) => $this->renderHeadHtml(),
169 4
            sprintf(self::PLACEHOLDER_BODY_BEGIN, $this->getPlaceholderSignature()) => $this->renderBodyBeginHtml(),
170 4
            sprintf(self::PLACEHOLDER_BODY_END, $this->getPlaceholderSignature()) => $this->renderBodyEndHtml($ajaxMode),
171
        ]);
172
173 4
        $this->clear();
174 4
    }
175
176
    /**
177
     * Renders a view in response to an AJAX request.
178
     *
179
     * This method is similar to {@see render()} except that it will surround the view being rendered with the calls of
180
     * {@see beginPage()}, {@see head()}, {@see beginBody()}, {@see endBody()} and {@see endPage()}. By doing so, the
181
     * method is able to inject into the rendering result with JS/CSS scripts and files that are registered with the
182
     * view.
183
     *
184
     * @param string $view the view name. Please refer to {@see render()} on how to specify this parameter.
185
     * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view
186
     * file.
187
     * @param ViewContextInterface|null $context the context that the view should use for rendering the view. If null,
188
     * existing {@see context} will be used.
189
     *
190
     * @return string the rendering result
191
     *
192
     * {@see render()}
193
     */
194
    public function renderAjax(string $view, array $params = [], ?ViewContextInterface $context = null): string
195
    {
196
        $viewFile = $this->findTemplateFile($view, $context);
197
198
        ob_start();
199
        PHP_VERSION_ID >= 80000 ? ob_implicit_flush(false) : ob_implicit_flush(0);
200
201
        $this->beginPage();
202
        $this->head();
203
        $this->beginBody();
204
        echo $this->renderFile($viewFile, $params, $context);
205
        $this->endBody();
206
        $this->endPage(true);
207
208
        return ob_get_clean();
209
    }
210
211
    /**
212
     * Clears up the registered meta tags, link tags, css/js scripts and files.
213
     */
214 4
    public function clear(): void
215
    {
216 4
        $this->metaTags = [];
217 4
        $this->linkTags = [];
218 4
        $this->css = [];
219 4
        $this->cssFiles = [];
220 4
        $this->js = [];
221 4
        $this->jsFiles = [];
222 4
    }
223
224
    /**
225
     * Registers a meta tag.
226
     *
227
     * For example, a description meta tag can be added like the following:
228
     *
229
     * ```php
230
     * $view->registerMetaTag([
231
     *     'name' => 'description',
232
     *     'content' => 'This website is about funny raccoons.'
233
     * ]);
234
     * ```
235
     *
236
     * will result in the meta tag `<meta name="description" content="This website is about funny raccoons.">`.
237
     *
238
     * @param array $options the HTML attributes for the meta tag.
239
     * @param string $key the key that identifies the meta tag. If two meta tags are registered with the same key, the
240
     * latter will overwrite the former. If this is null, the new meta tag will be appended to the
241
     * existing ones.
242
     */
243
    public function registerMetaTag(array $options, string $key = null): void
244
    {
245
        if ($key === null) {
246
            $this->metaTags[] = Html::tag('meta', '', $options);
247
        } else {
248
            $this->metaTags[$key] = Html::tag('meta', '', $options);
249
        }
250
    }
251
252
    /**
253
     * Registers a link tag.
254
     *
255
     * For example, a link tag for a custom [favicon](http://www.w3.org/2005/10/howto-favicon) can be added like the
256
     * following:
257
     *
258
     * ```php
259
     * $view->registerLinkTag(['rel' => 'icon', 'type' => 'image/png', 'href' => '/myicon.png']);
260
     * ```
261
     *
262
     * which will result in the following HTML: `<link rel="icon" type="image/png" href="/myicon.png">`.
263
     *
264
     * **Note:** To register link tags for CSS stylesheets, use {@see registerCssFile()]} instead, which has more
265
     * options for this kind of link tag.
266
     *
267
     * @param array $options the HTML attributes for the link tag.
268
     * @param string|null $key the key that identifies the link tag. If two link tags are registered with the same
269
     * key, the latter will overwrite the former. If this is null, the new link tag will be appended
270
     * to the existing ones.
271
     */
272
    public function registerLinkTag(array $options, ?string $key = null): void
273
    {
274
        if ($key === null) {
275
            $this->linkTags[] = Html::tag('link', '', $options);
276
        } else {
277
            $this->linkTags[$key] = Html::tag('link', '', $options);
278
        }
279
    }
280
281
    /**
282
     * Registers a CSS code block.
283
     *
284
     * @param string $css the content of the CSS code block to be registered
285
     * @param array $options the HTML attributes for the `<style>`-tag.
286
     * @param string $key the key that identifies the CSS code block. If null, it will use $css as the key. If two CSS
287
     * code blocks are registered with the same key, the latter will overwrite the former.
288
     */
289
    public function registerCss(string $css, array $options = [], string $key = null): void
290
    {
291
        $key = $key ?: md5($css);
292
        $this->css[$key] = Html::style($css, $options);
293
    }
294
295
    /**
296
     * Registers a CSS file.
297
     *
298
     * This method should be used for simple registration of CSS files. If you want to use features of
299
     * {@see \Yiisoft\Assets\AssetManager} like appending timestamps to the URL and file publishing options, use
300
     * {@see \Yiisoft\Assets\AssetBundle}.
301
     *
302
     * @param string $url the CSS file to be registered.
303
     * @param array $options the HTML attributes for the link tag. Please refer to {@see \Yiisoft\Html\Html::cssFile()}
304
     * for the supported options.
305
     * @param string $key the key that identifies the CSS script file. If null, it will use $url as the key. If two CSS
306
     * files are registered with the same key, the latter will overwrite the former.
307
     */
308 1
    public function registerCssFile(string $url, array $options = [], string $key = null): void
309
    {
310 1
        $key = $key ?: $url;
311
312 1
        $this->cssFiles[$key] = Html::cssFile($url, $options);
313 1
    }
314
315
    /**
316
     * Registers a JS code block.
317
     *
318
     * @param string $js the JS code block to be registered
319
     * @param int $position the position at which the JS script tag should be inserted in a page.
320
     *
321
     * The possible values are:
322
     *
323
     * - {@see POSITION_HEAD}: in the head section
324
     * - {@see POSITION_BEGIN}: at the beginning of the body section
325
     * - {@see POSITION_END}: at the end of the body section. This is the default value.
326
     * - {@see POSITION_LOAD}: executed when HTML page is completely loaded.
327
     * - {@see POSITION_READY}: executed when HTML document composition is ready.
328
     * @param string $key the key that identifies the JS code block. If null, it will use $js as the key. If two JS code
329
     * blocks are registered with the same key, the latter will overwrite the former.
330
     */
331 1
    public function registerJs(string $js, int $position = self::POSITION_END, string $key = null): void
332
    {
333 1
        $key = $key ?: md5($js);
334 1
        $this->js[$position][$key] = $js;
335 1
    }
336
337
    /**
338
     * Registers a JS file.
339
     *
340
     * This method should be used for simple registration of JS files. If you want to use features of
341
     * {@see \Yiisoft\Assets\AssetManager} like appending timestamps to the URL and file publishing options, use
342
     * {@see \Yiisoft\Assets\AssetBundle}.
343
     *
344
     * @param string $url the JS file to be registered.
345
     * @param array $options the HTML attributes for the script tag. The following options are specially handled and
346
     * are not treated as HTML attributes:
347
     *
348
     * - `position`: specifies where the JS script tag should be inserted in a page. The possible values are:
349
     *     * {@see POSITION_HEAD}: in the head section
350
     *     * {@see POSITION_BEGIN}: at the beginning of the body section
351
     *     * {@see POSITION_END}: at the end of the body section. This is the default value.
352
     *
353
     * Please refer to {@see \Yiisoft\Html\Html::javaScriptFile()} for other supported options.
354
     * @param string $key the key that identifies the JS script file. If null, it will use $url as the key. If two JS
355
     * files are registered with the same key at the same position, the latter will overwrite the former.
356
     * Note that position option takes precedence, thus files registered with the same key, but different
357
     * position option will not override each other.
358
     */
359 1
    public function registerJsFile(string $url, array $options = [], string $key = null): void
360
    {
361 1
        $key = $key ?: $url;
362
363 1
        $position = ArrayHelper::remove($options, 'position', self::POSITION_END);
364 1
        $this->jsFiles[$position][$key] = Html::javaScriptFile($url, $options);
365 1
    }
366
367
    /**
368
     * Registers a JS code block defining a variable. The name of variable will be used as key, preventing duplicated
369
     * variable names.
370
     *
371
     * @param string $name Name of the variable
372
     * @param array|string $value Value of the variable
373
     * @param int $position the position in a page at which the JavaScript variable should be inserted.
374
     *
375
     * The possible values are:
376
     *
377
     * - {@see POSITION_HEAD}: in the head section. This is the default value.
378
     * - {@see POSITION_BEGIN}: at the beginning of the body section.
379
     * - {@see POSITION_END}: at the end of the body section.
380
     * - {@see POSITION_LOAD}: enclosed within jQuery(window).load().
381
     *   Note that by using this position, the method will automatically register the jQuery js file.
382
     * - {@see POSITION_READY}: enclosed within jQuery(document).ready().
383
     *   Note that by using this position, the method will automatically register the jQuery js file.
384
     */
385 1
    public function registerJsVar(string $name, $value, int $position = self::POSITION_HEAD): void
386
    {
387 1
        $js = sprintf('var %s = %s;', $name, \Yiisoft\Json\Json::htmlEncode($value));
388 1
        $this->registerJs($js, $position, $name);
389 1
    }
390
391
    /**
392
     * Renders the content to be inserted in the head section.
393
     *
394
     * The content is rendered using the registered meta tags, link tags, CSS/JS code blocks and files.
395
     *
396
     * @return string the rendered content
397
     */
398 4
    protected function renderHeadHtml(): string
399
    {
400 4
        $lines = [];
401 4
        if (!empty($this->metaTags)) {
402
            $lines[] = implode("\n", $this->metaTags);
403
        }
404
405 4
        if (!empty($this->linkTags)) {
406
            $lines[] = implode("\n", $this->linkTags);
407
        }
408 4
        if (!empty($this->cssFiles)) {
409 1
            $lines[] = implode("\n", $this->cssFiles);
410
        }
411 4
        if (!empty($this->css)) {
412
            $lines[] = implode("\n", $this->css);
413
        }
414 4
        if (!empty($this->jsFiles[self::POSITION_HEAD])) {
415 1
            $lines[] = implode("\n", $this->jsFiles[self::POSITION_HEAD]);
416
        }
417 4
        if (!empty($this->js[self::POSITION_HEAD])) {
418 1
            $lines[] = Html::script(implode("\n", $this->js[self::POSITION_HEAD]));
419
        }
420
421 4
        return empty($lines) ? '' : implode("\n", $lines);
422
    }
423
424
    /**
425
     * Renders the content to be inserted at the beginning of the body section.
426
     *
427
     * The content is rendered using the registered JS code blocks and files.
428
     *
429
     * @return string the rendered content
430
     */
431 4
    protected function renderBodyBeginHtml(): string
432
    {
433 4
        $lines = [];
434 4
        if (!empty($this->jsFiles[self::POSITION_BEGIN])) {
435 1
            $lines[] = implode("\n", $this->jsFiles[self::POSITION_BEGIN]);
436
        }
437 4
        if (!empty($this->js[self::POSITION_BEGIN])) {
438
            $lines[] = Html::script(implode("\n", $this->js[self::POSITION_BEGIN]));
439
        }
440
441 4
        return empty($lines) ? '' : implode("\n", $lines);
442
    }
443
444
    /**
445
     * Renders the content to be inserted at the end of the body section.
446
     *
447
     * The content is rendered using the registered JS code blocks and files.
448
     *
449
     * @param bool $ajaxMode whether the view is rendering in AJAX mode. If true, the JS scripts registered at
450
     * {@see POSITION_READY} and {@see POSITION_LOAD} positions will be rendered at the end of the view like normal
451
     * scripts.
452
     *
453
     * @return string the rendered content
454
     */
455 4
    protected function renderBodyEndHtml(bool $ajaxMode): string
456
    {
457 4
        $lines = [];
458
459 4
        if (!empty($this->jsFiles[self::POSITION_END])) {
460 1
            $lines[] = implode("\n", $this->jsFiles[self::POSITION_END]);
461
        }
462
463 4
        if ($ajaxMode) {
464
            $scripts = [];
465
            if (!empty($this->js[self::POSITION_END])) {
466
                $scripts[] = implode("\n", $this->js[self::POSITION_END]);
467
            }
468
            if (!empty($this->js[self::POSITION_READY])) {
469
                $scripts[] = implode("\n", $this->js[self::POSITION_READY]);
470
            }
471
            if (!empty($this->js[self::POSITION_LOAD])) {
472
                $scripts[] = implode("\n", $this->js[self::POSITION_LOAD]);
473
            }
474
            if (!empty($scripts)) {
475
                $lines[] = Html::script(implode("\n", $scripts));
476
            }
477
        } else {
478 4
            if (!empty($this->js[self::POSITION_END])) {
479
                $lines[] = Html::script(implode("\n", $this->js[self::POSITION_END]));
480
            }
481 4
            if (!empty($this->js[self::POSITION_READY])) {
482
                $js = "document.addEventListener('DOMContentLoaded', function(event) {\n" . implode("\n", $this->js[self::POSITION_READY]) . "\n});";
483
                $lines[] = Html::script($js);
484
            }
485 4
            if (!empty($this->js[self::POSITION_LOAD])) {
486
                $js = "window.addEventListener('load', function (event) {\n" . implode("\n", $this->js[self::POSITION_LOAD]) . "\n});";
487
                $lines[] = Html::script($js);
488
            }
489
        }
490
491 4
        return empty($lines) ? '' : implode("\n", $lines);
492
    }
493
494
    /**
495
     * Get title in views.
496
     *
497
     * in Layout:
498
     *
499
     * ```php
500
     * <title><?= Html::encode($this->getTitle()) ?></title>
501
     * ```
502
     *
503
     * in Views:
504
     *
505
     * ```php
506
     * $this->setTitle('Web Application - Yii 3.0.');
507
     * ```
508
     *
509
     * @return string
510
     */
511
    public function getTitle(): string
512
    {
513
        return $this->title;
514
    }
515
516
    /**
517
     * It processes the CSS configuration generated by the asset manager and converts it into HTML code.
518
     *
519
     * @param array $cssFiles
520
     */
521
    public function setCssFiles(array $cssFiles): void
522
    {
523
        foreach ($cssFiles as $key => $value) {
524
            $this->registerCssFile(
525
                $cssFiles[$key]['url'],
526
                $cssFiles[$key]['attributes']
527
            );
528
        }
529
    }
530
531
    /**
532
     * It processes the JS configuration generated by the asset manager and converts it into HTML code.
533
     *
534
     * @param array $jsFiles
535
     */
536
    public function setJsFiles(array $jsFiles): void
537
    {
538
        foreach ($jsFiles as $key => $value) {
539
            $this->registerJsFile(
540
                $jsFiles[$key]['url'],
541
                $jsFiles[$key]['attributes']
542
            );
543
        }
544
    }
545
546
    /**
547
     * It processes the JS strings generated by the asset manager.
548
     *
549
     * @param array $jsStrings
550
     */
551
    public function setJsStrings(array $jsStrings): void
552
    {
553
        foreach ($jsStrings as $value) {
554
            $this->registerJs(
555
                $value['string'],
556
                $value['attributes']['position']
557
            );
558
        }
559
    }
560
561
    /**
562
     * It processes the JS variables generated by the asset manager and converts it into JS code.
563
     *
564
     * @param array $jsVar
565
     */
566
    public function setJsVar(array $jsVar): void
567
    {
568
        foreach ($jsVar as $key => $value) {
569
            $this->registerJsVar(
570
                (string)$key,
571
                $value['variables'],
572
                $value['attributes']['position']
573
            );
574
        }
575
    }
576
577
    /**
578
     * Set title in views.
579
     *
580
     * {@see getTitle()}
581
     *
582
     * @param string $value
583
     */
584
    public function setTitle($value): void
585
    {
586
        $this->title = $value;
587
    }
588
}
589