Passed
Pull Request — master (#143)
by Sergei
02:25
created

WebView::clear()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 6
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 8
ccs 7
cts 7
cp 1
crap 1
rs 10
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\Html\Tag\Script;
10
use Yiisoft\View\Event\BodyBegin;
11
use Yiisoft\View\Event\BodyEnd;
12
use Yiisoft\View\Event\PageBegin;
13
use Yiisoft\View\Event\PageEnd;
14
15
/**
16
 * View represents a view object in the MVC pattern.
17
 *
18
 * View provides a set of methods (e.g. {@see render()} for rendering purpose.
19
 *
20
 * You can modify its configuration by adding an array to your application config under `components` as it is shown in
21
 * the following example:
22
 *
23
 * ```php
24
 * 'view' => [
25
 *     'theme' => 'app\themes\MyTheme',
26
 *     'renderers' => [
27
 *         // you may add Smarty or Twig renderer here
28
 *     ]
29
 *     // ...
30
 * ]
31
 * ```
32
 *
33
 * For more details and usage information on View, see the [guide article on views](guide:structure-views).
34
 */
35
final class WebView extends BaseView
36
{
37
    /**
38
     * The location of registered JavaScript code block or files.
39
     * This means the location is in the head section.
40
     */
41
    public const POSITION_HEAD = 1;
42
43
    /**
44
     * The location of registered JavaScript code block or files.
45
     * This means the location is at the beginning of the body section.
46
     */
47
    public const POSITION_BEGIN = 2;
48
49
    /**
50
     * The location of registered JavaScript code block or files.
51
     * This means the location is at the end of the body section.
52
     */
53
    public const POSITION_END = 3;
54
55
    /**
56
     * The location of registered JavaScript code block.
57
     * This means the JavaScript code block will be executed when HTML document composition is ready.
58
     */
59
    public const POSITION_READY = 4;
60
61
    /**
62
     * The location of registered JavaScript code block.
63
     * This means the JavaScript code block will be executed when HTML page is completely loaded.
64
     */
65
    public const POSITION_LOAD = 5;
66
67
    /**
68
     * This is internally used as the placeholder for receiving the content registered for the head section.
69
     */
70
    private const PLACEHOLDER_HEAD = '<![CDATA[YII-BLOCK-HEAD-%s]]>';
71
72
    /**
73
     * This is internally used as the placeholder for receiving the content registered for the beginning of the body
74
     * section.
75
     */
76
    private const PLACEHOLDER_BODY_BEGIN = '<![CDATA[YII-BLOCK-BODY-BEGIN-%s]]>';
77
78
    /**
79
     * This is internally used as the placeholder for receiving the content registered for the end of the body section.
80
     */
81
    private const PLACEHOLDER_BODY_END = '<![CDATA[YII-BLOCK-BODY-END-%s]]>';
82
83
    /**
84
     * @var string the page title
85
     */
86
    private string $title = '';
87
88
    /**
89
     * @var array the registered meta tags.
90
     *
91
     * {@see registerMetaTag()}
92
     */
93
    private array $metaTags = [];
94
95
    /**
96
     * @var array the registered link tags.
97
     *
98
     * {@see registerLinkTag()}
99
     */
100
    private array $linkTags = [];
101
102
    /**
103
     * @var array the registered CSS code blocks.
104
     *
105
     * {@see registerCss()}
106
     */
107
    private array $css = [];
108
109
    /**
110
     * @var array the registered CSS files.
111
     *
112
     * {@see registerCssFile()}
113
     */
114
    private array $cssFiles = [];
115
116
    /**
117
     * @var array the registered JS code blocks
118
     * @psalm-var array<int, string[]|Script[]>
119
     *
120
     * {@see registerJs()}
121
     */
122
    private array $js = [];
123
124
    /**
125
     * @var array the registered JS files.
126
     *
127
     * {@see registerJsFile()}
128
     */
129
    private array $jsFiles = [];
130
131
    /**
132
     * Marks the position of an HTML head section.
133
     */
134 11
    public function head(): void
135
    {
136 11
        echo sprintf(self::PLACEHOLDER_HEAD, $this->getPlaceholderSignature());
137 11
    }
138
139
    /**
140
     * Marks the beginning of an HTML body section.
141
     */
142 11
    public function beginBody(): void
143
    {
144 11
        echo sprintf(self::PLACEHOLDER_BODY_BEGIN, $this->getPlaceholderSignature());
145 11
        $this->eventDispatcher->dispatch(new BodyBegin($this->getViewFile()));
146 11
    }
147
148
    /**
149
     * Marks the ending of an HTML body section.
150
     */
151 11
    public function endBody(): void
152
    {
153 11
        $this->eventDispatcher->dispatch(new BodyEnd($this->getViewFile()));
154 11
        echo sprintf(self::PLACEHOLDER_BODY_END, $this->getPlaceholderSignature());
155 11
    }
156
157
    /**
158
     * Marks the beginning of a page.
159
     */
160 11
    public function beginPage(): void
161
    {
162 11
        ob_start();
163 11
        PHP_VERSION_ID >= 80000 ? ob_implicit_flush(false) : ob_implicit_flush(0);
164
165 11
        $this->eventDispatcher->dispatch(new PageBegin($this->getViewFile()));
166 11
    }
167
168
    /**
169
     * Marks the ending of an HTML page.
170
     *
171
     * @param bool $ajaxMode whether the view is rendering in AJAX mode. If true, the JS scripts registered at
172
     * {@see POSITION_READY} and {@see POSITION_LOAD} positions will be rendered at the end of the view like
173
     * normal scripts.
174
     */
175 11
    public function endPage($ajaxMode = false): void
176
    {
177 11
        $this->eventDispatcher->dispatch(new PageEnd($this->getViewFile()));
178
179 11
        $content = ob_get_clean();
180
181 11
        echo strtr($content, [
182 11
            sprintf(self::PLACEHOLDER_HEAD, $this->getPlaceholderSignature()) => $this->renderHeadHtml(),
183 11
            sprintf(self::PLACEHOLDER_BODY_BEGIN, $this->getPlaceholderSignature()) => $this->renderBodyBeginHtml(),
184 11
            sprintf(self::PLACEHOLDER_BODY_END, $this->getPlaceholderSignature()) => $this->renderBodyEndHtml($ajaxMode),
185
        ]);
186
187 11
        $this->clear();
188 11
    }
189
190
    /**
191
     * Renders a view in response to an AJAX request.
192
     *
193
     * This method is similar to {@see render()} except that it will surround the view being rendered with the calls of
194
     * {@see beginPage()}, {@see head()}, {@see beginBody()}, {@see endBody()} and {@see endPage()}. By doing so, the
195
     * method is able to inject into the rendering result with JS/CSS scripts and files that are registered with the
196
     * view.
197
     *
198
     * @param string $view the view name. Please refer to {@see render()} on how to specify this parameter.
199
     * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view
200
     * file.
201
     *
202
     * @return string the rendering result
203
     *
204
     * {@see render()}
205
     */
206 2
    public function renderAjax(string $view, array $params = []): string
207
    {
208 2
        $viewFile = $this->findTemplateFile($view);
209
210 2
        ob_start();
211 2
        PHP_VERSION_ID >= 80000 ? ob_implicit_flush(false) : ob_implicit_flush(0);
212
213 2
        $this->beginPage();
214 2
        $this->head();
215 2
        $this->beginBody();
216 2
        echo $this->renderFile($viewFile, $params);
217 2
        $this->endBody();
218 2
        $this->endPage(true);
219
220 2
        return ob_get_clean();
221
    }
222
223
    /**
224
     * Clears up the registered meta tags, link tags, css/js scripts and files.
225
     */
226 11
    public function clear(): void
227
    {
228 11
        $this->metaTags = [];
229 11
        $this->linkTags = [];
230 11
        $this->css = [];
231 11
        $this->cssFiles = [];
232 11
        $this->js = [];
233 11
        $this->jsFiles = [];
234 11
    }
235
236
    /**
237
     * Registers a meta tag.
238
     *
239
     * For example, a description meta tag can be added like the following:
240
     *
241
     * ```php
242
     * $view->registerMetaTag([
243
     *     'name' => 'description',
244
     *     'content' => 'This website is about funny raccoons.'
245
     * ]);
246
     * ```
247
     *
248
     * will result in the meta tag `<meta name="description" content="This website is about funny raccoons.">`.
249
     *
250
     * @param array $options the HTML attributes for the meta tag.
251
     * @param string $key the key that identifies the meta tag. If two meta tags are registered with the same key, the
252
     * latter will overwrite the former. If this is null, the new meta tag will be appended to the
253
     * existing ones.
254
     */
255 1
    public function registerMetaTag(array $options, string $key = null): void
256
    {
257 1
        if ($key === null) {
258 1
            $this->metaTags[] = Html::meta()->attributes($options)->render();
259
        } else {
260
            $this->metaTags[$key] = Html::meta()->attributes($options)->render();
261
        }
262 1
    }
263
264
    /**
265
     * Registers a link tag.
266
     *
267
     * For example, a link tag for a custom [favicon](http://www.w3.org/2005/10/howto-favicon) can be added like the
268
     * following:
269
     *
270
     * ```php
271
     * $view->registerLinkTag(['rel' => 'icon', 'type' => 'image/png', 'href' => '/myicon.png']);
272
     * ```
273
     *
274
     * which will result in the following HTML: `<link rel="icon" type="image/png" href="/myicon.png">`.
275
     *
276
     * **Note:** To register link tags for CSS stylesheets, use {@see registerCssFile()]} instead, which has more
277
     * options for this kind of link tag.
278
     *
279
     * @param array $options the HTML attributes for the link tag.
280
     * @param string|null $key the key that identifies the link tag. If two link tags are registered with the same
281
     * key, the latter will overwrite the former. If this is null, the new link tag will be appended
282
     * to the existing ones.
283
     */
284 1
    public function registerLinkTag(array $options, ?string $key = null): void
285
    {
286 1
        if ($key === null) {
287 1
            $this->linkTags[] = Html::link()->attributes($options)->render();
288
        } else {
289
            $this->linkTags[$key] = Html::link()->attributes($options)->render();
290
        }
291 1
    }
292
293
    /**
294
     * Registers a CSS code block.
295
     *
296
     * @param string $css the content of the CSS code block to be registered
297
     * @param array $options the HTML attributes for the `<style>`-tag.
298
     * @param string $key the key that identifies the CSS code block. If null, it will use $css as the key. If two CSS
299
     * code blocks are registered with the same key, the latter will overwrite the former.
300
     */
301 1
    public function registerCss(string $css, array $options = [], string $key = null): void
302
    {
303 1
        $key = $key ?: md5($css);
304 1
        $this->css[$key] = Html::style($css, $options)->render();
305 1
    }
306
307
    /**
308
     * Registers a CSS file.
309
     *
310
     * This method should be used for simple registration of CSS files. If you want to use features of
311
     * {@see \Yiisoft\Assets\AssetManager} like appending timestamps to the URL and file publishing options, use
312
     * {@see \Yiisoft\Assets\AssetBundle}.
313
     *
314
     * @param string $url the CSS file to be registered.
315
     * @param array $options the HTML attributes for the link tag. Please refer to {@see \Yiisoft\Html\Html::cssFile()}
316
     * for the supported options.
317
     * @param string $key the key that identifies the CSS script file. If null, it will use $url as the key. If two CSS
318
     * files are registered with the same key, the latter will overwrite the former.
319
     */
320 1
    public function registerCssFile(string $url, array $options = [], string $key = null): void
321
    {
322 1
        $key = $key ?: $url;
323
324 1
        $this->cssFiles[$key] = Html::cssFile($url, $options)->render();
325 1
    }
326
327
    /**
328
     * Registers a JS code block.
329
     *
330
     * @param string $js the JS code block to be registered
331
     * @param int $position the position at which the JS script tag should be inserted in a page.
332
     *
333
     * The possible values are:
334
     *
335
     * - {@see POSITION_HEAD}: in the head section
336
     * - {@see POSITION_BEGIN}: at the beginning of the body section
337
     * - {@see POSITION_END}: at the end of the body section. This is the default value.
338
     * - {@see POSITION_LOAD}: executed when HTML page is completely loaded.
339
     * - {@see POSITION_READY}: executed when HTML document composition is ready.
340
     * @param string $key the key that identifies the JS code block. If null, it will use $js as the key. If two JS code
341
     * blocks are registered with the same key, the latter will overwrite the former.
342
     */
343 3
    public function registerJs(string $js, int $position = self::POSITION_END, string $key = null): void
344
    {
345 3
        $key = $key ?: md5($js);
346 3
        $this->js[$position][$key] = $js;
347 3
    }
348
349
    /**
350
     * Register a `script` tag
351
     *
352
     * @see registerJs()
353
     */
354 3
    public function registerScriptTag(Script $script, int $position = self::POSITION_END, string $key = null): void
355
    {
356 3
        $key = $key ?: md5($script->render());
357 3
        $this->js[$position][$key] = $script;
358 3
    }
359
360
    /**
361
     * Registers a JS file.
362
     *
363
     * This method should be used for simple registration of JS files. If you want to use features of
364
     * {@see \Yiisoft\Assets\AssetManager} like appending timestamps to the URL and file publishing options, use
365
     * {@see \Yiisoft\Assets\AssetBundle}.
366
     *
367
     * @param string $url the JS file to be registered.
368
     * @param array $options the HTML attributes for the script tag. The following options are specially handled and
369
     * are not treated as HTML attributes:
370
     *
371
     * - `position`: specifies where the JS script tag should be inserted in a page. The possible values are:
372
     *     * {@see POSITION_HEAD}: in the head section
373
     *     * {@see POSITION_BEGIN}: at the beginning of the body section
374
     *     * {@see POSITION_END}: at the end of the body section. This is the default value.
375
     *
376
     * Please refer to {@see \Yiisoft\Html\Html::javaScriptFile()} for other supported options.
377
     * @param string $key the key that identifies the JS script file. If null, it will use $url as the key. If two JS
378
     * files are registered with the same key at the same position, the latter will overwrite the former.
379
     * Note that position option takes precedence, thus files registered with the same key, but different
380
     * position option will not override each other.
381
     */
382 1
    public function registerJsFile(string $url, array $options = [], string $key = null): void
383
    {
384 1
        $key = $key ?: $url;
385
386 1
        $position = ArrayHelper::remove($options, 'position', self::POSITION_END);
387 1
        $this->jsFiles[$position][$key] = Html::javaScriptFile($url, $options)->render();
388 1
    }
389
390
    /**
391
     * Registers a JS code block defining a variable. The name of variable will be used as key, preventing duplicated
392
     * variable names.
393
     *
394
     * @param string $name Name of the variable
395
     * @param array|string $value Value of the variable
396
     * @param int $position the position in a page at which the JavaScript variable should be inserted.
397
     *
398
     * The possible values are:
399
     *
400
     * - {@see POSITION_HEAD}: in the head section. This is the default value.
401
     * - {@see POSITION_BEGIN}: at the beginning of the body section.
402
     * - {@see POSITION_END}: at the end of the body section.
403
     * - {@see POSITION_LOAD}: enclosed within jQuery(window).load().
404
     *   Note that by using this position, the method will automatically register the jQuery js file.
405
     * - {@see POSITION_READY}: enclosed within jQuery(document).ready().
406
     *   Note that by using this position, the method will automatically register the jQuery js file.
407
     */
408 1
    public function registerJsVar(string $name, $value, int $position = self::POSITION_HEAD): void
409
    {
410 1
        $js = sprintf('var %s = %s;', $name, \Yiisoft\Json\Json::htmlEncode($value));
411 1
        $this->registerJs($js, $position, $name);
412 1
    }
413
414
    /**
415
     * Renders the content to be inserted in the head section.
416
     *
417
     * The content is rendered using the registered meta tags, link tags, CSS/JS code blocks and files.
418
     *
419
     * @return string the rendered content
420
     */
421 11
    protected function renderHeadHtml(): string
422
    {
423 11
        $lines = [];
424 11
        if (!empty($this->metaTags)) {
425 1
            $lines[] = implode("\n", $this->metaTags);
426
        }
427
428 11
        if (!empty($this->linkTags)) {
429 1
            $lines[] = implode("\n", $this->linkTags);
430
        }
431 11
        if (!empty($this->cssFiles)) {
432 1
            $lines[] = implode("\n", $this->cssFiles);
433
        }
434 11
        if (!empty($this->css)) {
435 1
            $lines[] = implode("\n", $this->css);
436
        }
437 11
        if (!empty($this->jsFiles[self::POSITION_HEAD])) {
438 1
            $lines[] = implode("\n", $this->jsFiles[self::POSITION_HEAD]);
439
        }
440 11
        if (!empty($this->js[self::POSITION_HEAD])) {
441 1
            $lines[] = $this->generateJs($this->js[self::POSITION_HEAD]);
442
        }
443
444 11
        return empty($lines) ? '' : implode("\n", $lines);
445
    }
446
447
    /**
448
     * Renders the content to be inserted at the beginning of the body section.
449
     *
450
     * The content is rendered using the registered JS code blocks and files.
451
     *
452
     * @return string the rendered content
453
     */
454 11
    protected function renderBodyBeginHtml(): string
455
    {
456 11
        $lines = [];
457 11
        if (!empty($this->jsFiles[self::POSITION_BEGIN])) {
458 1
            $lines[] = implode("\n", $this->jsFiles[self::POSITION_BEGIN]);
459
        }
460 11
        if (!empty($this->js[self::POSITION_BEGIN])) {
461
            $lines[] = $this->generateJs($this->js[self::POSITION_BEGIN]);
462
        }
463
464 11
        return empty($lines) ? '' : implode("\n", $lines);
465
    }
466
467
    /**
468
     * Renders the content to be inserted at the end of the body section.
469
     *
470
     * The content is rendered using the registered JS code blocks and files.
471
     *
472
     * @param bool $ajaxMode whether the view is rendering in AJAX mode. If true, the JS scripts registered at
473
     * {@see POSITION_READY} and {@see POSITION_LOAD} positions will be rendered at the end of the view like normal
474
     * scripts.
475
     *
476
     * @return string the rendered content
477
     */
478 11
    protected function renderBodyEndHtml(bool $ajaxMode): string
479
    {
480 11
        $lines = [];
481
482 11
        if (!empty($this->jsFiles[self::POSITION_END])) {
483 1
            $lines[] = implode("\n", $this->jsFiles[self::POSITION_END]);
484
        }
485
486 11
        if ($ajaxMode) {
487 2
            $scripts = array_merge(
488 2
                $this->js[self::POSITION_END] ?? [],
489 2
                $this->js[self::POSITION_READY] ?? [],
490 2
                $this->js[self::POSITION_LOAD] ?? [],
491
            );
492 2
            if (!empty($scripts)) {
493 2
                $lines[] = $this->generateJs($scripts);
494
            }
495
        } else {
496 9
            if (!empty($this->js[self::POSITION_END])) {
497 2
                $lines[] = $this->generateJs($this->js[self::POSITION_END]);
498
            }
499 9
            if (!empty($this->js[self::POSITION_READY])) {
500
                $js = "document.addEventListener('DOMContentLoaded', function(event) {\n" .
501 1
                    $this->generateJsWithoutTag($this->js[self::POSITION_READY]) .
502 1
                    "\n});";
503 1
                $lines[] = Html::script($js)->render();
504
            }
505 9
            if (!empty($this->js[self::POSITION_LOAD])) {
506
                $js = "window.addEventListener('load', function (event) {\n" .
507
                    $this->generateJsWithoutTag($this->js[self::POSITION_LOAD]) .
508
                    "\n});";
509
                $lines[] = Html::script($js)->render();
510
            }
511
        }
512
513 11
        return empty($lines) ? '' : implode("\n", $lines);
514
    }
515
516
    /**
517
     * Get title in views.
518
     *
519
     * in Layout:
520
     *
521
     * ```php
522
     * <title><?= Html::encode($this->getTitle()) ?></title>
523
     * ```
524
     *
525
     * in Views:
526
     *
527
     * ```php
528
     * $this->setTitle('Web Application - Yii 3.0.');
529
     * ```
530
     *
531
     * @return string
532
     */
533
    public function getTitle(): string
534
    {
535
        return $this->title;
536
    }
537
538
    /**
539
     * It processes the CSS configuration generated by the asset manager and converts it into HTML code.
540
     *
541
     * @param array $cssFiles
542
     */
543
    public function setCssFiles(array $cssFiles): void
544
    {
545
        foreach ($cssFiles as $key => $value) {
546
            $this->registerCssFile(
547
                $cssFiles[$key]['url'],
548
                $cssFiles[$key]['attributes']
549
            );
550
        }
551
    }
552
553
    /**
554
     * It processes the JS configuration generated by the asset manager and converts it into HTML code.
555
     *
556
     * @param array $jsFiles
557
     */
558
    public function setJsFiles(array $jsFiles): void
559
    {
560
        foreach ($jsFiles as $key => $value) {
561
            $this->registerJsFile(
562
                $jsFiles[$key]['url'],
563
                $jsFiles[$key]['attributes']
564
            );
565
        }
566
    }
567
568
    /**
569
     * It processes the JS strings generated by the asset manager.
570
     *
571
     * @param array $jsStrings
572
     */
573
    public function setJsStrings(array $jsStrings): void
574
    {
575
        foreach ($jsStrings as $value) {
576
            $this->registerJs(
577
                $value['string'],
578
                $value['attributes']['position']
579
            );
580
        }
581
    }
582
583
    /**
584
     * It processes the JS variables generated by the asset manager and converts it into JS code.
585
     *
586
     * @param array $jsVar
587
     */
588
    public function setJsVar(array $jsVar): void
589
    {
590
        foreach ($jsVar as $key => $value) {
591
            $this->registerJsVar(
592
                (string)$key,
593
                $value['variables'],
594
                $value['attributes']['position']
595
            );
596
        }
597
    }
598
599
    /**
600
     * Set title in views.
601
     *
602
     * {@see getTitle()}
603
     *
604
     * @param string $value
605
     */
606
    public function setTitle(string $value): void
607
    {
608
        $this->title = $value;
609
    }
610
611
    /**
612
     * @param Script[]|string[] $items
613
     */
614 4
    private function generateJs(array $items): string
615
    {
616 4
        $lines = [];
617
618 4
        $js = [];
619 4
        foreach ($items as $item) {
620 4
            if ($item instanceof Script) {
621 3
                if ($js !== []) {
622 2
                    $lines[] = Html::script(implode("\n", $js))->render();
623 2
                    $js = [];
624
                }
625 3
                $lines[] = $item->render();
626
            } else {
627 3
                $js[] = $item;
628
            }
629
        }
630 4
        if ($js !== []) {
631 2
            $lines[] = Html::script(implode("\n", $js))->render();
632
        }
633
634 4
        return implode("\n", $lines);
635
    }
636
637
    /**
638
     * @param Script[]|string[] $items
639
     */
640 1
    private function generateJsWithoutTag(array $items): string
641
    {
642 1
        $js = [];
643 1
        foreach ($items as $item) {
644 1
            $js[] = $item instanceof Script ? $item->getContent() : $item;
645
        }
646 1
        return implode("\n", $js);
647
    }
648
}
649