Completed
Push — master ( 67caf0...bdc372 )
by Dmitry
13:07 queued 04:28
created

framework/base/View.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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'],
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 149
    public function init()
116
    {
117 149
        parent::init();
118 149
        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 149
        } elseif (is_string($this->theme)) {
124
            $this->theme = Yii::createObject($this->theme);
125
        }
126 149
    }
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 35
    public function render($view, $params = [], $context = null)
154
    {
155 35
        $viewFile = $this->findViewFile($view, $context);
156 35
        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 35
    protected function findViewFile($view, $context = null)
171
    {
172 35
        if (strncmp($view, '@', 1) === 0) {
173
            // e.g. "@app/views/main"
174 24
            $file = Yii::getAlias($view);
175 11
        } elseif (strncmp($view, '//', 2) === 0) {
176
            // e.g. "//layouts/main"
177
            $file = Yii::$app->getViewPath() . DIRECTORY_SEPARATOR . ltrim($view, '/');
178 11
        } 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 11
        } elseif ($context instanceof ViewContextInterface) {
186 6
            $file = $context->getViewPath() . DIRECTORY_SEPARATOR . $view;
187 5
        } elseif (($currentViewFile = $this->getViewFile()) !== false) {
188 5
            $file = dirname($currentViewFile) . DIRECTORY_SEPARATOR . $view;
189
        } else {
190
            throw new InvalidCallException("Unable to resolve view file for view '$view': no active view context.");
191
        }
192
193 35
        if (pathinfo($file, PATHINFO_EXTENSION) !== '') {
194 23
            return $file;
195
        }
196 12
        $path = $file . '.' . $this->defaultExtension;
197 12
        if ($this->defaultExtension !== 'php' && !is_file($path)) {
198
            $path = $file . '.php';
199
        }
200
201 12
        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 75
    public function renderFile($viewFile, $params = [], $context = null)
224
    {
225 75
        $viewFile = Yii::getAlias($viewFile);
226
227 75
        if ($this->theme !== null) {
228
            $viewFile = $this->theme->applyTo($viewFile);
229
        }
230 75
        if (is_file($viewFile)) {
231 74
            $viewFile = FileHelper::localize($viewFile);
232
        } else {
233 2
            throw new ViewNotFoundException("The view file does not exist: $viewFile");
234
        }
235
236 74
        $oldContext = $this->context;
237 74
        if ($context !== null) {
238 25
            $this->context = $context;
239
        }
240 74
        $output = '';
241 74
        $this->_viewFiles[] = $viewFile;
242
243 74
        if ($this->beforeRender($viewFile, $params)) {
244 74
            Yii::debug("Rendering view file: $viewFile", __METHOD__);
245 74
            $ext = pathinfo($viewFile, PATHINFO_EXTENSION);
246 74
            if (isset($this->renderers[$ext])) {
247
                if (is_array($this->renderers[$ext]) || is_string($this->renderers[$ext])) {
248
                    $this->renderers[$ext] = Yii::createObject($this->renderers[$ext]);
249
                }
250
                /* @var $renderer ViewRenderer */
251
                $renderer = $this->renderers[$ext];
252
                $output = $renderer->render($this, $viewFile, $params);
253
            } else {
254 74
                $output = $this->renderPhpFile($viewFile, $params);
255
            }
256 74
            $this->afterRender($viewFile, $params, $output);
257
        }
258
259 74
        array_pop($this->_viewFiles);
260 74
        $this->context = $oldContext;
261
262 74
        return $output;
263
    }
264
265
    /**
266
     * @return string|bool the view file currently being rendered. False if no view file is being rendered.
267
     */
268 5
    public function getViewFile()
269
    {
270 5
        return end($this->_viewFiles);
271
    }
272
273
    /**
274
     * This method is invoked right before [[renderFile()]] renders a view file.
275
     * The default implementation will trigger the [[EVENT_BEFORE_RENDER]] event.
276
     * If you override this method, make sure you call the parent implementation first.
277
     * @param string $viewFile the view file to be rendered.
278
     * @param array $params the parameter array passed to the [[render()]] method.
279
     * @return bool whether to continue rendering the view file.
280
     */
281 74
    public function beforeRender($viewFile, $params)
282
    {
283 74
        $event = new ViewEvent([
284 74
            'viewFile' => $viewFile,
285 74
            'params' => $params,
286
        ]);
287 74
        $this->trigger(self::EVENT_BEFORE_RENDER, $event);
288
289 74
        return $event->isValid;
290
    }
291
292
    /**
293
     * This method is invoked right after [[renderFile()]] renders a view file.
294
     * The default implementation will trigger the [[EVENT_AFTER_RENDER]] event.
295
     * If you override this method, make sure you call the parent implementation first.
296
     * @param string $viewFile the view file being rendered.
297
     * @param array $params the parameter array passed to the [[render()]] method.
298
     * @param string $output the rendering result of the view file. Updates to this parameter
299
     * will be passed back and returned by [[renderFile()]].
300
     */
301 74
    public function afterRender($viewFile, $params, &$output)
302
    {
303 74
        if ($this->hasEventHandlers(self::EVENT_AFTER_RENDER)) {
304
            $event = new ViewEvent([
305
                'viewFile' => $viewFile,
306
                'params' => $params,
307
                'output' => $output,
308
            ]);
309
            $this->trigger(self::EVENT_AFTER_RENDER, $event);
310
            $output = $event->output;
311
        }
312 74
    }
313
314
    /**
315
     * Renders a view file as a PHP script.
316
     *
317
     * This method treats the view file as a PHP script and includes the file.
318
     * It extracts the given parameters and makes them available in the view file.
319
     * The method captures the output of the included view file and returns it as a string.
320
     *
321
     * This method should mainly be called by view renderer or [[renderFile()]].
322
     *
323
     * @param string $_file_ the view file.
324
     * @param array $_params_ the parameters (name-value pairs) that will be extracted and made available in the view file.
325
     * @return string the rendering result
326
     * @throws \Exception
327
     * @throws \Throwable
328
     */
329 74
    public function renderPhpFile($_file_, $_params_ = [])
330
    {
331 74
        $_obInitialLevel_ = ob_get_level();
332 74
        ob_start();
333 74
        ob_implicit_flush(false);
334 74
        extract($_params_, EXTR_OVERWRITE);
335
        try {
336 74
            require $_file_;
337 74
            return ob_get_clean();
338 1
        } catch (\Exception $e) {
339 1
            while (ob_get_level() > $_obInitialLevel_) {
340 1
                if (!@ob_end_clean()) {
341
                    ob_clean();
342
                }
343
            }
344 1
            throw $e;
345
        } catch (\Throwable $e) {
0 ignored issues
show
The class Throwable does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
346
            while (ob_get_level() > $_obInitialLevel_) {
347
                if (!@ob_end_clean()) {
348
                    ob_clean();
349
                }
350
            }
351
            throw $e;
352
        }
353
    }
354
355
    /**
356
     * Renders dynamic content returned by the given PHP statements.
357
     * This method is mainly used together with content caching (fragment caching and page caching)
358
     * when some portions of the content (called *dynamic content*) should not be cached.
359
     * The dynamic content must be returned by some PHP statements.
360
     * @param string $statements the PHP statements for generating the dynamic content.
361
     * @return string the placeholder of the dynamic content, or the dynamic content if there is no
362
     * active content cache currently.
363
     */
364 18
    public function renderDynamic($statements)
365
    {
366 18
        if (!empty($this->cacheStack)) {
367 16
            $n = count($this->dynamicPlaceholders);
368 16
            $placeholder = "<![CDATA[YII-DYNAMIC-$n]]>";
369 16
            $this->addDynamicPlaceholder($placeholder, $statements);
370
371 16
            return $placeholder;
372
        }
373
374 2
        return $this->evaluateDynamicContent($statements);
375
    }
376
377
    /**
378
     * {@inheritdoc}
379
     */
380
    public function getDynamicPlaceholders()
381
    {
382
        return $this->dynamicPlaceholders;
383
    }
384
385
    /**
386
     * {@inheritdoc}
387
     */
388
    public function setDynamicPlaceholders($placeholders)
389
    {
390
        $this->dynamicPlaceholders = $placeholders;
391
    }
392
393
    /**
394
     * {@inheritdoc}
395
     */
396 16
    public function addDynamicPlaceholder($placeholder, $statements)
397
    {
398 16
        foreach ($this->cacheStack as $cache) {
399 16
            if ($cache instanceof DynamicContentAwareInterface) {
400 16
                $cache->addDynamicPlaceholder($placeholder, $statements);
401
            } else {
402
                // To be removed in 2.1
403 16
                $cache->dynamicPlaceholders[$placeholder] = $statements;
404
            }
405
        }
406 16
        $this->dynamicPlaceholders[$placeholder] = $statements;
407 16
}
408
409
    /**
410
     * Evaluates the given PHP statements.
411
     * This method is mainly used internally to implement dynamic content feature.
412
     * @param string $statements the PHP statements to be evaluated.
413
     * @return mixed the return value of the PHP statements.
414
     */
415 18
    public function evaluateDynamicContent($statements)
416
    {
417 18
        return eval($statements);
418
    }
419
420
    /**
421
     * Returns a list of currently active dynamic content class instances.
422
     * @return DynamicContentAwareInterface[] class instances supporting dynamic contents.
423
     * @since 2.0.14
424
     */
425 16
    public function getDynamicContents()
426
    {
427 16
        return $this->cacheStack;
428
    }
429
430
    /**
431
     * Adds a class instance supporting dynamic contents to the end of a list of currently active
432
     * dynamic content class instances.
433
     * @param DynamicContentAwareInterface $instance class instance supporting dynamic contents.
434
     * @since 2.0.14
435
     */
436 21
    public function pushDynamicContent(DynamicContentAwareInterface $instance)
437
    {
438 21
        $this->cacheStack[] = $instance;
439 21
    }
440
441
    /**
442
     * Removes a last class instance supporting dynamic contents from a list of currently active
443
     * dynamic content class instances.
444
     * @since 2.0.14
445
     */
446 21
    public function popDynamicContent()
447
    {
448 21
        array_pop($this->cacheStack);
449 21
    }
450
451
    /**
452
     * Begins recording a block.
453
     *
454
     * This method is a shortcut to beginning [[Block]].
455
     * @param string $id the block ID.
456
     * @param bool $renderInPlace whether to render the block content in place.
457
     * Defaults to false, meaning the captured block will not be displayed.
458
     * @return Block the Block widget instance
459
     */
460
    public function beginBlock($id, $renderInPlace = false)
461
    {
462
        return Block::begin([
463
            'id' => $id,
464
            'renderInPlace' => $renderInPlace,
465
            'view' => $this,
466
        ]);
467
    }
468
469
    /**
470
     * Ends recording a block.
471
     */
472
    public function endBlock()
473
    {
474
        Block::end();
475
    }
476
477
    /**
478
     * Begins the rendering of content that is to be decorated by the specified view.
479
     *
480
     * This method can be used to implement nested layout. For example, a layout can be embedded
481
     * in another layout file specified as '@app/views/layouts/base.php' like the following:
482
     *
483
     * ```php
484
     * <?php $this->beginContent('@app/views/layouts/base.php'); ?>
485
     * //...layout content here...
486
     * <?php $this->endContent(); ?>
487
     * ```
488
     *
489
     * @param string $viewFile the view file that will be used to decorate the content enclosed by this widget.
490
     * This can be specified as either the view file path or [path alias](guide:concept-aliases).
491
     * @param array $params the variables (name => value) to be extracted and made available in the decorative view.
492
     * @return ContentDecorator the ContentDecorator widget instance
493
     * @see ContentDecorator
494
     */
495
    public function beginContent($viewFile, $params = [])
496
    {
497
        return ContentDecorator::begin([
498
            'viewFile' => $viewFile,
499
            'params' => $params,
500
            'view' => $this,
501
        ]);
502
    }
503
504
    /**
505
     * Ends the rendering of content.
506
     */
507
    public function endContent()
508
    {
509
        ContentDecorator::end();
510
    }
511
512
    /**
513
     * Begins fragment caching.
514
     *
515
     * This method will display cached content if it is available.
516
     * If not, it will start caching and would expect an [[endCache()]]
517
     * call to end the cache and save the content into cache.
518
     * A typical usage of fragment caching is as follows,
519
     *
520
     * ```php
521
     * if ($this->beginCache($id)) {
522
     *     // ...generate content here
523
     *     $this->endCache();
524
     * }
525
     * ```
526
     *
527
     * @param string $id a unique ID identifying the fragment to be cached.
528
     * @param array $properties initial property values for [[FragmentCache]]
529
     * @return bool whether you should generate the content for caching.
530
     * False if the cached version is available.
531
     */
532 10
    public function beginCache($id, $properties = [])
533
    {
534 10
        $properties['id'] = $id;
535 10
        $properties['view'] = $this;
536
        /* @var $cache FragmentCache */
537 10
        $cache = FragmentCache::begin($properties);
538 10
        if ($cache->getCachedContent() !== false) {
539 7
            $this->endCache();
540
541 7
            return false;
542
        }
543
544 10
        return true;
545
    }
546
547
    /**
548
     * Ends fragment caching.
549
     */
550 10
    public function endCache()
551
    {
552 10
        FragmentCache::end();
553 10
    }
554
555
    /**
556
     * Marks the beginning of a page.
557
     */
558 50
    public function beginPage()
559
    {
560 50
        ob_start();
561 50
        ob_implicit_flush(false);
562
563 50
        $this->trigger(self::EVENT_BEGIN_PAGE);
564 50
    }
565
566
    /**
567
     * Marks the ending of a page.
568
     */
569
    public function endPage()
570
    {
571
        $this->trigger(self::EVENT_END_PAGE);
572
        ob_end_flush();
573
    }
574
}
575