-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHelpCommand.php
116 lines (107 loc) · 3.04 KB
/
HelpCommand.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
<?php
/**
* slince console component
* @author Tao <[email protected]>
*/
namespace Slince\Console;
use Slince\Console\Helper\HelperInterface;
use Slince\Console\Context\Io;
use Slince\Console\Context\Argv;
use Slince\Console\Context\Definition;
use Slince\Console\Context\Argument;
use Slince\Console\Context\Option;
class HelpCommand extends Command
{
/**
* help command name
*
* @var string
*/
const COMMAND_NAME = 'help';
/**
* help command name
*
* @var string
*/
protected $name = self::COMMAND_NAME;
/**
* (non-PHPdoc)
* @see \Slince\Console\Command::configure()
*/
function configure()
{
$this->name = 'help';
$this->addArgument('command_name', Option::VALUE_REQUIRED, 'The command name');
}
/**
* (non-PHPdoc)
* @see \Slince\Console\Command::execute()
*/
function execute(Io $io, Argv $argv)
{
$commandName = $argv->getArgument('command_name');
$command = $this->console->find($commandName);
$io->write($this->getCommandHelp($command));
}
/**
* 获取command的Help对象
*
* @param CommandInterface $command
* @return \Slince\Console\Help
*/
function getCommandHelp(CommandInterface $command)
{
$help = $this->createHelp();
$help->setDescription($command->getDescription());
$optionHelps = $argumentHelps = [];
foreach ($command->getDefinition()->getArguments() as $argument) {
$argumentHelps[$argument->getName()] = $argument->getDescription();
}
foreach ($command->getDefinition()->getOptions() as $option) {
$key = ($option->isShort() ? '-' : '--') . $option->getName();
$optionHelps[$key] = $option->getDescription();
}
$help->setUsage($this->getCommandUsage($command));
$help->setArgumentHelps($argumentHelps);
$help->setOptionHelps($optionHelps);
return $help;
}
/**
* 获取command的usage信息
*
* @param CommandInterface $command
* @return string
*/
protected function getCommandUsage(CommandInterface $command)
{
$argumentsUsages = [];
foreach ($command->getDefinition()->getArguments() as $argument) {
$usage = "<{$argument->getName()}>";
if ($argument->isValueOptional()) {
$usage = "[{$usage}]";
}
$argumentsUsages[] = $usage;
}
$usages[] = $command->getName();
$options = $command->getDefinition()->getOptions();
if ($haveOptions = ! empty($options)) {
$usages[] = '[options]';
}
if (! empty($argumentsUsages)) {
if ($haveOptions) {
$usages[] = '--';
}
$usages[] = implode(' ', $argumentsUsages);
}
return implode(' ', $usages);;
}
/**
* 创建一个help对象
*
* @return \Slince\Console\Help
*/
protected function createHelp()
{
return new Help();
}
}