Passed
Pull Request — master (#77)
by
unknown
01:40
created

WebView::registerJsVar()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 3
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]]>';
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->getBeginPageIsCalled()) {
170 1
            throw new \LogicException('Need to call beginPage() before endPage().');
171
        }
172 3
        $this->eventDispatcher->dispatch(new PageEnd($this->getViewFile()));
0 ignored issues
show
Bug introduced by
It seems like $this->getViewFile() can also be of type null; 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

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