Completed
Push — 2.1 ( 6b99e4...fa71f8 )
by Dmitry
15:50
created

View::getRequestedViewFile()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 2
eloc 2
nc 2
nop 0
crap 2
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 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 mixed 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::class],
64
     *     'twig' => ['__class' => \yii\twig\ViewRenderer::class],
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 DynamicContentAwareInterface[] a list of currently active dynamic content class instances.
90
     */
91
    private $_cacheStack = [];
92
    /**
93
     * @var array a list of placeholders for embedding dynamic contents.
94
     */
95
    private $_dynamicPlaceholders = [];
96
    /**
97
     * @var array the view files currently being rendered. There may be multiple view files being
98
     * rendered at a moment because one view may be rendered within another.
99
     */
100
    private $_viewFiles = [];
101
102
103
    /**
104
     * Initializes the view component.
105
     */
106 152
    public function init()
107
    {
108 152
        parent::init();
109 152
        if (is_array($this->theme)) {
110
            if (!isset($this->theme['__class'])) {
111
                $this->theme['__class'] = Theme::class;
112
            }
113
            $this->theme = Yii::createObject($this->theme);
114 152
        } elseif (is_string($this->theme)) {
115
            $this->theme = Yii::createObject($this->theme);
116
        }
117 152
    }
118
119
    /**
120
     * Renders a view.
121
     *
122
     * The view to be rendered can be specified in one of the following formats:
123
     *
124
     * - [path alias](guide:concept-aliases) (e.g. "@app/views/site/index");
125
     * - absolute path within application (e.g. "//site/index"): the view name starts with double slashes.
126
     *   The actual view file will be looked for under the [[Application::viewPath|view path]] of the application.
127
     * - absolute path within current module (e.g. "/site/index"): the view name starts with a single slash.
128
     *   The actual view file will be looked for under the [[Module::viewPath|view path]] of the [[Controller::module|current module]].
129
     * - relative view (e.g. "index"): the view name does not start with `@` or `/`. The corresponding view file will be
130
     *   looked for under the [[ViewContextInterface::getViewPath()|view path]] of the view `$context`.
131
     *   If `$context` is not given, it will be looked for under the directory containing the view currently
132
     *   being rendered (i.e., this happens when rendering a view within another view).
133
     *
134
     * @param string $view the view name.
135
     * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view file.
136
     * @param object $context the context to be assigned to the view and can later be accessed via [[context]]
137
     * in the view. If the context implements [[ViewContextInterface]], it may also be used to locate
138
     * the view file corresponding to a relative view name.
139
     * @return string the rendering result
140
     * @throws ViewNotFoundException if the view file does not exist.
141
     * @throws InvalidCallException if the view cannot be resolved.
142
     * @see renderFile()
143
     */
144 37
    public function render($view, $params = [], $context = null)
145
    {
146 37
        $viewFile = $this->findViewFile($view, $context);
147 37
        return $this->renderFile($viewFile, $params, $context);
0 ignored issues
show
Bug introduced by
It seems like $viewFile defined by $this->findViewFile($view, $context) on line 146 can also be of type boolean; however, yii\base\View::renderFile() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

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