Completed
Push — 2.1 ( f53151...0babc4 )
by Alexander
11:44
created

View   B

Complexity

Total Complexity 51

Size/Duplication

Total Lines 541
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 12

Test Coverage

Coverage 70.2%

Importance

Changes 0
Metric Value
wmc 51
lcom 2
cbo 12
dl 0
loc 541
ccs 106
cts 151
cp 0.702
rs 8.3206
c 0
b 0
f 0

24 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 12 4
A render() 0 5 1
D findViewFile() 0 33 10
C renderFile() 0 41 8
A getViewFile() 0 4 1
A beforeRender() 0 10 1
A afterRender() 0 12 2
A renderPhpFile() 0 18 4
A renderDynamic() 0 16 3
A getDynamicPlaceholders() 0 4 1
A setDynamicPlaceholders() 0 4 1
A addDynamicPlaceholder() 0 8 2
A evaluateDynamicContent() 0 4 1
A getDynamicContents() 0 4 1
A pushDynamicContent() 0 4 1
A popDynamicContent() 0 4 1
A beginBlock() 0 8 1
A endBlock() 0 4 1
A beginContent() 0 8 1
A endContent() 0 4 1
A beginCache() 0 14 2
A endCache() 0 4 1
A beginPage() 0 7 1
A endPage() 0 5 1

How to fix   Complexity   

Complex Class

Complex classes like View often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use View, and based on these observations, apply Extract Interface, too.

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