Passed
Pull Request — master (#137)
by
unknown
03:24
created

WebView::setTitle()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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