Passed
Pull Request — master (#99)
by
unknown
14:25
created

WebView::renderHeadHtml()   B

Complexity

Conditions 8
Paths 128

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 8.125

Importance

Changes 0
Metric Value
eloc 14
c 0
b 0
f 0
dl 0
loc 24
ccs 7
cts 8
cp 0.875
rs 8.2111
cc 8
nc 128
nop 0
crap 8.125
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
use Yiisoft\View\Exception\ContentCantBeFetched;
13
use Yiisoft\View\Exception\ViewNotFoundException;
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
class WebView extends View
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
     *
119
     * {@see registerJs()}
120
     */
121
    private array $js = [];
122
123
    /**
124
     * @var array the registered JS files.
125
     *
126
     * {@see registerJsFile()}
127
     */
128
    private array $jsFiles = [];
129
130
    /**
131 4
     * Marks the position of an HTML head section.
132
     */
133 4
    public function head(): void
134 4
    {
135
        echo sprintf(self::PLACEHOLDER_HEAD, $this->getPlaceholderSignature());
136
    }
137
138
    /**
139 4
     * Marks the beginning of an HTML body section.
140
     */
141 4
    public function beginBody(): void
142 4
    {
143 4
        if (is_string($viewFile = $this->getViewFile())) {
144
            echo sprintf(self::PLACEHOLDER_BODY_BEGIN, $this->getPlaceholderSignature());
145
            $this->eventDispatcher->dispatch(new BodyBegin($viewFile));
146
        }
147
    }
148 4
149
    /**
150 4
     * Marks the ending of an HTML body section.
151 4
     */
152 4
    public function endBody(): void
153
    {
154
        if (is_string($viewFile = $this->getViewFile())) {
155
            $this->eventDispatcher->dispatch(new BodyEnd($viewFile));
156
            echo sprintf(self::PLACEHOLDER_BODY_END, $this->getPlaceholderSignature());
157
        }
158
    }
159
160
    /**
161 4
     * Marks the ending of an HTML page.
162
     *
163 4
     * @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 4
     * normal scripts.
166
     */
167 4
    public function endPage($ajaxMode = false): void
168 4
    {
169 4
        if (is_string($viewFile = $this->getViewFile())) {
170 4
            $this->eventDispatcher->dispatch(new PageEnd($viewFile));
171
172
            $content = ob_get_clean();
173 4
174 4
            if (is_string($content)) {
0 ignored issues
show
introduced by
The condition is_string($content) is always true.
Loading history...
175
                echo strtr($content, [
176
                    sprintf(self::PLACEHOLDER_HEAD, $this->getPlaceholderSignature()) => $this->renderHeadHtml(),
177
                    sprintf(self::PLACEHOLDER_BODY_BEGIN, $this->getPlaceholderSignature()) => $this->renderBodyBeginHtml(),
178
                    sprintf(self::PLACEHOLDER_BODY_END, $this->getPlaceholderSignature()) => $this->renderBodyEndHtml($ajaxMode),
179
                ]);
180
            }
181
182
            $this->clear();
183
        }
184
    }
185
186
    /**
187
     * Renders a view in response to an AJAX request.
188
     *
189
     * This method is similar to {@see render()} except that it will surround the view being rendered with the calls of
190
     * {@see beginPage()}, {@see head()}, {@see beginBody()}, {@see endBody()} and {@see endPage()}. By doing so, the
191
     * method is able to inject into the rendering result with JS/CSS scripts and files that are registered with the
192
     * view.
193
     *
194
     * @param string $view the view name. Please refer to {@see render()} on how to specify this parameter.
195
     * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view
196
     * file.
197
     * @param ViewContextInterface|null $context the context that the view should use for rendering the view. If null,
198
     * existing {@see context} will be used.
199
     *
200
     * @return string the rendering result
201
     * @throws ContentCantBeFetched
202
     * @throws ViewNotFoundException|\Throwable
203
     *
204
     * {@see render()}
205
     */
206
    public function renderAjax(string $view, array $params = [], ?ViewContextInterface $context = null): string
207
    {
208
        $viewFile = $this->findTemplateFile($view, $context);
209
210
        ob_start();
211
        PHP_VERSION_ID >= 80000 ? ob_implicit_flush(false) : ob_implicit_flush(0);
0 ignored issues
show
Bug introduced by
false of type false is incompatible with the type integer expected by parameter $flag of ob_implicit_flush(). ( Ignorable by Annotation )

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

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