Skip to content

Commit 93c4a97

Browse files
committed
some update
1 parent dbfea82 commit 93c4a97

12 files changed

+118
-53
lines changed

examples/DemoCommand.php

+4-1
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,14 @@ class DemoCommand extends Command
2121
protected static $name = 'demo';
2222
protected static $description = 'this is a demo independent command. but config use configure(), it like symfony console: argument define by position';
2323

24+
/**
25+
* {@inheritDoc}
26+
*/
2427
protected function configure()
2528
{
2629
$this->createDefinition()
2730
->setDescription(self::getDescription())
28-
->setExample($this->replaceAnnotationVars('{script} {command} john male 43 --opt1 value1'))
31+
->setExample($this->handleAnnotationVars('{script} {command} john male 43 --opt1 value1'))
2932
->addArgument('name', Input::ARG_REQUIRED, 'description for the argument [name], is required')
3033
->addArgument('sex', Input::ARG_OPTIONAL, 'description for the argument [sex], is optional')
3134
->addArgument('age', Input::ARG_OPTIONAL, 'description for the argument [age], is optional')

src/Application.php

+22-12
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
namespace Inhere\Console;
1010

1111
use Inhere\Console\Base\AbstractApplication;
12+
use LightCms\Web\App;
1213

1314
/**
1415
* Class App
@@ -23,38 +24,47 @@ class Application extends AbstractApplication
2324
/**
2425
* Register a app group command(by controller)
2526
* @param string $name The controller name
26-
* @param string $controller The controller class
27+
* @param string $class The controller class
2728
* @return static
2829
*/
29-
public function controller(string $name, string $controller = null)
30+
public function controller(string $name, string $class = null)
3031
{
31-
if (!$controller && class_exists($name)) {
32-
/** @var Controller $controller */
33-
$controller = $name;
34-
$name = $controller::getName();
32+
if (!$class && class_exists($name)) {
33+
/** @var Controller $class */
34+
$class = $name;
35+
$name = $class::getName();
3536
}
3637

37-
if (!$name || !$controller) {
38+
if (!$name || !$class) {
3839
throw new \InvalidArgumentException(
39-
'Group-command "name" and "controller" not allowed to is empty! name: ' . $name . ', controller: ' . $controller
40+
'Group-command "name" and "controller" not allowed to is empty! name: ' . $name . ', controller: ' . $class
4041
);
4142
}
4243

4344
$this->validateName($name, true);
4445

45-
if (!class_exists($controller)) {
46-
throw new \InvalidArgumentException("The console controller class [$controller] not exists!");
46+
if (!class_exists($class)) {
47+
throw new \InvalidArgumentException("The console controller class [$class] not exists!");
4748
}
4849

49-
if (!is_subclass_of($controller, Controller::class)) {
50+
if (!is_subclass_of($class, Controller::class)) {
5051
throw new \InvalidArgumentException('The console controller class must is subclass of the: ' . Controller::class);
5152
}
5253

53-
$this->controllers[$name] = $controller;
54+
$this->controllers[$name] = $class;
5455

5556
return $this;
5657
}
5758

59+
/**
60+
* @see Application::controller()
61+
* {@inheritdoc}
62+
*/
63+
public function addController(string $name, string $class = null)
64+
{
65+
return $this->controller($name, $class);
66+
}
67+
5868
/**
5969
* @param array $controllers
6070
*/

src/Base/AbstractApplication.php

+19-5
Original file line numberDiff line numberDiff line change
@@ -155,16 +155,29 @@ public function run($exit = true)
155155
}
156156

157157
/**
158+
* dispatch command
158159
* @param string $command A command name
159160
* @return int|mixed
160161
*/
161162
abstract protected function dispatch($command);
162163

164+
/**
165+
* run a independent command
166+
* {@inheritdoc}
167+
*/
168+
abstract public function runCommand($name, $believable = false);
169+
170+
/**
171+
* run a controller's action
172+
* {@inheritdoc}
173+
*/
174+
abstract public function runAction($name, $action, $believable = false, $standAlone = false);
175+
163176
protected function afterRun()
164177
{
165178
// display runtime info
166179
if ($this->isDebug()) {
167-
$title = '------------ Runtime Stats ------------';
180+
$title = '---------- Runtime Stats(debug=true) ----------';
168181
$stats = $this->meta['_stats'];
169182
$this->meta['_stats'] = Helper::runtime($stats['startTime'], $stats['startMemory'], $stats);
170183
$this->output->write('');
@@ -315,7 +328,7 @@ public function showHelpInfo($quit = true)
315328
$sep = $this->delimiter;
316329

317330
$this->output->helpPanel([
318-
'usage' => "$script [route|command] [arg0 arg1=value1 arg2=value2 ...] [--opt -v -h ...]",
331+
'usage' => "$script {route|command} [arg0 arg1=value1 arg2=value2 ...] [--opt -v -h ...]",
319332
'example' => [
320333
"$script test (run a independent command)",
321334
"$script home{$sep}index (run a command of the group)",
@@ -366,6 +379,7 @@ public function showCommandList($quit = true)
366379
// all console controllers
367380
$controllers = $this->controllers;
368381
ksort($controllers);
382+
369383
foreach ($controllers as $name => $controller) {
370384
/** @var AbstractCommand $controller */
371385
$controllerArr[$name] = $controller::getDescription() ?: $desPlaceholder;
@@ -383,7 +397,7 @@ public function showCommandList($quit = true)
383397
} else if ($msg = $this->getCommandMessage($name)) {
384398
$desc = $msg;
385399
} else if (is_string($command)) {
386-
$desc = 'A handler: ' . $command;
400+
$desc = 'A handler : ' . $command;
387401
} else if (is_object($command)) {
388402
$desc = 'A handler by ' . get_class($command);
389403
}
@@ -394,14 +408,14 @@ public function showCommandList($quit = true)
394408
// $this->output->write('There are all console controllers and independent commands.');
395409
$this->output->mList([
396410
//'There are all console controllers and independent commands.',
397-
'Usage:' => "$script [route|command] [arg0 arg1=value1 arg2=value2 ...] [--opt -v -h ...]",
411+
'Usage:' => "$script {route|command} [arg0 arg1=value1 arg2=value2 ...] [--opt -v -h ...]",
398412
'Group Commands:' => $controllerArr ?: '... No register any group command(controller)',
399413
'Independent Commands:' => $commandArr ?: '... No register any independent command',
400414
'Internal Commands:' => $internalCommands,
401415
'Internal Options:' => self::$internalOptions
402416
]);
403417

404-
$this->output->write("More please see: <cyan>$script [controller|command] -h</cyan>");
418+
$this->output->write("More command information, please use: <cyan>$script {command} -h</cyan>");
405419
$quit && $this->stop();
406420
}
407421

src/Base/AbstractCommand.php

+2-12
Original file line numberDiff line numberDiff line change
@@ -302,7 +302,7 @@ protected function annotationVars()
302302
* @param string $str
303303
* @return string
304304
*/
305-
protected function replaceAnnotationVars($str)
305+
protected function handleAnnotationVars($str)
306306
{
307307
$map = [];
308308

@@ -314,16 +314,6 @@ protected function replaceAnnotationVars($str)
314314
return $map ? strtr($str, $map) : $str;
315315
}
316316

317-
/**
318-
* get All Command Methods for a group(controller)
319-
* @param \ReflectionClass|null $ref
320-
* @return \Generator
321-
*/
322-
protected function getAllCommandMethods(\ReflectionClass $ref = null)
323-
{
324-
// ...
325-
}
326-
327317
/**
328318
* show help by parse method annotation
329319
* @param string $method
@@ -348,7 +338,7 @@ protected function showHelpByMethodAnnotation($method, $action = null)
348338
}
349339

350340
$doc = $ref->getMethod($method)->getDocComment();
351-
$tags = Annotation::tagList($this->replaceAnnotationVars($doc));
341+
$tags = Annotation::tagList($this->handleAnnotationVars($doc));
352342

353343
foreach ($tags as $tag => $msg) {
354344
if (!$msg || !is_string($msg)) {

src/Base/ApplicationInterface.php

+24
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,35 @@ interface ApplicationInterface
2121
const ON_STOP_RUN = 'stopRun';
2222
const ON_NOT_FOUND = 'notFound';
2323

24+
/**
25+
* @param bool $exit
26+
* @return int
27+
*/
2428
public function run($exit = true);
2529

2630
public function stop($code = 0);
2731

32+
/**
33+
* run a independent command
34+
* @param string $name
35+
* @param bool $believable
36+
* @return mixed
37+
*/
38+
public function runCommand($name, $believable = false);
39+
40+
/**
41+
* run a controller's action
42+
* @param string $name Controller name
43+
* @param string $action Command
44+
* @param bool $believable The `$name` is believable
45+
* @param bool $standAlone
46+
* @return mixed
47+
*/
48+
public function runAction($name, $action, $believable = false, $standAlone = false);
49+
2850
public function controller(string $name, string $controller = null);
2951

3052
public function command(string $name, $handler = null, $description = null);
53+
54+
public function showCommandList($quit = true);
3155
}

src/Base/CommandInterface.php

+5
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,11 @@ public function getDefinition();
3333
*/
3434
public function getApp(): ApplicationInterface;
3535

36+
/**
37+
* @return string
38+
*/
39+
public static function getName(): string;
40+
3641
/**
3742
* @return string
3843
*/

src/Base/ControllerInterface.php

+7
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ interface ControllerInterface
1919
*/
2020
public function helpCommand();
2121

22+
public function showCommandList();
23+
2224
/**
2325
* @return string
2426
*/
@@ -28,4 +30,9 @@ public function getAction(): string;
2830
* @return string
2931
*/
3032
public function getDefaultAction(): string;
33+
34+
/**
35+
* @param string $delimiter
36+
*/
37+
public function setDelimiter(string $delimiter);
3138
}

src/Controller.php

+8-9
Original file line numberDiff line numberDiff line change
@@ -74,8 +74,7 @@ protected function configure()
7474
*/
7575
protected function execute($input, $output)
7676
{
77-
$action = $this->action ?: $this->defaultAction;
78-
$action = Helper::camelCase(trim($action, $this->delimiter));
77+
$action = Helper::camelCase(trim($this->action ?: $this->defaultAction, $this->delimiter));
7978
$method = $this->actionSuffix ? $action . ucfirst($this->actionSuffix) : $action;
8079

8180
// the action method exists and only allow access public method.
@@ -87,22 +86,23 @@ protected function execute($input, $output)
8786
} elseif (($notFoundCallback = $this->notFoundCallback) && method_exists($this, $notFoundCallback)) {
8887
$status = $this->{$notFoundCallback}($action);
8988
} else {
89+
$group = static::getName();
9090
$status = -1;
91-
$this->output->liteError("Sorry, the console controller command [$action] not exist!");
91+
$this->output->liteError("Sorry, The command '$action' not exist of the group '{$group}'!");
9292

9393
// find similar command names by similar_text()
94-
$similares = [];
94+
$similar = [];
9595

9696
foreach ($this->getAllCommandMethods() as $cmd => $refM) {
9797
similar_text($action, $cmd, $percent);
9898

9999
if (45 <= (int)$percent) {
100-
$similares[] = $cmd;
100+
$similar[] = $cmd;
101101
}
102102
}
103103

104-
if ($similares) {
105-
$this->write(sprintf('Maybe what you mean is: <info>%s</info>', implode(', ', $similares)));
104+
if ($similar) {
105+
$this->write(sprintf('Maybe what you mean is: <info>%s</info>', implode(', ', $similar)));
106106
} else {
107107
$this->showCommandList();
108108
}
@@ -155,7 +155,7 @@ final public function helpCommand()
155155
/**
156156
* show command list of the controller class
157157
*/
158-
final protected function showCommandList()
158+
final public function showCommandList()
159159
{
160160
$ref = new \ReflectionClass($this);
161161
$sName = lcfirst(self::getName() ?: $ref->getShortName());
@@ -199,7 +199,6 @@ final protected function showCommandList()
199199
'Commands:' => $commands,
200200
'Options:' => [
201201
'-h,--help' => 'Show help of the command group or specified command action',
202-
// $this->showMore ? "\nMore information please use: <cyan>$script {$name}{command} -h</cyan>" : ''
203202
],
204203
]);
205204

src/IO/OutputInterface.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -21,5 +21,5 @@ interface OutputInterface
2121
* @param int|boolean $quit If is int, setting it is exit code.
2222
* @return static
2323
*/
24-
public function write($messages = '', $nl = true, $quit = false);
24+
public function write($messages, $nl = true, $quit = false);
2525
}

src/Traits/FormatOutputTrait.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ trait FormatOutputTrait
4040
* @inheritdoc
4141
* @see Show::write()
4242
*/
43-
public function write($messages = '', $nl = true, $quit = false): int
43+
public function write($messages, $nl = true, $quit = false): int
4444
{
4545
return Show::write($messages, $nl, $quit, [
4646
'flush' => true,

src/Utils/Helper.php

+9-7
Original file line numberDiff line numberDiff line change
@@ -318,10 +318,11 @@ public static function spliceKeyValue(array $data, array $opts = [])
318318
$text = '';
319319
$opts = array_merge([
320320
'leftChar' => '', // e.g ' ', ' * '
321-
'sepChar' => ' ', // e.g ' | ' => OUT: key | value
321+
'sepChar' => ' ', // e.g ' | ' OUT: key | value
322322
'keyStyle' => '', // e.g 'info','comment'
323+
'valStyle' => '', // e.g 'info','comment'
323324
'keyMaxWidth' => null, // if not set, will automatic calculation
324-
'ucfirst' => true, // if not set, will automatic calculation
325+
'ucFirst' => true, // upper first char
325326
], $opts);
326327

327328
if (!is_numeric($opts['keyMaxWidth'])) {
@@ -336,7 +337,8 @@ public static function spliceKeyValue(array $data, array $opts = [])
336337

337338
if ($hasKey && $opts['keyMaxWidth']) {
338339
$key = str_pad($key, $opts['keyMaxWidth'], ' ');
339-
$text .= ($keyStyle ? "<{$keyStyle}>$key</{$keyStyle}> " : $key) . $opts['sepChar'];
340+
// $text .= ($keyStyle ? "<{$keyStyle}>$key</{$keyStyle}> " : $key) . $opts['sepChar'];
341+
$text .= self::wrapTag($key, $keyStyle) . $opts['sepChar'];
340342
}
341343

342344
// if value is array, translate array to string
@@ -351,7 +353,7 @@ public static function spliceKeyValue(array $data, array $opts = [])
351353
$val = is_scalar($val) ? (string)$val : gettype($val);
352354
}
353355

354-
$temp .= (!is_numeric($k) ? "$k: " : '') . "<info>$val</info>, ";
356+
$temp .= (!is_numeric($k) ? "$k: " : '') . "$val, ";
355357
}
356358

357359
$value = rtrim($temp, ' ,');
@@ -361,8 +363,8 @@ public static function spliceKeyValue(array $data, array $opts = [])
361363
$value = (string)$value;
362364
}
363365

364-
$value = $hasKey && $opts['ucfirst'] ? ucfirst($value) : $value;
365-
$text .= "$value\n";
366+
$value = $hasKey && $opts['ucFirst'] ? ucfirst($value) : $value;
367+
$text .= self::wrapTag($value, $opts['valStyle']) . "\n";
366368
}
367369

368370
return $text;
@@ -481,7 +483,7 @@ public static function runtime($startTime, $startMem, array $info = [])
481483
$info['endMemory'] = memory_get_usage(true);
482484

483485
// 计算运行时间
484-
$info['runtime'] = number_format(($info['endTime'] - $startTime) * 1000, 3) . 'ms';
486+
$info['runtime'] = number_format(($info['endTime'] - $startTime) * 1000, 3) . 'ms';
485487

486488
if ($startMem) {
487489
$startMem = array_sum(explode(' ', $startMem));

0 commit comments

Comments
 (0)