Passed
Push — master ( 9dbdd9...d5a428 )
by Alexander
04:15
created

framework/base/View.php (1 issue)

1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\base;
9
10
use Yii;
11
use yii\helpers\FileHelper;
12
use yii\widgets\Block;
13
use yii\widgets\ContentDecorator;
14
use yii\widgets\FragmentCache;
15
16
/**
17
 * View represents a view object in the MVC pattern.
18
 *
19
 * View provides a set of methods (e.g. [[render()]]) for rendering purpose.
20
 *
21
 * For more details and usage information on View, see the [guide article on views](guide:structure-views).
22
 *
23
 * @property-read string|bool $viewFile The view file currently being rendered. False if no view file is being
24
 * rendered. This property is read-only.
25
 *
26
 * @author Qiang Xue <[email protected]>
27
 * @since 2.0
28
 */
29
class View extends Component implements DynamicContentAwareInterface
30
{
31
    /**
32
     * @event Event an event that is triggered by [[beginPage()]].
33
     */
34
    const EVENT_BEGIN_PAGE = 'beginPage';
35
    /**
36
     * @event Event an event that is triggered by [[endPage()]].
37
     */
38
    const EVENT_END_PAGE = 'endPage';
39
    /**
40
     * @event ViewEvent an event that is triggered by [[renderFile()]] right before it renders a view file.
41
     */
42
    const EVENT_BEFORE_RENDER = 'beforeRender';
43
    /**
44
     * @event ViewEvent an event that is triggered by [[renderFile()]] right after it renders a view file.
45
     */
46
    const EVENT_AFTER_RENDER = 'afterRender';
47
48
    /**
49
     * @var ViewContextInterface the context under which the [[renderFile()]] method is being invoked.
50
     */
51
    public $context;
52
    /**
53
     * @var array custom parameters that are shared among view templates.
54
     */
55
    public $params = [];
56
    /**
57
     * @var array a list of available renderers indexed by their corresponding supported file extensions.
58
     * Each renderer may be a view renderer object or the configuration for creating the renderer object.
59
     * For example, the following configuration enables both Smarty and Twig view renderers:
60
     *
61
     * ```php
62
     * [
63
     *     'tpl' => ['class' => 'yii\smarty\ViewRenderer'],
64
     *     'twig' => ['class' => 'yii\twig\ViewRenderer'],
65
     * ]
66
     * ```
67
     *
68
     * If no renderer is available for the given view file, the view file will be treated as a normal PHP
69
     * and rendered via [[renderPhpFile()]].
70
     */
71
    public $renderers;
72
    /**
73
     * @var string the default view file extension. This will be appended to view file names if they don't have file extensions.
74
     */
75
    public $defaultExtension = 'php';
76
    /**
77
     * @var Theme|array|string the theme object or the configuration for creating the theme object.
78
     * If not set, it means theming is not enabled.
79
     */
80
    public $theme;
81
    /**
82
     * @var array a list of named output blocks. The keys are the block names and the values
83
     * are the corresponding block content. You can call [[beginBlock()]] and [[endBlock()]]
84
     * to capture small fragments of a view. They can be later accessed somewhere else
85
     * through this property.
86
     */
87
    public $blocks;
88
    /**
89
     * @var array|DynamicContentAwareInterface[] a list of currently active dynamic content class instances.
90
     * This property is used internally to implement the dynamic content caching feature. Do not modify it directly.
91
     * @internal
92
     * @deprecated Since 2.0.14. Do not use this property directly. Use methods [[getDynamicContents()]],
93
     * [[pushDynamicContent()]], [[popDynamicContent()]] instead.
94
     */
95
    public $cacheStack = [];
96
    /**
97
     * @var array a list of placeholders for embedding dynamic contents. This property
98
     * is used internally to implement the content caching feature. Do not modify it directly.
99
     * @internal
100
     * @deprecated Since 2.0.14. Do not use this property directly. Use methods [[getDynamicPlaceholders()]],
101
     * [[setDynamicPlaceholders()]], [[addDynamicPlaceholder()]] instead.
102
     */
103
    public $dynamicPlaceholders = [];
104
105
    /**
106
     * @var array the view files currently being rendered. There may be multiple view files being
107
     * rendered at a moment because one view may be rendered within another.
108
     */
109
    private $_viewFiles = [];
110
111
112
    /**
113
     * Initializes the view component.
114
     */
115 239
    public function init()
116
    {
117 239
        parent::init();
118 239
        if (is_array($this->theme)) {
119
            if (!isset($this->theme['class'])) {
120
                $this->theme['class'] = 'yii\base\Theme';
121
            }
122
            $this->theme = Yii::createObject($this->theme);
123 239
        } elseif (is_string($this->theme)) {
124
            $this->theme = Yii::createObject($this->theme);
125
        }
126 239
    }
127
128
    /**
129
     * Renders a view.
130
     *
131
     * The view to be rendered can be specified in one of the following formats:
132
     *
133
     * - [path alias](guide:concept-aliases) (e.g. "@app/views/site/index");
134
     * - absolute path within application (e.g. "//site/index"): the view name starts with double slashes.
135
     *   The actual view file will be looked for under the [[Application::viewPath|view path]] of the application.
136
     * - absolute path within current module (e.g. "/site/index"): the view name starts with a single slash.
137
     *   The actual view file will be looked for under the [[Module::viewPath|view path]] of the [[Controller::module|current module]].
138
     * - relative view (e.g. "index"): the view name does not start with `@` or `/`. The corresponding view file will be
139
     *   looked for under the [[ViewContextInterface::getViewPath()|view path]] of the view `$context`.
140
     *   If `$context` is not given, it will be looked for under the directory containing the view currently
141
     *   being rendered (i.e., this happens when rendering a view within another view).
142
     *
143
     * @param string $view the view name.
144
     * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view file.
145
     * @param object $context the context to be assigned to the view and can later be accessed via [[context]]
146
     * in the view. If the context implements [[ViewContextInterface]], it may also be used to locate
147
     * the view file corresponding to a relative view name.
148
     * @return string the rendering result
149
     * @throws ViewNotFoundException if the view file does not exist.
150
     * @throws InvalidCallException if the view cannot be resolved.
151
     * @see renderFile()
152
     */
153 113
    public function render($view, $params = [], $context = null)
154
    {
155 113
        $viewFile = $this->findViewFile($view, $context);
156 113
        return $this->renderFile($viewFile, $params, $context);
157
    }
158
159
    /**
160
     * Finds the view file based on the given view name.
161
     * @param string $view the view name or the [path alias](guide:concept-aliases) of the view file. Please refer to [[render()]]
162
     * on how to specify this parameter.
163
     * @param object $context the context to be assigned to the view and can later be accessed via [[context]]
164
     * in the view. If the context implements [[ViewContextInterface]], it may also be used to locate
165
     * the view file corresponding to a relative view name.
166
     * @return string the view file path. Note that the file may not exist.
167
     * @throws InvalidCallException if a relative view name is given while there is no active context to
168
     * determine the corresponding view file.
169
     */
170 113
    protected function findViewFile($view, $context = null)
171
    {
172 113
        if (strncmp($view, '@', 1) === 0) {
173
            // e.g. "@app/views/main"
174 28
            $file = Yii::getAlias($view);
175 86
        } elseif (strncmp($view, '//', 2) === 0) {
176
            // e.g. "//layouts/main"
177
            $file = Yii::$app->getViewPath() . DIRECTORY_SEPARATOR . ltrim($view, '/');
178 86
        } elseif (strncmp($view, '/', 1) === 0) {
179
            // e.g. "/site/index"
180
            if (Yii::$app->controller !== null) {
181
                $file = Yii::$app->controller->module->getViewPath() . DIRECTORY_SEPARATOR . ltrim($view, '/');
182
            } else {
183
                throw new InvalidCallException("Unable to locate view file for view '$view': no active controller.");
184
            }
185 86
        } elseif ($context instanceof ViewContextInterface) {
186 6
            $file = $context->getViewPath() . DIRECTORY_SEPARATOR . $view;
187 80
        } elseif (($currentViewFile = $this->getRequestedViewFile()) !== false) {
188 80
            $file = dirname($currentViewFile) . DIRECTORY_SEPARATOR . $view;
0 ignored issues
show
It seems like $currentViewFile can also be of type true; however, parameter $path of dirname() 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

188
            $file = dirname(/** @scrutinizer ignore-type */ $currentViewFile) . DIRECTORY_SEPARATOR . $view;
Loading history...
189
        } else {
190
            throw new InvalidCallException("Unable to resolve view file for view '$view': no active view context.");
191
        }
192
193 113
        if (pathinfo($file, PATHINFO_EXTENSION) !== '') {
194 26
            return $file;
195
        }
196 87
        $path = $file . '.' . $this->defaultExtension;
197 87
        if ($this->defaultExtension !== 'php' && !is_file($path)) {
198
            $path = $file . '.php';
199
        }
200
201 87
        return $path;
202
    }
203
204
    /**
205
     * Renders a view file.
206
     *
207
     * If [[theme]] is enabled (not null), it will try to render the themed version of the view file as long
208
     * as it is available.
209
     *
210
     * The method will call [[FileHelper::localize()]] to localize the view file.
211
     *
212
     * If [[renderers|renderer]] is enabled (not null), the method will use it to render the view file.
213
     * Otherwise, it will simply include the view file as a normal PHP file, capture its output and
214
     * return it as a string.
215
     *
216
     * @param string $viewFile the view file. This can be either an absolute file path or an alias of it.
217
     * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view file.
218
     * @param object $context the context that the view should use for rendering the view. If null,
219
     * existing [[context]] will be used.
220
     * @return string the rendering result
221
     * @throws ViewNotFoundException if the view file does not exist
222
     */
223 155
    public function renderFile($viewFile, $params = [], $context = null)
224
    {
225 155
        $viewFile = $requestedFile = Yii::getAlias($viewFile);
226
227 155
        if ($this->theme !== null) {
228 1
            $viewFile = $this->theme->applyTo($viewFile);
229
        }
230 155
        if (is_file($viewFile)) {
231 154
            $viewFile = FileHelper::localize($viewFile);
232
        } else {
233 2
            throw new ViewNotFoundException("The view file does not exist: $viewFile");
234
        }
235
236 154
        $oldContext = $this->context;
237 154
        if ($context !== null) {
238 101
            $this->context = $context;
239
        }
240 154
        $output = '';
241 154
        $this->_viewFiles[] = [
242 154
            'resolved' => $viewFile,
243 154
            'requested' => $requestedFile
244
        ];
245
246 154
        if ($this->beforeRender($viewFile, $params)) {
247 154
            Yii::debug("Rendering view file: $viewFile", __METHOD__);
248 154
            $ext = pathinfo($viewFile, PATHINFO_EXTENSION);
249 154
            if (isset($this->renderers[$ext])) {
250
                if (is_array($this->renderers[$ext]) || is_string($this->renderers[$ext])) {
251
                    $this->renderers[$ext] = Yii::createObject($this->renderers[$ext]);
252
                }
253
                /* @var $renderer ViewRenderer */
254
                $renderer = $this->renderers[$ext];
255
                $output = $renderer->render($this, $viewFile, $params);
256
            } else {
257 154
                $output = $this->renderPhpFile($viewFile, $params);
258
            }
259 154
            $this->afterRender($viewFile, $params, $output);
260
        }
261
262 154
        array_pop($this->_viewFiles);
263 154
        $this->context = $oldContext;
264
265 154
        return $output;
266
    }
267
268
    /**
269
     * @return string|bool the view file currently being rendered. False if no view file is being rendered.
270
     */
271
    public function getViewFile()
272
    {
273
        return empty($this->_viewFiles) ? false : end($this->_viewFiles)['resolved'];
274
    }
275
276
    /**
277
     * @return string|bool the requested view currently being rendered. False if no view file is being rendered.
278
     * @since 2.0.16
279
     */
280 80
    protected function getRequestedViewFile()
281
    {
282 80
        return empty($this->_viewFiles) ? false : end($this->_viewFiles)['requested'];
283
    }
284
285
    /**
286
     * This method is invoked right before [[renderFile()]] renders a view file.
287
     * The default implementation will trigger the [[EVENT_BEFORE_RENDER]] event.
288
     * If you override this method, make sure you call the parent implementation first.
289
     * @param string $viewFile the view file to be rendered.
290
     * @param array $params the parameter array passed to the [[render()]] method.
291
     * @return bool whether to continue rendering the view file.
292
     */
293 154
    public function beforeRender($viewFile, $params)
294
    {
295 154
        $event = new ViewEvent([
296 154
            'viewFile' => $viewFile,
297 154
            'params' => $params,
298
        ]);
299 154
        $this->trigger(self::EVENT_BEFORE_RENDER, $event);
300
301 154
        return $event->isValid;
302
    }
303
304
    /**
305
     * This method is invoked right after [[renderFile()]] renders a view file.
306
     * The default implementation will trigger the [[EVENT_AFTER_RENDER]] event.
307
     * If you override this method, make sure you call the parent implementation first.
308
     * @param string $viewFile the view file being rendered.
309
     * @param array $params the parameter array passed to the [[render()]] method.
310
     * @param string $output the rendering result of the view file. Updates to this parameter
311
     * will be passed back and returned by [[renderFile()]].
312
     */
313 154
    public function afterRender($viewFile, $params, &$output)
314
    {
315 154
        if ($this->hasEventHandlers(self::EVENT_AFTER_RENDER)) {
316
            $event = new ViewEvent([
317
                'viewFile' => $viewFile,
318
                'params' => $params,
319
                'output' => $output,
320
            ]);
321
            $this->trigger(self::EVENT_AFTER_RENDER, $event);
322
            $output = $event->output;
323
        }
324 154
    }
325
326
    /**
327
     * Renders a view file as a PHP script.
328
     *
329
     * This method treats the view file as a PHP script and includes the file.
330
     * It extracts the given parameters and makes them available in the view file.
331
     * The method captures the output of the included view file and returns it as a string.
332
     *
333
     * This method should mainly be called by view renderer or [[renderFile()]].
334
     *
335
     * @param string $_file_ the view file.
336
     * @param array $_params_ the parameters (name-value pairs) that will be extracted and made available in the view file.
337
     * @return string the rendering result
338
     * @throws \Exception
339
     * @throws \Throwable
340
     */
341 154
    public function renderPhpFile($_file_, $_params_ = [])
342
    {
343 154
        $_obInitialLevel_ = ob_get_level();
344 154
        ob_start();
345 154
        ob_implicit_flush(false);
346 154
        extract($_params_, EXTR_OVERWRITE);
347
        try {
348 154
            require $_file_;
349 154
            return ob_get_clean();
350 1
        } catch (\Exception $e) {
351 1
            while (ob_get_level() > $_obInitialLevel_) {
352 1
                if (!@ob_end_clean()) {
353
                    ob_clean();
354
                }
355
            }
356 1
            throw $e;
357
        } catch (\Throwable $e) {
358
            while (ob_get_level() > $_obInitialLevel_) {
359
                if (!@ob_end_clean()) {
360
                    ob_clean();
361
                }
362
            }
363
            throw $e;
364
        }
365
    }
366
367
    /**
368
     * Renders dynamic content returned by the given PHP statements.
369
     * This method is mainly used together with content caching (fragment caching and page caching)
370
     * when some portions of the content (called *dynamic content*) should not be cached.
371
     * The dynamic content must be returned by some PHP statements.
372
     * @param string $statements the PHP statements for generating the dynamic content.
373
     * @return string the placeholder of the dynamic content, or the dynamic content if there is no
374
     * active content cache currently.
375
     *
376
     * Note that most methods that indirectly modify layout such as registerJS() or registerJSFile() do not
377
     * work with dynamic rendering.
378
     *
379
     * @see https://github.com/yiisoft/yii2/issues/17673
380
     */
381 18
    public function renderDynamic($statements)
382
    {
383 18
        if (!empty($this->cacheStack)) {
384 16
            $n = count($this->dynamicPlaceholders);
385 16
            $placeholder = "<![CDATA[YII-DYNAMIC-$n]]>";
386 16
            $this->addDynamicPlaceholder($placeholder, $statements);
387
388 16
            return $placeholder;
389
        }
390
391 2
        return $this->evaluateDynamicContent($statements);
392
    }
393
394
    /**
395
     * {@inheritdoc}
396
     */
397
    public function getDynamicPlaceholders()
398
    {
399
        return $this->dynamicPlaceholders;
400
    }
401
402
    /**
403
     * {@inheritdoc}
404
     */
405
    public function setDynamicPlaceholders($placeholders)
406
    {
407
        $this->dynamicPlaceholders = $placeholders;
408
    }
409
410
    /**
411
     * {@inheritdoc}
412
     */
413 16
    public function addDynamicPlaceholder($placeholder, $statements)
414
    {
415 16
        foreach ($this->cacheStack as $cache) {
416 16
            if ($cache instanceof DynamicContentAwareInterface) {
417 16
                $cache->addDynamicPlaceholder($placeholder, $statements);
418
            } else {
419
                // TODO: Remove in 2.1
420 16
                $cache->dynamicPlaceholders[$placeholder] = $statements;
421
            }
422
        }
423 16
        $this->dynamicPlaceholders[$placeholder] = $statements;
424 16
}
425
426
    /**
427
     * Evaluates the given PHP statements.
428
     * This method is mainly used internally to implement dynamic content feature.
429
     * @param string $statements the PHP statements to be evaluated.
430
     * @return mixed the return value of the PHP statements.
431
     */
432 18
    public function evaluateDynamicContent($statements)
433
    {
434 18
        return eval($statements);
435
    }
436
437
    /**
438
     * Returns a list of currently active dynamic content class instances.
439
     * @return DynamicContentAwareInterface[] class instances supporting dynamic contents.
440
     * @since 2.0.14
441
     */
442 16
    public function getDynamicContents()
443
    {
444 16
        return $this->cacheStack;
445
    }
446
447
    /**
448
     * Adds a class instance supporting dynamic contents to the end of a list of currently active
449
     * dynamic content class instances.
450
     * @param DynamicContentAwareInterface $instance class instance supporting dynamic contents.
451
     * @since 2.0.14
452
     */
453 21
    public function pushDynamicContent(DynamicContentAwareInterface $instance)
454
    {
455 21
        $this->cacheStack[] = $instance;
456 21
    }
457
458
    /**
459
     * Removes a last class instance supporting dynamic contents from a list of currently active
460
     * dynamic content class instances.
461
     * @since 2.0.14
462
     */
463 21
    public function popDynamicContent()
464
    {
465 21
        array_pop($this->cacheStack);
466 21
    }
467
468
    /**
469
     * Begins recording a block.
470
     *
471
     * This method is a shortcut to beginning [[Block]].
472
     * @param string $id the block ID.
473
     * @param bool $renderInPlace whether to render the block content in place.
474
     * Defaults to false, meaning the captured block will not be displayed.
475
     * @return Block the Block widget instance
476
     */
477
    public function beginBlock($id, $renderInPlace = false)
478
    {
479
        return Block::begin([
480
            'id' => $id,
481
            'renderInPlace' => $renderInPlace,
482
            'view' => $this,
483
        ]);
484
    }
485
486
    /**
487
     * Ends recording a block.
488
     */
489
    public function endBlock()
490
    {
491
        Block::end();
492
    }
493
494
    /**
495
     * Begins the rendering of content that is to be decorated by the specified view.
496
     *
497
     * This method can be used to implement nested layout. For example, a layout can be embedded
498
     * in another layout file specified as '@app/views/layouts/base.php' like the following:
499
     *
500
     * ```php
501
     * <?php $this->beginContent('@app/views/layouts/base.php'); ?>
502
     * //...layout content here...
503
     * <?php $this->endContent(); ?>
504
     * ```
505
     *
506
     * @param string $viewFile the view file that will be used to decorate the content enclosed by this widget.
507
     * This can be specified as either the view file path or [path alias](guide:concept-aliases).
508
     * @param array $params the variables (name => value) to be extracted and made available in the decorative view.
509
     * @return ContentDecorator the ContentDecorator widget instance
510
     * @see ContentDecorator
511
     */
512
    public function beginContent($viewFile, $params = [])
513
    {
514
        return ContentDecorator::begin([
515
            'viewFile' => $viewFile,
516
            'params' => $params,
517
            'view' => $this,
518
        ]);
519
    }
520
521
    /**
522
     * Ends the rendering of content.
523
     */
524
    public function endContent()
525
    {
526
        ContentDecorator::end();
527
    }
528
529
    /**
530
     * Begins fragment caching.
531
     *
532
     * This method will display cached content if it is available.
533
     * If not, it will start caching and would expect an [[endCache()]]
534
     * call to end the cache and save the content into cache.
535
     * A typical usage of fragment caching is as follows,
536
     *
537
     * ```php
538
     * if ($this->beginCache($id)) {
539
     *     // ...generate content here
540
     *     $this->endCache();
541
     * }
542
     * ```
543
     *
544
     * @param string $id a unique ID identifying the fragment to be cached.
545
     * @param array $properties initial property values for [[FragmentCache]]
546
     * @return bool whether you should generate the content for caching.
547
     * False if the cached version is available.
548
     */
549 10
    public function beginCache($id, $properties = [])
550
    {
551 10
        $properties['id'] = $id;
552 10
        $properties['view'] = $this;
553
        /* @var $cache FragmentCache */
554 10
        $cache = FragmentCache::begin($properties);
555 10
        if ($cache->getCachedContent() !== false) {
556 7
            $this->endCache();
557
558 7
            return false;
559
        }
560
561 10
        return true;
562
    }
563
564
    /**
565
     * Ends fragment caching.
566
     */
567 10
    public function endCache()
568
    {
569 10
        FragmentCache::end();
570 10
    }
571
572
    /**
573
     * Marks the beginning of a page.
574
     */
575 55
    public function beginPage()
576
    {
577 55
        ob_start();
578 55
        ob_implicit_flush(false);
579
580 55
        $this->trigger(self::EVENT_BEGIN_PAGE);
581 55
    }
582
583
    /**
584
     * Marks the ending of a page.
585
     */
586
    public function endPage()
587
    {
588
        $this->trigger(self::EVENT_END_PAGE);
589
        ob_end_flush();
590
    }
591
}
592