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 |
||
29 | class View extends Component |
||
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 a list of currently active fragment cache widgets. This property |
||
90 | * is used internally to implement the content caching feature. Do not modify it directly. |
||
91 | * @internal |
||
92 | */ |
||
93 | public $cacheStack = []; |
||
94 | /** |
||
95 | * @var array a list of placeholders for embedding dynamic contents. This property |
||
96 | * is used internally to implement the content caching feature. Do not modify it directly. |
||
97 | * @internal |
||
98 | */ |
||
99 | public $dynamicPlaceholders = []; |
||
100 | |||
101 | /** |
||
102 | * @var array the view files currently being rendered. There may be multiple view files being |
||
103 | * rendered at a moment because one view may be rendered within another. |
||
104 | */ |
||
105 | private $_viewFiles = []; |
||
106 | |||
107 | |||
108 | /** |
||
109 | * Initializes the view component. |
||
110 | */ |
||
111 | 119 | public function init() |
|
112 | { |
||
113 | 119 | parent::init(); |
|
114 | 119 | if (is_array($this->theme)) { |
|
115 | if (!isset($this->theme['class'])) { |
||
116 | $this->theme['class'] = 'yii\base\Theme'; |
||
117 | } |
||
118 | $this->theme = Yii::createObject($this->theme); |
||
119 | 119 | } elseif (is_string($this->theme)) { |
|
120 | $this->theme = Yii::createObject($this->theme); |
||
121 | } |
||
122 | 119 | } |
|
123 | |||
124 | /** |
||
125 | * Renders a view. |
||
126 | * |
||
127 | * The view to be rendered can be specified in one of the following formats: |
||
128 | * |
||
129 | * - path alias (e.g. "@app/views/site/index"); |
||
130 | * - absolute path within application (e.g. "//site/index"): the view name starts with double slashes. |
||
131 | * The actual view file will be looked for under the [[Application::viewPath|view path]] of the application. |
||
132 | * - absolute path within current module (e.g. "/site/index"): the view name starts with a single slash. |
||
133 | * The actual view file will be looked for under the [[Module::viewPath|view path]] of the [[Controller::module|current module]]. |
||
134 | * - relative view (e.g. "index"): the view name does not start with `@` or `/`. The corresponding view file will be |
||
135 | * looked for under the [[ViewContextInterface::getViewPath()|view path]] of the view `$context`. |
||
136 | * If `$context` is not given, it will be looked for under the directory containing the view currently |
||
137 | * being rendered (i.e., this happens when rendering a view within another view). |
||
138 | * |
||
139 | * @param string $view the view name. |
||
140 | * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view file. |
||
141 | * @param object $context the context to be assigned to the view and can later be accessed via [[context]] |
||
142 | * in the view. If the context implements [[ViewContextInterface]], it may also be used to locate |
||
143 | * the view file corresponding to a relative view name. |
||
144 | * @return string the rendering result |
||
145 | * @throws ViewNotFoundException if the view file does not exist. |
||
146 | * @throws InvalidCallException if the view cannot be resolved. |
||
147 | * @see renderFile() |
||
148 | */ |
||
149 | 26 | public function render($view, $params = [], $context = null) |
|
150 | { |
||
151 | 26 | $viewFile = $this->findViewFile($view, $context); |
|
152 | 26 | return $this->renderFile($viewFile, $params, $context); |
|
|
|||
153 | } |
||
154 | |||
155 | /** |
||
156 | * Finds the view file based on the given view name. |
||
157 | * @param string $view the view name or the path alias of the view file. Please refer to [[render()]] |
||
158 | * on how to specify this parameter. |
||
159 | * @param object $context the context to be assigned to the view and can later be accessed via [[context]] |
||
160 | * in the view. If the context implements [[ViewContextInterface]], it may also be used to locate |
||
161 | * the view file corresponding to a relative view name. |
||
162 | * @return string the view file path. Note that the file may not exist. |
||
163 | * @throws InvalidCallException if a relative view name is given while there is no active context to |
||
164 | * determine the corresponding view file. |
||
165 | */ |
||
166 | 26 | protected function findViewFile($view, $context = null) |
|
167 | { |
||
168 | 26 | if (strncmp($view, '@', 1) === 0) { |
|
169 | // e.g. "@app/views/main" |
||
170 | 16 | $file = Yii::getAlias($view); |
|
171 | 26 | } elseif (strncmp($view, '//', 2) === 0) { |
|
172 | // e.g. "//layouts/main" |
||
173 | $file = Yii::$app->getViewPath() . DIRECTORY_SEPARATOR . ltrim($view, '/'); |
||
174 | 10 | } elseif (strncmp($view, '/', 1) === 0) { |
|
175 | // e.g. "/site/index" |
||
176 | if (Yii::$app->controller !== null) { |
||
177 | $file = Yii::$app->controller->module->getViewPath() . DIRECTORY_SEPARATOR . ltrim($view, '/'); |
||
178 | } else { |
||
179 | throw new InvalidCallException("Unable to locate view file for view '$view': no active controller."); |
||
180 | } |
||
181 | 10 | } elseif ($context instanceof ViewContextInterface) { |
|
182 | 5 | $file = $context->getViewPath() . DIRECTORY_SEPARATOR . $view; |
|
183 | 10 | } elseif (($currentViewFile = $this->getViewFile()) !== false) { |
|
184 | 5 | $file = dirname($currentViewFile) . DIRECTORY_SEPARATOR . $view; |
|
185 | 5 | } else { |
|
186 | throw new InvalidCallException("Unable to resolve view file for view '$view': no active view context."); |
||
187 | } |
||
188 | |||
189 | 26 | if (pathinfo($file, PATHINFO_EXTENSION) !== '') { |
|
190 | 15 | return $file; |
|
191 | } |
||
192 | 11 | $path = $file . '.' . $this->defaultExtension; |
|
193 | 11 | if ($this->defaultExtension !== 'php' && !is_file($path)) { |
|
194 | $path = $file . '.php'; |
||
195 | } |
||
196 | |||
197 | 11 | return $path; |
|
198 | } |
||
199 | |||
200 | /** |
||
201 | * Renders a view file. |
||
202 | * |
||
203 | * If [[theme]] is enabled (not null), it will try to render the themed version of the view file as long |
||
204 | * as it is available. |
||
205 | * |
||
206 | * The method will call [[FileHelper::localize()]] to localize the view file. |
||
207 | * |
||
208 | * If [[renderers|renderer]] is enabled (not null), the method will use it to render the view file. |
||
209 | * Otherwise, it will simply include the view file as a normal PHP file, capture its output and |
||
210 | * return it as a string. |
||
211 | * |
||
212 | * @param string $viewFile the view file. This can be either an absolute file path or an alias of it. |
||
213 | * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view file. |
||
214 | * @param object $context the context that the view should use for rendering the view. If null, |
||
215 | * existing [[context]] will be used. |
||
216 | * @return string the rendering result |
||
217 | * @throws ViewNotFoundException if the view file does not exist |
||
218 | */ |
||
219 | 62 | public function renderFile($viewFile, $params = [], $context = null) |
|
220 | { |
||
221 | 62 | $viewFile = Yii::getAlias($viewFile); |
|
222 | |||
223 | 62 | if ($this->theme !== null) { |
|
224 | $viewFile = $this->theme->applyTo($viewFile); |
||
225 | } |
||
226 | 62 | if (is_file($viewFile)) { |
|
227 | 62 | $viewFile = FileHelper::localize($viewFile); |
|
228 | 62 | } else { |
|
229 | throw new ViewNotFoundException("The view file does not exist: $viewFile"); |
||
230 | } |
||
231 | |||
232 | 62 | $oldContext = $this->context; |
|
233 | 62 | if ($context !== null) { |
|
234 | 16 | $this->context = $context; |
|
235 | 16 | } |
|
236 | 62 | $output = ''; |
|
237 | 62 | $this->_viewFiles[] = $viewFile; |
|
238 | |||
239 | 62 | if ($this->beforeRender($viewFile, $params)) { |
|
240 | 62 | Yii::trace("Rendering view file: $viewFile", __METHOD__); |
|
241 | 62 | $ext = pathinfo($viewFile, PATHINFO_EXTENSION); |
|
242 | 62 | if (isset($this->renderers[$ext])) { |
|
243 | if (is_array($this->renderers[$ext]) || is_string($this->renderers[$ext])) { |
||
244 | $this->renderers[$ext] = Yii::createObject($this->renderers[$ext]); |
||
245 | } |
||
246 | /* @var $renderer ViewRenderer */ |
||
247 | $renderer = $this->renderers[$ext]; |
||
248 | $output = $renderer->render($this, $viewFile, $params); |
||
249 | } else { |
||
250 | 62 | $output = $this->renderPhpFile($viewFile, $params); |
|
251 | } |
||
252 | 62 | $this->afterRender($viewFile, $params, $output); |
|
253 | 62 | } |
|
254 | |||
255 | 62 | array_pop($this->_viewFiles); |
|
256 | 62 | $this->context = $oldContext; |
|
257 | |||
258 | 62 | return $output; |
|
259 | } |
||
260 | |||
261 | /** |
||
262 | * @return string|bool the view file currently being rendered. False if no view file is being rendered. |
||
263 | */ |
||
264 | 5 | public function getViewFile() |
|
265 | { |
||
266 | 5 | return end($this->_viewFiles); |
|
267 | } |
||
268 | |||
269 | /** |
||
270 | * This method is invoked right before [[renderFile()]] renders a view file. |
||
271 | * The default implementation will trigger the [[EVENT_BEFORE_RENDER]] event. |
||
272 | * If you override this method, make sure you call the parent implementation first. |
||
273 | * @param string $viewFile the view file to be rendered. |
||
274 | * @param array $params the parameter array passed to the [[render()]] method. |
||
275 | * @return bool whether to continue rendering the view file. |
||
276 | */ |
||
277 | 62 | public function beforeRender($viewFile, $params) |
|
278 | { |
||
279 | 62 | $event = new ViewEvent([ |
|
280 | 62 | 'viewFile' => $viewFile, |
|
281 | 62 | 'params' => $params, |
|
282 | 62 | ]); |
|
283 | 62 | $this->trigger(self::EVENT_BEFORE_RENDER, $event); |
|
284 | |||
285 | 62 | return $event->isValid; |
|
286 | } |
||
287 | |||
288 | /** |
||
289 | * This method is invoked right after [[renderFile()]] renders a view file. |
||
290 | * The default implementation will trigger the [[EVENT_AFTER_RENDER]] event. |
||
291 | * If you override this method, make sure you call the parent implementation first. |
||
292 | * @param string $viewFile the view file being rendered. |
||
293 | * @param array $params the parameter array passed to the [[render()]] method. |
||
294 | * @param string $output the rendering result of the view file. Updates to this parameter |
||
295 | * will be passed back and returned by [[renderFile()]]. |
||
296 | */ |
||
297 | 62 | public function afterRender($viewFile, $params, &$output) |
|
298 | { |
||
299 | 62 | if ($this->hasEventHandlers(self::EVENT_AFTER_RENDER)) { |
|
300 | $event = new ViewEvent([ |
||
301 | 'viewFile' => $viewFile, |
||
302 | 'params' => $params, |
||
303 | 'output' => $output, |
||
304 | ]); |
||
305 | $this->trigger(self::EVENT_AFTER_RENDER, $event); |
||
306 | $output = $event->output; |
||
307 | } |
||
308 | 62 | } |
|
309 | |||
310 | /** |
||
311 | * Renders a view file as a PHP script. |
||
312 | * |
||
313 | * This method treats the view file as a PHP script and includes the file. |
||
314 | * It extracts the given parameters and makes them available in the view file. |
||
315 | * The method captures the output of the included view file and returns it as a string. |
||
316 | * |
||
317 | * This method should mainly be called by view renderer or [[renderFile()]]. |
||
318 | * |
||
319 | * @param string $_file_ the view file. |
||
320 | * @param array $_params_ the parameters (name-value pairs) that will be extracted and made available in the view file. |
||
321 | * @return string the rendering result |
||
322 | */ |
||
323 | 62 | public function renderPhpFile($_file_, $_params_ = []) |
|
324 | { |
||
325 | 62 | ob_start(); |
|
326 | 62 | ob_implicit_flush(false); |
|
327 | 62 | extract($_params_, EXTR_OVERWRITE); |
|
328 | 62 | require($_file_); |
|
329 | |||
330 | 62 | return ob_get_clean(); |
|
331 | } |
||
332 | |||
333 | /** |
||
334 | * Renders dynamic content returned by the given PHP statements. |
||
335 | * This method is mainly used together with content caching (fragment caching and page caching) |
||
336 | * when some portions of the content (called *dynamic content*) should not be cached. |
||
337 | * The dynamic content must be returned by some PHP statements. |
||
338 | * @param string $statements the PHP statements for generating the dynamic content. |
||
339 | * @return string the placeholder of the dynamic content, or the dynamic content if there is no |
||
340 | * active content cache currently. |
||
341 | */ |
||
342 | 13 | public function renderDynamic($statements) |
|
343 | { |
||
344 | 13 | if (!empty($this->cacheStack)) { |
|
345 | 12 | $n = count($this->dynamicPlaceholders); |
|
346 | 12 | $placeholder = "<![CDATA[YII-DYNAMIC-$n]]>"; |
|
347 | 12 | $this->addDynamicPlaceholder($placeholder, $statements); |
|
348 | |||
349 | 12 | return $placeholder; |
|
350 | } |
||
351 | 1 | return $this->evaluateDynamicContent($statements); |
|
352 | } |
||
353 | |||
354 | /** |
||
355 | * Adds a placeholder for dynamic content. |
||
356 | * This method is internally used. |
||
357 | * @param string $placeholder the placeholder name |
||
358 | * @param string $statements the PHP statements for generating the dynamic content |
||
359 | */ |
||
360 | 12 | public function addDynamicPlaceholder($placeholder, $statements) |
|
361 | { |
||
362 | 12 | foreach ($this->cacheStack as $cache) { |
|
363 | 12 | $cache->dynamicPlaceholders[$placeholder] = $statements; |
|
364 | 12 | } |
|
365 | 12 | $this->dynamicPlaceholders[$placeholder] = $statements; |
|
366 | 12 | } |
|
367 | |||
368 | /** |
||
369 | * Evaluates the given PHP statements. |
||
370 | * This method is mainly used internally to implement dynamic content feature. |
||
371 | * @param string $statements the PHP statements to be evaluated. |
||
372 | * @return mixed the return value of the PHP statements. |
||
373 | */ |
||
374 | 13 | public function evaluateDynamicContent($statements) |
|
375 | { |
||
376 | 13 | return eval($statements); |
|
377 | } |
||
378 | |||
379 | /** |
||
380 | * Begins recording a block. |
||
381 | * This method is a shortcut to beginning [[Block]] |
||
382 | * @param string $id the block ID. |
||
383 | * @param bool $renderInPlace whether to render the block content in place. |
||
384 | * Defaults to false, meaning the captured block will not be displayed. |
||
385 | * @return Block the Block widget instance |
||
386 | */ |
||
387 | public function beginBlock($id, $renderInPlace = false) |
||
388 | { |
||
389 | return Block::begin([ |
||
390 | 'id' => $id, |
||
391 | 'renderInPlace' => $renderInPlace, |
||
392 | 'view' => $this, |
||
393 | ]); |
||
394 | } |
||
395 | |||
396 | /** |
||
397 | * Ends recording a block. |
||
398 | */ |
||
399 | public function endBlock() |
||
400 | { |
||
401 | Block::end(); |
||
402 | } |
||
403 | |||
404 | /** |
||
405 | * Begins the rendering of content that is to be decorated by the specified view. |
||
406 | * This method can be used to implement nested layout. For example, a layout can be embedded |
||
407 | * in another layout file specified as '@app/views/layouts/base.php' like the following: |
||
408 | * |
||
409 | * ```php |
||
410 | * <?php $this->beginContent('@app/views/layouts/base.php'); ?> |
||
411 | * //...layout content here... |
||
412 | * <?php $this->endContent(); ?> |
||
413 | * ``` |
||
414 | * |
||
415 | * @param string $viewFile the view file that will be used to decorate the content enclosed by this widget. |
||
416 | * This can be specified as either the view file path or path alias. |
||
417 | * @param array $params the variables (name => value) to be extracted and made available in the decorative view. |
||
418 | * @return ContentDecorator the ContentDecorator widget instance |
||
419 | * @see ContentDecorator |
||
420 | */ |
||
421 | public function beginContent($viewFile, $params = []) |
||
422 | { |
||
423 | return ContentDecorator::begin([ |
||
424 | 'viewFile' => $viewFile, |
||
425 | 'params' => $params, |
||
426 | 'view' => $this, |
||
427 | ]); |
||
428 | } |
||
429 | |||
430 | /** |
||
431 | * Ends the rendering of content. |
||
432 | */ |
||
433 | public function endContent() |
||
434 | { |
||
435 | ContentDecorator::end(); |
||
436 | } |
||
437 | |||
438 | /** |
||
439 | * Begins fragment caching. |
||
440 | * This method will display cached content if it is available. |
||
441 | * If not, it will start caching and would expect an [[endCache()]] |
||
442 | * call to end the cache and save the content into cache. |
||
443 | * A typical usage of fragment caching is as follows, |
||
444 | * |
||
445 | * ```php |
||
446 | * if ($this->beginCache($id)) { |
||
447 | * // ...generate content here |
||
448 | * $this->endCache(); |
||
449 | * } |
||
450 | * ``` |
||
451 | * |
||
452 | * @param string $id a unique ID identifying the fragment to be cached. |
||
453 | * @param array $properties initial property values for [[FragmentCache]] |
||
454 | * @return bool whether you should generate the content for caching. |
||
455 | * False if the cached version is available. |
||
456 | */ |
||
457 | 15 | public function beginCache($id, $properties = []) |
|
458 | { |
||
459 | 15 | $properties['id'] = $id; |
|
460 | 15 | $properties['view'] = $this; |
|
461 | /* @var $cache FragmentCache */ |
||
462 | 15 | $cache = FragmentCache::begin($properties); |
|
463 | 15 | if ($cache->getCachedContent() !== false) { |
|
464 | 12 | $this->endCache(); |
|
465 | |||
466 | 12 | return false; |
|
467 | } |
||
468 | 15 | return true; |
|
469 | } |
||
470 | |||
471 | /** |
||
472 | * Ends fragment caching. |
||
473 | */ |
||
474 | 15 | public function endCache() |
|
478 | |||
479 | /** |
||
480 | * Marks the beginning of a page. |
||
481 | */ |
||
482 | 48 | public function beginPage() |
|
489 | |||
490 | /** |
||
491 | * Marks the ending of a page. |
||
492 | */ |
||
493 | public function endPage() |
||
498 | } |
||
499 |
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:
If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.