Passed
Pull Request — master (#75)
by
unknown
02:11
created

WebView::head()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
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-%s]]>';
69
70
    /**
71
     * This is internally used as the placeholder for receiving the content registered for the beginning of the body
72
     * section.
73
     */
74
    private const PLACEHOLDER_BODY_BEGIN = '<![CDATA[YII-BLOCK-BODY-BEGIN-%s]]>';
75
76
    /**
77
     * This is internally used as the placeholder for receiving the content registered for the end of the body section.
78
     */
79
    private const PLACEHOLDER_BODY_END = '<![CDATA[YII-BLOCK-BODY-END-%s]]>';
80
81
    /**
82
     * @var string the page title
83
     */
84
    private string $title;
85
86
    /**
87
     * @var array the registered meta tags.
88
     *
89
     * {@see registerMetaTag()}
90
     */
91
    private array $metaTags = [];
92
93
    /**
94
     * @var array the registered link tags.
95
     *
96
     * {@see registerLinkTag()}
97
     */
98
    private array $linkTags = [];
99
100
    /**
101
     * @var array the registered CSS code blocks.
102
     *
103
     * {@see registerCss()}
104
     */
105
    private array $css = [];
106
107
    /**
108
     * @var array the registered CSS files.
109
     *
110
     * {@see registerCssFile()}
111
     */
112
    private array $cssFiles = [];
113
114
    /**
115
     * @var array the registered JS code blocks
116
     *
117
     * {@see registerJs()}
118
     */
119
    private array $js = [];
120
121
    /**
122
     * @var array the registered JS files.
123
     *
124
     * {@see registerJsFile()}
125
     */
126
    private array $jsFiles = [];
127
128
    /**
129
     * Marks the position of an HTML head section.
130
     */
131 4
    public function head(): void
132
    {
133 4
        echo sprintf(self::PLACEHOLDER_HEAD, $this->getPlaceholderSignature());
134
    }
135
136
    /**
137
     * Marks the beginning of an HTML body section.
138
     */
139 4
    public function beginBody(): void
140
    {
141 4
        echo sprintf(self::PLACEHOLDER_BODY_BEGIN, $this->getPlaceholderSignature());
142 4
        $this->eventDispatcher->dispatch(new BodyBegin($this->getViewFile()));
0 ignored issues
show
Bug introduced by
It seems like $this->getViewFile() can also be of type boolean; however, parameter $file of Yiisoft\View\Event\BodyBegin::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

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

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

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

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

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