Complex classes like Controller 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 Controller, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
41 | class Controller extends \yii\base\Controller |
||
42 | { |
||
43 | /** |
||
44 | * @var bool whether to run the command interactively. |
||
45 | */ |
||
46 | public $interactive = true; |
||
47 | /** |
||
48 | * @var bool whether to enable ANSI color in the output. |
||
49 | * If not set, ANSI color will only be enabled for terminals that support it. |
||
50 | */ |
||
51 | public $color; |
||
52 | /** |
||
53 | * @var bool whether to display help information about current command. |
||
54 | * @since 2.0.10 |
||
55 | */ |
||
56 | public $help; |
||
57 | |||
58 | /** |
||
59 | * @var array the options passed during execution. |
||
60 | */ |
||
61 | private $_passedOptions = []; |
||
62 | |||
63 | |||
64 | /** |
||
65 | * Returns a value indicating whether ANSI color is enabled. |
||
66 | * |
||
67 | * ANSI color is enabled only if [[color]] is set true or is not set |
||
68 | * and the terminal supports ANSI color. |
||
69 | * |
||
70 | * @param resource $stream the stream to check. |
||
71 | * @return bool Whether to enable ANSI style in output. |
||
72 | */ |
||
73 | 4 | public function isColorEnabled($stream = \STDOUT) |
|
77 | |||
78 | /** |
||
79 | * Runs an action with the specified action ID and parameters. |
||
80 | * If the action ID is empty, the method will use [[defaultAction]]. |
||
81 | * @param string $id the ID of the action to be executed. |
||
82 | * @param array $params the parameters (name-value pairs) to be passed to the action. |
||
83 | * @return int the status of the action execution. 0 means normal, other values mean abnormal. |
||
84 | * @throws InvalidRouteException if the requested action ID cannot be resolved into an action successfully. |
||
85 | * @throws Exception if there are unknown options or missing arguments |
||
86 | * @see createAction |
||
87 | */ |
||
88 | 112 | public function runAction($id, $params = []) |
|
89 | { |
||
90 | 112 | if (!empty($params)) { |
|
91 | // populate options here so that they are available in beforeAction(). |
||
92 | 101 | $options = $this->options($id === '' ? $this->defaultAction : $id); |
|
93 | 101 | if (isset($params['_aliases'])) { |
|
94 | 1 | $optionAliases = $this->optionAliases(); |
|
95 | 1 | foreach ($params['_aliases'] as $name => $value) { |
|
96 | 1 | if (array_key_exists($name, $optionAliases)) { |
|
97 | 1 | $params[$optionAliases[$name]] = $value; |
|
98 | } else { |
||
99 | 1 | throw new Exception(Yii::t('yii', 'Unknown alias: -{name}', ['name' => $name])); |
|
100 | } |
||
101 | } |
||
102 | 1 | unset($params['_aliases']); |
|
103 | } |
||
104 | 101 | foreach ($params as $name => $value) { |
|
105 | // Allow camelCase options to be entered in kebab-case |
||
106 | 101 | if (!in_array($name, $options, true) && strpos($name, '-') !== false) { |
|
107 | 1 | $kebabName = $name; |
|
108 | 1 | $altName = lcfirst(Inflector::id2camel($kebabName)); |
|
109 | 1 | if (in_array($altName, $options, true)) { |
|
110 | 1 | $name = $altName; |
|
111 | } |
||
112 | } |
||
113 | |||
114 | 101 | if (in_array($name, $options, true)) { |
|
115 | 11 | $default = $this->$name; |
|
116 | 11 | if (is_array($default)) { |
|
117 | 11 | $this->$name = preg_split('/\s*,\s*(?![^()]*\))/', $value); |
|
118 | 9 | } elseif ($default !== null) { |
|
119 | 8 | settype($value, gettype($default)); |
|
120 | 8 | $this->$name = $value; |
|
121 | } else { |
||
122 | 1 | $this->$name = $value; |
|
123 | } |
||
124 | 11 | $this->_passedOptions[] = $name; |
|
125 | 11 | unset($params[$name]); |
|
126 | 11 | if (isset($kebabName)) { |
|
127 | 11 | unset($params[$kebabName]); |
|
128 | } |
||
129 | 95 | } elseif (!is_int($name)) { |
|
130 | 101 | throw new Exception(Yii::t('yii', 'Unknown option: --{name}', ['name' => $name])); |
|
131 | } |
||
132 | } |
||
133 | } |
||
134 | 112 | if ($this->help) { |
|
135 | 2 | $route = $this->getUniqueId() . '/' . $id; |
|
136 | 2 | return Yii::$app->runAction('help', [$route]); |
|
137 | } |
||
138 | |||
139 | 112 | return parent::runAction($id, $params); |
|
140 | } |
||
141 | |||
142 | /** |
||
143 | * Binds the parameters to the action. |
||
144 | * This method is invoked by [[Action]] when it begins to run with the given parameters. |
||
145 | * This method will first bind the parameters with the [[options()|options]] |
||
146 | * available to the action. It then validates the given arguments. |
||
147 | * @param Action $action the action to be bound with parameters |
||
148 | * @param array $params the parameters to be bound to the action |
||
149 | * @return array the valid parameters that the action can run with. |
||
150 | * @throws Exception if there are unknown options or missing arguments |
||
151 | */ |
||
152 | 119 | public function bindActionParams($action, $params) |
|
182 | |||
183 | /** |
||
184 | * Formats a string with ANSI codes. |
||
185 | * |
||
186 | * You may pass additional parameters using the constants defined in [[\yii\helpers\Console]]. |
||
187 | * |
||
188 | * Example: |
||
189 | * |
||
190 | * ``` |
||
191 | * echo $this->ansiFormat('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE); |
||
192 | * ``` |
||
193 | * |
||
194 | * @param string $string the string to be formatted |
||
195 | * @return string |
||
196 | */ |
||
197 | 4 | public function ansiFormat($string) |
|
207 | |||
208 | /** |
||
209 | * Prints a string to STDOUT. |
||
210 | * |
||
211 | * You may optionally format the string with ANSI codes by |
||
212 | * passing additional parameters using the constants defined in [[\yii\helpers\Console]]. |
||
213 | * |
||
214 | * Example: |
||
215 | * |
||
216 | * ``` |
||
217 | * $this->stdout('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE); |
||
218 | * ``` |
||
219 | * |
||
220 | * @param string $string the string to print |
||
221 | * @return int|bool Number of bytes printed or false on error |
||
222 | */ |
||
223 | public function stdout($string) |
||
233 | |||
234 | /** |
||
235 | * Prints a string to STDERR. |
||
236 | * |
||
237 | * You may optionally format the string with ANSI codes by |
||
238 | * passing additional parameters using the constants defined in [[\yii\helpers\Console]]. |
||
239 | * |
||
240 | * Example: |
||
241 | * |
||
242 | * ``` |
||
243 | * $this->stderr('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE); |
||
244 | * ``` |
||
245 | * |
||
246 | * @param string $string the string to print |
||
247 | * @return int|bool Number of bytes printed or false on error |
||
248 | */ |
||
249 | public function stderr($string) |
||
259 | |||
260 | /** |
||
261 | * Prompts the user for input and validates it. |
||
262 | * |
||
263 | * @param string $text prompt string |
||
264 | * @param array $options the options to validate the input: |
||
265 | * |
||
266 | * - required: whether it is required or not |
||
267 | * - default: default value if no input is inserted by the user |
||
268 | * - pattern: regular expression pattern to validate user input |
||
269 | * - validator: a callable function to validate input. The function must accept two parameters: |
||
270 | * - $input: the user input to validate |
||
271 | * - $error: the error value passed by reference if validation failed. |
||
272 | * |
||
273 | * An example of how to use the prompt method with a validator function. |
||
274 | * |
||
275 | * ```php |
||
276 | * $code = $this->prompt('Enter 4-Chars-Pin', ['required' => true, 'validator' => function($input, &$error) { |
||
277 | * if (strlen($input) !== 4) { |
||
278 | * $error = 'The Pin must be exactly 4 chars!'; |
||
279 | * return false; |
||
280 | * } |
||
281 | * return true; |
||
282 | * }]); |
||
283 | * ``` |
||
284 | * |
||
285 | * @return string the user input |
||
286 | */ |
||
287 | public function prompt($text, $options = []) |
||
288 | { |
||
289 | if ($this->interactive) { |
||
290 | return Console::prompt($text, $options); |
||
291 | } |
||
292 | |||
293 | return $options['default'] ?? ''; |
||
294 | } |
||
295 | |||
296 | /** |
||
297 | * Asks user to confirm by typing y or n. |
||
298 | * |
||
299 | * A typical usage looks like the following: |
||
300 | * |
||
301 | * ```php |
||
302 | * if ($this->confirm("Are you sure?")) { |
||
303 | * echo "user typed yes\n"; |
||
304 | * } else { |
||
305 | * echo "user typed no\n"; |
||
306 | * } |
||
307 | * ``` |
||
308 | * |
||
309 | * @param string $message to echo out before waiting for user input |
||
310 | * @param bool $default this value is returned if no selection is made. |
||
311 | * @return bool whether user confirmed. |
||
312 | * Will return true if [[interactive]] is false. |
||
313 | */ |
||
314 | 67 | public function confirm($message, $default = false) |
|
322 | |||
323 | /** |
||
324 | * Gives the user an option to choose from. Giving '?' as an input will show |
||
325 | * a list of options to choose from and their explanations. |
||
326 | * |
||
327 | * @param string $prompt the prompt message |
||
328 | * @param array $options Key-value array of options to choose from |
||
329 | * |
||
330 | * @return string An option character the user chose |
||
331 | */ |
||
332 | public function select($prompt, $options = []) |
||
336 | |||
337 | /** |
||
338 | * Returns the names of valid options for the action (id) |
||
339 | * An option requires the existence of a public member variable whose |
||
340 | * name is the option name. |
||
341 | * Child classes may override this method to specify possible options. |
||
342 | * |
||
343 | * Note that the values setting via options are not available |
||
344 | * until [[beforeAction()]] is being called. |
||
345 | * |
||
346 | * @param string $actionID the action id of the current request |
||
347 | * @return string[] the names of the options valid for the action |
||
348 | */ |
||
349 | 104 | public function options($actionID) |
|
354 | |||
355 | /** |
||
356 | * Returns option alias names. |
||
357 | * Child classes may override this method to specify alias options. |
||
358 | * |
||
359 | * @return array the options alias names valid for the action |
||
360 | * where the keys is alias name for option and value is option name. |
||
361 | * |
||
362 | * @since 2.0.8 |
||
363 | * @see options() |
||
364 | */ |
||
365 | 2 | public function optionAliases() |
|
371 | |||
372 | /** |
||
373 | * Returns properties corresponding to the options for the action id |
||
374 | * Child classes may override this method to specify possible properties. |
||
375 | * |
||
376 | * @param string $actionID the action id of the current request |
||
377 | * @return array properties corresponding to the options for the action |
||
378 | */ |
||
379 | 42 | public function getOptionValues($actionID) |
|
389 | |||
390 | /** |
||
391 | * Returns the names of valid options passed during execution. |
||
392 | * |
||
393 | * @return array the names of the options passed during execution |
||
394 | */ |
||
395 | public function getPassedOptions() |
||
399 | |||
400 | /** |
||
401 | * Returns the properties corresponding to the passed options. |
||
402 | * |
||
403 | * @return array the properties corresponding to the passed options |
||
404 | */ |
||
405 | 39 | public function getPassedOptionValues() |
|
414 | |||
415 | /** |
||
416 | * Returns one-line short summary describing this controller. |
||
417 | * |
||
418 | * You may override this method to return customized summary. |
||
419 | * The default implementation returns first line from the PHPDoc comment. |
||
420 | * |
||
421 | * @return string |
||
422 | */ |
||
423 | 3 | public function getHelpSummary() |
|
427 | |||
428 | /** |
||
429 | * Returns help information for this controller. |
||
430 | * |
||
431 | * You may override this method to return customized help. |
||
432 | * The default implementation returns help information retrieved from the PHPDoc comment. |
||
433 | * @return string |
||
434 | */ |
||
435 | public function getHelp() |
||
439 | |||
440 | /** |
||
441 | * Returns a one-line short summary describing the specified action. |
||
442 | * @param Action $action action to get summary for |
||
443 | * @return string a one-line short summary describing the specified action. |
||
444 | */ |
||
445 | 1 | public function getActionHelpSummary($action) |
|
449 | |||
450 | /** |
||
451 | * Returns the detailed help information for the specified action. |
||
452 | * @param Action $action action to get help for |
||
453 | * @return string the detailed help information for the specified action. |
||
454 | */ |
||
455 | 2 | public function getActionHelp($action) |
|
459 | |||
460 | /** |
||
461 | * Returns the help information for the anonymous arguments for the action. |
||
462 | * |
||
463 | * The returned value should be an array. The keys are the argument names, and the values are |
||
464 | * the corresponding help information. Each value must be an array of the following structure: |
||
465 | * |
||
466 | * - required: boolean, whether this argument is required. |
||
467 | * - type: string, the PHP type of this argument. |
||
468 | * - default: string, the default value of this argument |
||
469 | * - comment: string, the comment of this argument |
||
470 | * |
||
471 | * The default implementation will return the help information extracted from the doc-comment of |
||
472 | * the parameters corresponding to the action method. |
||
473 | * |
||
474 | * @param Action $action |
||
475 | * @return array the help information of the action arguments |
||
476 | */ |
||
477 | 5 | public function getActionArgsHelp($action) |
|
478 | { |
||
479 | 5 | $method = $this->getActionMethodReflection($action); |
|
480 | 5 | $tags = $this->parseDocCommentTags($method); |
|
481 | 5 | $params = isset($tags['param']) ? (array) $tags['param'] : []; |
|
482 | |||
483 | 5 | $args = []; |
|
484 | |||
485 | /** @var \ReflectionParameter $reflection */ |
||
486 | 5 | foreach ($method->getParameters() as $i => $reflection) { |
|
487 | 5 | if ($reflection->getClass() !== null) { |
|
488 | 1 | continue; |
|
489 | } |
||
490 | 5 | $name = $reflection->getName(); |
|
491 | 5 | $tag = $params[$i] ?? ''; |
|
492 | 5 | if (preg_match('/^(\S+)\s+(\$\w+\s+)?(.*)/s', $tag, $matches)) { |
|
493 | 4 | $type = $matches[1]; |
|
494 | 4 | $comment = $matches[3]; |
|
495 | } else { |
||
496 | 1 | $type = null; |
|
497 | 1 | $comment = $tag; |
|
498 | } |
||
499 | 5 | if ($reflection->isDefaultValueAvailable()) { |
|
500 | 2 | $args[$name] = [ |
|
501 | 2 | 'required' => false, |
|
502 | 2 | 'type' => $type, |
|
503 | 2 | 'default' => $reflection->getDefaultValue(), |
|
504 | 2 | 'comment' => $comment, |
|
505 | ]; |
||
506 | } else { |
||
507 | 3 | $args[$name] = [ |
|
508 | 3 | 'required' => true, |
|
509 | 3 | 'type' => $type, |
|
510 | 'default' => null, |
||
511 | 5 | 'comment' => $comment, |
|
512 | ]; |
||
513 | } |
||
514 | } |
||
515 | |||
516 | 5 | return $args; |
|
517 | } |
||
518 | |||
519 | /** |
||
520 | * Returns the help information for the options for the action. |
||
521 | * |
||
522 | * The returned value should be an array. The keys are the option names, and the values are |
||
523 | * the corresponding help information. Each value must be an array of the following structure: |
||
524 | * |
||
525 | * - type: string, the PHP type of this argument. |
||
526 | * - default: string, the default value of this argument |
||
527 | * - comment: string, the comment of this argument |
||
528 | * |
||
529 | * The default implementation will return the help information extracted from the doc-comment of |
||
530 | * the properties corresponding to the action options. |
||
531 | * |
||
532 | * @param Action $action |
||
533 | * @return array the help information of the action options |
||
534 | */ |
||
535 | 3 | public function getActionOptionsHelp($action) |
|
536 | { |
||
537 | 3 | $optionNames = $this->options($action->id); |
|
538 | 3 | if (empty($optionNames)) { |
|
539 | return []; |
||
540 | } |
||
541 | |||
542 | 3 | $class = new \ReflectionClass($this); |
|
543 | 3 | $options = []; |
|
544 | 3 | foreach ($class->getProperties() as $property) { |
|
545 | 3 | $name = $property->getName(); |
|
546 | 3 | if (!in_array($name, $optionNames, true)) { |
|
547 | 3 | continue; |
|
548 | } |
||
549 | 3 | $defaultValue = $property->getValue($this); |
|
550 | 3 | $tags = $this->parseDocCommentTags($property); |
|
551 | |||
552 | // Display camelCase options in kebab-case |
||
553 | 3 | $name = Inflector::camel2id($name, '-', true); |
|
554 | |||
555 | 3 | if (isset($tags['var']) || isset($tags['property'])) { |
|
556 | 3 | $doc = $tags['var'] ?? $tags['property']; |
|
557 | 3 | if (is_array($doc)) { |
|
558 | $doc = reset($doc); |
||
559 | } |
||
560 | 3 | if (preg_match('/^(\S+)(.*)/s', $doc, $matches)) { |
|
561 | 3 | $type = $matches[1]; |
|
562 | 3 | $comment = $matches[2]; |
|
563 | } else { |
||
564 | $type = null; |
||
565 | $comment = $doc; |
||
566 | } |
||
567 | 3 | $options[$name] = [ |
|
568 | 3 | 'type' => $type, |
|
569 | 3 | 'default' => $defaultValue, |
|
570 | 3 | 'comment' => $comment, |
|
571 | ]; |
||
572 | } else { |
||
573 | $options[$name] = [ |
||
574 | 'type' => null, |
||
575 | 'default' => $defaultValue, |
||
576 | 3 | 'comment' => '', |
|
577 | ]; |
||
578 | } |
||
579 | } |
||
580 | |||
581 | 3 | return $options; |
|
582 | } |
||
583 | |||
584 | private $_reflections = []; |
||
585 | |||
586 | /** |
||
587 | * @param Action $action |
||
588 | * @return \ReflectionMethod |
||
589 | */ |
||
590 | 6 | protected function getActionMethodReflection($action) |
|
602 | |||
603 | /** |
||
604 | * Parses the comment block into tags. |
||
605 | * @param \Reflector $reflection the comment block |
||
606 | * @return array the parsed tags |
||
607 | */ |
||
608 | 5 | protected function parseDocCommentTags($reflection) |
|
629 | |||
630 | /** |
||
631 | * Returns the first line of docblock. |
||
632 | * |
||
633 | * @param \Reflector $reflection |
||
634 | * @return string |
||
635 | */ |
||
636 | 3 | protected function parseDocCommentSummary($reflection) |
|
645 | |||
646 | /** |
||
647 | * Returns full description from the docblock. |
||
648 | * |
||
649 | * @param \Reflector $reflection |
||
650 | * @return string |
||
651 | */ |
||
652 | 2 | protected function parseDocCommentDetail($reflection) |
|
664 | } |
||
665 |