Passed
Pull Request — master (#77)
by
unknown
02:08
created

WebView::renderHeadHtml()   B

Complexity

Conditions 8
Paths 128

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 8.512

Importance

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