Passed
Push — master ( 811ea8...c636a5 )
by Alexander
02:19
created

WebView::endPage()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 1

Importance

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