Completed
Pull Request — 2.1 (#15718)
by Alex
17:00
created

HelpController   D

Complexity

Total Complexity 105

Size/Duplication

Total Lines 533
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 82.8%

Importance

Changes 0
Metric Value
wmc 105
lcom 1
cbo 6
dl 0
loc 533
ccs 231
cts 279
cp 0.828
rs 4.8717
c 0
b 0
f 0

16 Methods

Rating   Name   Duplication   Size   Complexity  
B actionList() 0 20 6
A getCommands() 0 6 1
A getCommandDescriptions() 0 18 4
B getActions() 0 14 6
B actionIndex() 0 21 6
C actionUsage() 0 33 7
C actionListActionOptions() 0 28 8
D getModuleCommands() 0 44 10
A validateControllerClass() 0 9 3
C getDefaultHelp() 0 67 17
D getCommandHelp() 0 41 9
C getSubCommandHelp() 0 73 12
D formatOptionHelp() 0 36 11
A formatOptionAliases() 0 11 3
A getScriptName() 0 4 1
A getDefaultHelpHeader() 0 4 1

How to fix   Complexity   

Complex Class

Complex classes like HelpController 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 HelpController, 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\console\controllers;
9
10
use Yii;
11
use yii\base\Application;
12
use yii\console\Controller;
13
use yii\console\Exception;
14
use yii\helpers\Console;
15
use yii\helpers\Inflector;
16
17
/**
18
 * Provides help information about console commands.
19
 *
20
 * This command displays the available command list in
21
 * the application or the detailed instructions about using
22
 * a specific command.
23
 *
24
 * This command can be used as follows on command line:
25
 *
26
 * ```
27
 * yii help [command name]
28
 * ```
29
 *
30
 * In the above, if the command name is not provided, all
31
 * available commands will be displayed.
32
 *
33
 * @property array $commands All available command names. This property is read-only.
34
 *
35
 * @author Qiang Xue <[email protected]>
36
 * @since 2.0
37
 */
38
class HelpController extends Controller
39
{
40
    /**
41
     * Displays available commands or the detailed information
42
     * about a particular command.
43
     *
44
     * @param string $command The name of the command to show help about.
45
     * If not provided, all available commands will be displayed.
46
     * @return int the exit status
47
     * @throws Exception if the command for help is unknown
48
     */
49 3
    public function actionIndex($command = null)
50
    {
51 3
        if ($command !== null) {
52 2
            $result = Yii::$app->createController($command);
53 2
            if ($result === false) {
54
                $name = $this->ansiFormat($command, Console::FG_YELLOW);
55
                throw new Exception("No help for unknown command \"$name\".");
56
            }
57
58 2
            [$controller, $actionID] = $result;
0 ignored issues
show
Bug introduced by
The variable $controller does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $actionID does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
59
60 2
            $actions = $this->getActions($controller);
61 2
            if ($actionID !== '' || count($actions) === 1 && $actions[0] === $controller->defaultAction) {
62 2
                $this->getSubCommandHelp($controller, $actionID);
63
            } else {
64 2
                $this->getCommandHelp($controller);
65
            }
66
        } else {
67 1
            $this->getDefaultHelp();
68
        }
69 3
    }
70
71
    /**
72
     * List all available controllers and actions in machine readable format.
73
     * This is used for shell completion.
74
     * @since 2.0.11
75
     */
76 2
    public function actionList()
77
    {
78 2
        $commands = $this->getCommandDescriptions();
79 2
        foreach ($commands as $command => $description) {
80 2
            $result = Yii::$app->createController($command);
81 2
            if ($result === false || !($result[0] instanceof Controller)) {
82
                continue;
83
            }
84
            /** @var $controller Controller */
85 2
            [$controller, $actionID] = $result;
0 ignored issues
show
Bug introduced by
The variable $controller does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $actionID does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
86 2
            $actions = $this->getActions($controller);
87 2
            if (!empty($actions)) {
88 2
                $prefix = $controller->getUniqueId();
89 2
                $this->stdout("$prefix\n");
90 2
                foreach ($actions as $action) {
91 2
                    $this->stdout("$prefix/$action\n");
92
                }
93
            }
94
        }
95 2
    }
96
97
    /**
98
     * List all available options for the $action in machine readable format.
99
     * This is used for shell completion.
100
     *
101
     * @param string $action route to action
102
     * @since 2.0.11
103
     */
104 1
    public function actionListActionOptions($action)
105
    {
106 1
        $result = Yii::$app->createController($action);
107
108 1
        if ($result === false || !($result[0] instanceof Controller)) {
109
            return;
110
        }
111
112
        /** @var Controller $controller */
113 1
        [$controller, $actionID] = $result;
0 ignored issues
show
Bug introduced by
The variable $controller does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $actionID does not exist. Did you mean $action?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
114 1
        $action = $controller->createAction($actionID);
0 ignored issues
show
Bug introduced by
The variable $actionID does not exist. Did you mean $action?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
115 1
        if ($action === null) {
116
            return;
117
        }
118
119 1
        $arguments = $controller->getActionArgsHelp($action);
120 1
        foreach ($arguments as $argument => $help) {
121 1
            $description = str_replace("\n", '', addcslashes($help['comment'], ':')) ?: $argument;
122 1
            $this->stdout($argument . ':' . $description . "\n");
123
        }
124
125 1
        $this->stdout("\n");
126 1
        $options = $controller->getActionOptionsHelp($action);
127 1
        foreach ($options as $argument => $help) {
128 1
            $description = str_replace("\n", '', addcslashes($help['comment'], ':'));
129 1
            $this->stdout('--' . $argument . ($description ? ':' . $description : '') . "\n");
130
        }
131 1
    }
132
133
    /**
134
     * Displays usage information for $action.
135
     *
136
     * @param string $action route to action
137
     * @since 2.0.11
138
     */
139 1
    public function actionUsage($action)
140
    {
141 1
        $result = Yii::$app->createController($action);
142
143 1
        if ($result === false || !($result[0] instanceof Controller)) {
144
            return;
145
        }
146
147
        /** @var Controller $controller */
148 1
        [$controller, $actionID] = $result;
0 ignored issues
show
Bug introduced by
The variable $controller does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $actionID does not exist. Did you mean $action?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
149 1
        $action = $controller->createAction($actionID);
0 ignored issues
show
Bug introduced by
The variable $actionID does not exist. Did you mean $action?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
150 1
        if ($action === null) {
151
            return;
152
        }
153
154 1
        $scriptName = $this->getScriptName();
155 1
        if ($action->id === $controller->defaultAction) {
156
            $this->stdout($scriptName . ' ' . $this->ansiFormat($controller->getUniqueId(), Console::FG_YELLOW));
157
        } else {
158 1
            $this->stdout($scriptName . ' ' . $this->ansiFormat($action->getUniqueId(), Console::FG_YELLOW));
159
        }
160
161 1
        $args = $controller->getActionArgsHelp($action);
162 1
        foreach ($args as $name => $arg) {
163 1
            if ($arg['required']) {
164 1
                $this->stdout(' <' . $name . '>', Console::FG_CYAN);
165
            } else {
166 1
                $this->stdout(' [' . $name . ']', Console::FG_CYAN);
167
            }
168
        }
169
170 1
        $this->stdout("\n");
171 1
    }
172
173
    /**
174
     * Returns all available command names.
175
     * @return array all available command names
176
     */
177 18
    public function getCommands()
178
    {
179 18
        $commands = $this->getModuleCommands(Yii::$app);
180 18
        sort($commands);
181 18
        return array_unique($commands);
182
    }
183
184
    /**
185
     * Returns an array of commands an their descriptions.
186
     * @return array all available commands as keys and their description as values.
187
     */
188 3
    protected function getCommandDescriptions()
189
    {
190 3
        $descriptions = [];
191 3
        foreach ($this->getCommands() as $command) {
192 3
            $description = '';
193
194 3
            $result = Yii::$app->createController($command);
195 3
            if ($result !== false && $result[0] instanceof Controller) {
196 3
                [$controller, $actionID] = $result;
0 ignored issues
show
Bug introduced by
The variable $controller does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $actionID does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
197
                /** @var Controller $controller */
198 3
                $description = $controller->getHelpSummary();
199
            }
200
201 3
            $descriptions[$command] = $description;
202
        }
203
204 3
        return $descriptions;
205
    }
206
207
    /**
208
     * Returns all available actions of the specified controller.
209
     * @param Controller $controller the controller instance
210
     * @return array all available action IDs.
211
     */
212 20
    public function getActions($controller)
213
    {
214 20
        $actions = array_keys($controller->actions());
215 20
        $class = new \ReflectionClass($controller);
216 20
        foreach ($class->getMethods() as $method) {
217 20
            $name = $method->getName();
0 ignored issues
show
Bug introduced by
Consider using $method->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
218 20
            if ($name !== 'actions' && $method->isPublic() && !$method->isStatic() && strpos($name, 'action') === 0) {
219 20
                $actions[] = Inflector::camel2id(substr($name, 6), '-', true);
220
            }
221
        }
222 20
        sort($actions);
223
224 20
        return array_unique($actions);
225
    }
226
227
    /**
228
     * Returns available commands of a specified module.
229
     * @param \yii\base\Module $module the module instance
230
     * @return array the available command names
231
     */
232 18
    protected function getModuleCommands($module)
233
    {
234 18
        $prefix = $module instanceof Application ? '' : $module->getUniqueId() . '/';
235
236 18
        $commands = [];
237 18
        foreach (array_keys($module->controllerMap) as $id) {
238 18
            $commands[] = $prefix . $id;
239
        }
240
241 18
        foreach ($module->getModules() as $id => $child) {
242 1
            if (($child = $module->getModule($id)) === null) {
243
                continue;
244
            }
245 1
            foreach ($this->getModuleCommands($child) as $command) {
246 1
                $commands[] = $command;
247
            }
248
        }
249
250 18
        $controllerPath = $module->getControllerPath();
251 18
        if (is_dir($controllerPath)) {
252 1
            $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($controllerPath, \RecursiveDirectoryIterator::KEY_AS_PATHNAME));
253 1
            $iterator = new \RegexIterator($iterator, '/.*Controller\.php$/', \RecursiveRegexIterator::GET_MATCH);
254 1
            foreach ($iterator as $matches) {
255 1
                $file = $matches[0];
256 1
                $relativePath = str_replace($controllerPath, '', $file);
257 1
                $class = strtr($relativePath, [
258 1
                    DIRECTORY_SEPARATOR => '\\',
259 1
                    '.php' => '',
260
                ]);
261 1
                $controllerClass = $module->controllerNamespace . $class;
262 1
                if ($this->validateControllerClass($controllerClass)) {
263 1
                    $dir = ltrim(pathinfo($relativePath, PATHINFO_DIRNAME), DIRECTORY_SEPARATOR);
264
265 1
                    $command = Inflector::camel2id(substr(basename($file), 0, -14), '-', true);
266 1
                    if (!empty($dir)) {
267 1
                        $command = $dir . DIRECTORY_SEPARATOR . $command;
268
                    }
269 1
                    $commands[] = $prefix . $command;
270
                }
271
            }
272
        }
273
274 18
        return $commands;
275
    }
276
277
    /**
278
     * Validates if the given class is a valid console controller class.
279
     * @param string $controllerClass
280
     * @return bool
281
     */
282 1
    protected function validateControllerClass($controllerClass)
283
    {
284 1
        if (class_exists($controllerClass)) {
285 1
            $class = new \ReflectionClass($controllerClass);
286 1
            return !$class->isAbstract() && $class->isSubclassOf(Controller::class);
287
        }
288
289
        return false;
290
    }
291
292
    /**
293
     * Displays all available commands.
294
     */
295 1
    protected function getDefaultHelp()
296
    {
297 1
        $commands = $this->getCommandDescriptions();
298 1
        $this->stdout($this->getDefaultHelpHeader());
299 1
        if (!empty($commands)) {
300 1
            $this->stdout("\nThe following commands are available:\n\n", Console::BOLD);
301 1
            $len = 0;
302 1
            foreach ($commands as $command => $description) {
303 1
                $result = Yii::$app->createController($command);
304 1
                if ($result !== false && $result[0] instanceof Controller) {
305
                    /** @var $controller Controller */
306 1
                    [$controller, $actionID] = $result;
0 ignored issues
show
Bug introduced by
The variable $controller does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $actionID does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
307 1
                    $actions = $this->getActions($controller);
308 1
                    if (!empty($actions)) {
309 1
                        $prefix = $controller->getUniqueId();
310 1
                        foreach ($actions as $action) {
311 1
                            $string = $prefix . '/' . $action;
312 1
                            if ($action === $controller->defaultAction) {
313 1
                                $string .= ' (default)';
314
                            }
315 1
                            if (($l = strlen($string)) > $len) {
316 1
                                $len = $l;
317
                            }
318
                        }
319
                    }
320
                } elseif (($l = strlen($command)) > $len) {
321 1
                    $len = $l;
322
                }
323
            }
324 1
            foreach ($commands as $command => $description) {
325 1
                $this->stdout('- ' . $this->ansiFormat($command, Console::FG_YELLOW));
326 1
                $this->stdout(str_repeat(' ', $len + 4 - strlen($command)));
327 1
                $this->stdout(Console::wrapText($description, $len + 4 + 2), Console::BOLD);
328 1
                $this->stdout("\n");
329
330 1
                $result = Yii::$app->createController($command);
331 1
                if ($result !== false && $result[0] instanceof Controller) {
332 1
                    [$controller, $actionID] = $result;
333 1
                    $actions = $this->getActions($controller);
334 1
                    if (!empty($actions)) {
335 1
                        $prefix = $controller->getUniqueId();
336 1
                        foreach ($actions as $action) {
337 1
                            $string = '  ' . $prefix . '/' . $action;
338 1
                            $this->stdout('  ' . $this->ansiFormat($string, Console::FG_GREEN));
339 1
                            if ($action === $controller->defaultAction) {
340 1
                                $string .= ' (default)';
341 1
                                $this->stdout(' (default)', Console::FG_YELLOW);
342
                            }
343 1
                            $summary = $controller->getActionHelpSummary($controller->createAction($action));
0 ignored issues
show
Documentation introduced by
$controller->createAction($action) is of type object|null, but the function expects a object<yii\base\Action>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
344 1
                            if ($summary !== '') {
345 1
                                $this->stdout(str_repeat(' ', $len + 4 - strlen($string)));
346 1
                                $this->stdout(Console::wrapText($summary, $len + 4 + 2));
347
                            }
348 1
                            $this->stdout("\n");
349
                        }
350
                    }
351 1
                    $this->stdout("\n");
352
                }
353
            }
354 1
            $scriptName = $this->getScriptName();
355 1
            $this->stdout("\nTo see the help of each command, enter:\n", Console::BOLD);
356 1
            $this->stdout("\n  $scriptName " . $this->ansiFormat('help', Console::FG_YELLOW) . ' '
357 1
                . $this->ansiFormat('<command-name>', Console::FG_CYAN) . "\n\n");
358
        } else {
359
            $this->stdout("\nNo commands are found.\n\n", Console::BOLD);
360
        }
361 1
    }
362
363
    /**
364
     * Displays the overall information of the command.
365
     * @param Controller $controller the controller instance
366
     */
367
    protected function getCommandHelp($controller)
368
    {
369
        $controller->color = $this->color;
370
371
        $this->stdout("\nDESCRIPTION\n", Console::BOLD);
372
        $comment = $controller->getHelp();
373
        if ($comment !== '') {
374
            $this->stdout("\n$comment\n\n");
375
        }
376
377
        $actions = $this->getActions($controller);
378
        if (!empty($actions)) {
379
            $this->stdout("\nSUB-COMMANDS\n\n", Console::BOLD);
380
            $prefix = $controller->getUniqueId();
381
382
            $maxlen = 5;
383
            foreach ($actions as $action) {
384
                $len = strlen($prefix . '/' . $action) + 2 + ($action === $controller->defaultAction ? 10 : 0);
385
                if ($maxlen < $len) {
386
                    $maxlen = $len;
387
                }
388
            }
389
            foreach ($actions as $action) {
390
                $this->stdout('- ' . $this->ansiFormat($prefix . '/' . $action, Console::FG_YELLOW));
391
                $len = strlen($prefix . '/' . $action) + 2;
392
                if ($action === $controller->defaultAction) {
393
                    $this->stdout(' (default)', Console::FG_GREEN);
394
                    $len += 10;
395
                }
396
                $summary = $controller->getActionHelpSummary($controller->createAction($action));
0 ignored issues
show
Documentation introduced by
$controller->createAction($action) is of type object|null, but the function expects a object<yii\base\Action>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
397
                if ($summary !== '') {
398
                    $this->stdout(str_repeat(' ', $maxlen - $len + 2) . Console::wrapText($summary, $maxlen + 2));
399
                }
400
                $this->stdout("\n");
401
            }
402
            $scriptName = $this->getScriptName();
403
            $this->stdout("\nTo see the detailed information about individual sub-commands, enter:\n");
404
            $this->stdout("\n  $scriptName " . $this->ansiFormat('help', Console::FG_YELLOW) . ' '
405
                . $this->ansiFormat('<sub-command>', Console::FG_CYAN) . "\n\n");
406
        }
407
    }
408
409
    /**
410
     * Displays the detailed information of a command action.
411
     * @param Controller $controller the controller instance
412
     * @param string $actionID action ID
413
     * @throws Exception if the action does not exist
414
     */
415 2
    protected function getSubCommandHelp($controller, $actionID)
416
    {
417 2
        $action = $controller->createAction($actionID);
418 2
        if ($action === null) {
419
            $name = $this->ansiFormat(rtrim($controller->getUniqueId() . '/' . $actionID, '/'), Console::FG_YELLOW);
420
            throw new Exception("No help for unknown sub-command \"$name\".");
421
        }
422
423 2
        $description = $controller->getActionHelp($action);
424 2
        if ($description !== '') {
425 2
            $this->stdout("\nDESCRIPTION\n", Console::BOLD);
426 2
            $this->stdout("\n$description\n\n");
427
        }
428
429 2
        $this->stdout("\nUSAGE\n\n", Console::BOLD);
430 2
        $scriptName = $this->getScriptName();
431 2
        if ($action->id === $controller->defaultAction) {
432 2
            $this->stdout($scriptName . ' ' . $this->ansiFormat($controller->getUniqueId(), Console::FG_YELLOW));
433
        } else {
434
            $this->stdout($scriptName . ' ' . $this->ansiFormat($action->getUniqueId(), Console::FG_YELLOW));
435
        }
436
437 2
        $args = $controller->getActionArgsHelp($action);
438 2
        foreach ($args as $name => $arg) {
439 2
            if ($arg['required']) {
440
                $this->stdout(' <' . $name . '>', Console::FG_CYAN);
441
            } else {
442 2
                $this->stdout(' [' . $name . ']', Console::FG_CYAN);
443
            }
444
        }
445
446 2
        $options = $controller->getActionOptionsHelp($action);
447 2
        $options[\yii\console\Application::OPTION_APPCONFIG] = [
448
            'type' => 'string',
449
            'default' => null,
450
            'comment' => "custom application configuration file path.\nIf not set, default application configuration is used.",
451
        ];
452 2
        ksort($options);
453
454 2
        if (!empty($options)) {
455 2
            $this->stdout(' [...options...]', Console::FG_RED);
456
        }
457 2
        $this->stdout("\n\n");
458
459 2
        if (!empty($args)) {
460 2
            foreach ($args as $name => $arg) {
461 2
                $this->stdout($this->formatOptionHelp(
462 2
                        '- ' . $this->ansiFormat($name, Console::FG_CYAN),
463 2
                        $arg['required'],
464 2
                        $arg['type'],
465 2
                        $arg['default'],
466 2
                        $arg['comment']
467 2
                ) . "\n\n");
468
            }
469
        }
470
471 2
        if (!empty($options)) {
472 2
            $this->stdout("\nOPTIONS\n\n", Console::BOLD);
473 2
            foreach ($options as $name => $option) {
474 2
                $this->stdout($this->formatOptionHelp(
475 2
                        $this->ansiFormat(
476 2
                            '--' . $name . $this->formatOptionAliases($controller, $name),
477 2
                            Console::FG_RED,
478 2
                            empty($option['required']) ? Console::FG_RED : Console::BOLD
479
                        ),
480 2
                        !empty($option['required']),
481 2
                        $option['type'],
482 2
                        $option['default'],
483 2
                        $option['comment']
484 2
                ) . "\n\n");
485
            }
486
        }
487 2
    }
488
489
    /**
490
     * Generates a well-formed string for an argument or option.
491
     * @param string $name the name of the argument or option
492
     * @param bool $required whether the argument is required
493
     * @param string $type the type of the option or argument
494
     * @param mixed $defaultValue the default value of the option or argument
495
     * @param string $comment comment about the option or argument
496
     * @return string the formatted string for the argument or option
497
     */
498 2
    protected function formatOptionHelp($name, $required, $type, $defaultValue, $comment)
499
    {
500 2
        $comment = trim($comment);
501 2
        $type = trim($type);
502 2
        if (strncmp($type, 'bool', 4) === 0) {
503 2
            $type = 'boolean, 0 or 1';
504
        }
505
506 2
        if ($defaultValue !== null && !is_array($defaultValue)) {
507 2
            if ($type === null) {
508
                $type = gettype($defaultValue);
509
            }
510 2
            if (is_bool($defaultValue)) {
511
                // show as integer to avoid confusion
512 2
                $defaultValue = (int) $defaultValue;
513
            }
514 2
            if (is_string($defaultValue)) {
515 1
                $defaultValue = "'" . $defaultValue . "'";
516
            } else {
517 2
                $defaultValue = var_export($defaultValue, true);
518
            }
519 2
            $doc = "$type (defaults to $defaultValue)";
520
        } else {
521 2
            $doc = $type;
522
        }
523
524 2
        if ($doc === '') {
525
            $doc = $comment;
526 2
        } elseif ($comment !== '') {
527 2
            $doc .= "\n" . preg_replace('/^/m', '  ', $comment);
528
        }
529
530 2
        $name = $required ? "$name (required)" : $name;
531
532 2
        return $doc === '' ? $name : "$name: $doc";
533
    }
534
535
    /**
536
     * @param Controller $controller the controller instance
537
     * @param string $option the option name
538
     * @return string the formatted string for the alias argument or option
539
     * @since 2.0.8
540
     */
541 2
    protected function formatOptionAliases($controller, $option)
542
    {
543 2
        $aliases = $controller->optionAliases();
544 2
        foreach ($aliases as $name => $value) {
545 2
            if ($value === $option) {
546 2
                return ', -' . $name;
547
            }
548
        }
549
550 2
        return '';
551
    }
552
553
    /**
554
     * @return string the name of the cli script currently running.
555
     */
556 4
    protected function getScriptName()
557
    {
558 4
        return basename(Yii::$app->request->scriptFile);
559
    }
560
561
    /**
562
     * Return a default help header.
563
     * @return string default help header.
564
     * @since 2.0.11
565
     */
566 1
    protected function getDefaultHelpHeader()
567
    {
568 1
        return "\nThis is Yii version " . \Yii::getVersion() . ".\n";
569
    }
570
}
571