Skip to content

Commit

Permalink
some update
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Oct 26, 2017
1 parent dbfea82 commit 93c4a97
Show file tree
Hide file tree
Showing 12 changed files with 118 additions and 53 deletions.
5 changes: 4 additions & 1 deletion examples/DemoCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,14 @@ class DemoCommand extends Command
protected static $name = 'demo';
protected static $description = 'this is a demo independent command. but config use configure(), it like symfony console: argument define by position';

/**
* {@inheritDoc}
*/
protected function configure()
{
$this->createDefinition()
->setDescription(self::getDescription())
->setExample($this->replaceAnnotationVars('{script} {command} john male 43 --opt1 value1'))
->setExample($this->handleAnnotationVars('{script} {command} john male 43 --opt1 value1'))
->addArgument('name', Input::ARG_REQUIRED, 'description for the argument [name], is required')
->addArgument('sex', Input::ARG_OPTIONAL, 'description for the argument [sex], is optional')
->addArgument('age', Input::ARG_OPTIONAL, 'description for the argument [age], is optional')
Expand Down
34 changes: 22 additions & 12 deletions src/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
namespace Inhere\Console;

use Inhere\Console\Base\AbstractApplication;
use LightCms\Web\App;

/**
* Class App
Expand All @@ -23,38 +24,47 @@ class Application extends AbstractApplication
/**
* Register a app group command(by controller)
* @param string $name The controller name
* @param string $controller The controller class
* @param string $class The controller class
* @return static
*/
public function controller(string $name, string $controller = null)
public function controller(string $name, string $class = null)
{
if (!$controller && class_exists($name)) {
/** @var Controller $controller */
$controller = $name;
$name = $controller::getName();
if (!$class && class_exists($name)) {
/** @var Controller $class */
$class = $name;
$name = $class::getName();
}

if (!$name || !$controller) {
if (!$name || !$class) {
throw new \InvalidArgumentException(
'Group-command "name" and "controller" not allowed to is empty! name: ' . $name . ', controller: ' . $controller
'Group-command "name" and "controller" not allowed to is empty! name: ' . $name . ', controller: ' . $class
);
}

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

if (!class_exists($controller)) {
throw new \InvalidArgumentException("The console controller class [$controller] not exists!");
if (!class_exists($class)) {
throw new \InvalidArgumentException("The console controller class [$class] not exists!");
}

if (!is_subclass_of($controller, Controller::class)) {
if (!is_subclass_of($class, Controller::class)) {
throw new \InvalidArgumentException('The console controller class must is subclass of the: ' . Controller::class);
}

$this->controllers[$name] = $controller;
$this->controllers[$name] = $class;

return $this;
}

/**
* @see Application::controller()
* {@inheritdoc}
*/
public function addController(string $name, string $class = null)
{
return $this->controller($name, $class);
}

/**
* @param array $controllers
*/
Expand Down
24 changes: 19 additions & 5 deletions src/Base/AbstractApplication.php
Original file line number Diff line number Diff line change
Expand Up @@ -155,16 +155,29 @@ public function run($exit = true)
}

/**
* dispatch command
* @param string $command A command name
* @return int|mixed
*/
abstract protected function dispatch($command);

/**
* run a independent command
* {@inheritdoc}
*/
abstract public function runCommand($name, $believable = false);

/**
* run a controller's action
* {@inheritdoc}
*/
abstract public function runAction($name, $action, $believable = false, $standAlone = false);

protected function afterRun()
{
// display runtime info
if ($this->isDebug()) {
$title = '------------ Runtime Stats ------------';
$title = '---------- Runtime Stats(debug=true) ----------';
$stats = $this->meta['_stats'];
$this->meta['_stats'] = Helper::runtime($stats['startTime'], $stats['startMemory'], $stats);
$this->output->write('');
Expand Down Expand Up @@ -315,7 +328,7 @@ public function showHelpInfo($quit = true)
$sep = $this->delimiter;

$this->output->helpPanel([
'usage' => "$script [route|command] [arg0 arg1=value1 arg2=value2 ...] [--opt -v -h ...]",
'usage' => "$script {route|command} [arg0 arg1=value1 arg2=value2 ...] [--opt -v -h ...]",
'example' => [
"$script test (run a independent command)",
"$script home{$sep}index (run a command of the group)",
Expand Down Expand Up @@ -366,6 +379,7 @@ public function showCommandList($quit = true)
// all console controllers
$controllers = $this->controllers;
ksort($controllers);

foreach ($controllers as $name => $controller) {
/** @var AbstractCommand $controller */
$controllerArr[$name] = $controller::getDescription() ?: $desPlaceholder;
Expand All @@ -383,7 +397,7 @@ public function showCommandList($quit = true)
} else if ($msg = $this->getCommandMessage($name)) {
$desc = $msg;
} else if (is_string($command)) {
$desc = 'A handler: ' . $command;
$desc = 'A handler : ' . $command;
} else if (is_object($command)) {
$desc = 'A handler by ' . get_class($command);
}
Expand All @@ -394,14 +408,14 @@ public function showCommandList($quit = true)
// $this->output->write('There are all console controllers and independent commands.');
$this->output->mList([
//'There are all console controllers and independent commands.',
'Usage:' => "$script [route|command] [arg0 arg1=value1 arg2=value2 ...] [--opt -v -h ...]",
'Usage:' => "$script {route|command} [arg0 arg1=value1 arg2=value2 ...] [--opt -v -h ...]",
'Group Commands:' => $controllerArr ?: '... No register any group command(controller)',
'Independent Commands:' => $commandArr ?: '... No register any independent command',
'Internal Commands:' => $internalCommands,
'Internal Options:' => self::$internalOptions
]);

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

Expand Down
14 changes: 2 additions & 12 deletions src/Base/AbstractCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,7 @@ protected function annotationVars()
* @param string $str
* @return string
*/
protected function replaceAnnotationVars($str)
protected function handleAnnotationVars($str)
{
$map = [];

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

/**
* get All Command Methods for a group(controller)
* @param \ReflectionClass|null $ref
* @return \Generator
*/
protected function getAllCommandMethods(\ReflectionClass $ref = null)
{
// ...
}

/**
* show help by parse method annotation
* @param string $method
Expand All @@ -348,7 +338,7 @@ protected function showHelpByMethodAnnotation($method, $action = null)
}

$doc = $ref->getMethod($method)->getDocComment();
$tags = Annotation::tagList($this->replaceAnnotationVars($doc));
$tags = Annotation::tagList($this->handleAnnotationVars($doc));

foreach ($tags as $tag => $msg) {
if (!$msg || !is_string($msg)) {
Expand Down
24 changes: 24 additions & 0 deletions src/Base/ApplicationInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,35 @@ interface ApplicationInterface
const ON_STOP_RUN = 'stopRun';
const ON_NOT_FOUND = 'notFound';

/**
* @param bool $exit
* @return int
*/
public function run($exit = true);

public function stop($code = 0);

/**
* run a independent command
* @param string $name
* @param bool $believable
* @return mixed
*/
public function runCommand($name, $believable = false);

/**
* run a controller's action
* @param string $name Controller name
* @param string $action Command
* @param bool $believable The `$name` is believable
* @param bool $standAlone
* @return mixed
*/
public function runAction($name, $action, $believable = false, $standAlone = false);

public function controller(string $name, string $controller = null);

public function command(string $name, $handler = null, $description = null);

public function showCommandList($quit = true);
}
5 changes: 5 additions & 0 deletions src/Base/CommandInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ public function getDefinition();
*/
public function getApp(): ApplicationInterface;

/**
* @return string
*/
public static function getName(): string;

/**
* @return string
*/
Expand Down
7 changes: 7 additions & 0 deletions src/Base/ControllerInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ interface ControllerInterface
*/
public function helpCommand();

public function showCommandList();

/**
* @return string
*/
Expand All @@ -28,4 +30,9 @@ public function getAction(): string;
* @return string
*/
public function getDefaultAction(): string;

/**
* @param string $delimiter
*/
public function setDelimiter(string $delimiter);
}
17 changes: 8 additions & 9 deletions src/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,7 @@ protected function configure()
*/
protected function execute($input, $output)
{
$action = $this->action ?: $this->defaultAction;
$action = Helper::camelCase(trim($action, $this->delimiter));
$action = Helper::camelCase(trim($this->action ?: $this->defaultAction, $this->delimiter));
$method = $this->actionSuffix ? $action . ucfirst($this->actionSuffix) : $action;

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

// find similar command names by similar_text()
$similares = [];
$similar = [];

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

if (45 <= (int)$percent) {
$similares[] = $cmd;
$similar[] = $cmd;
}
}

if ($similares) {
$this->write(sprintf('Maybe what you mean is: <info>%s</info>', implode(', ', $similares)));
if ($similar) {
$this->write(sprintf('Maybe what you mean is: <info>%s</info>', implode(', ', $similar)));
} else {
$this->showCommandList();
}
Expand Down Expand Up @@ -155,7 +155,7 @@ final public function helpCommand()
/**
* show command list of the controller class
*/
final protected function showCommandList()
final public function showCommandList()
{
$ref = new \ReflectionClass($this);
$sName = lcfirst(self::getName() ?: $ref->getShortName());
Expand Down Expand Up @@ -199,7 +199,6 @@ final protected function showCommandList()
'Commands:' => $commands,
'Options:' => [
'-h,--help' => 'Show help of the command group or specified command action',
// $this->showMore ? "\nMore information please use: <cyan>$script {$name}{command} -h</cyan>" : ''
],
]);

Expand Down
2 changes: 1 addition & 1 deletion src/IO/OutputInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,5 @@ interface OutputInterface
* @param int|boolean $quit If is int, setting it is exit code.
* @return static
*/
public function write($messages = '', $nl = true, $quit = false);
public function write($messages, $nl = true, $quit = false);
}
2 changes: 1 addition & 1 deletion src/Traits/FormatOutputTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ trait FormatOutputTrait
* @inheritdoc
* @see Show::write()
*/
public function write($messages = '', $nl = true, $quit = false): int
public function write($messages, $nl = true, $quit = false): int
{
return Show::write($messages, $nl, $quit, [
'flush' => true,
Expand Down
16 changes: 9 additions & 7 deletions src/Utils/Helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -318,10 +318,11 @@ public static function spliceKeyValue(array $data, array $opts = [])
$text = '';
$opts = array_merge([
'leftChar' => '', // e.g ' ', ' * '
'sepChar' => ' ', // e.g ' | ' => OUT: key | value
'sepChar' => ' ', // e.g ' | ' OUT: key | value
'keyStyle' => '', // e.g 'info','comment'
'valStyle' => '', // e.g 'info','comment'
'keyMaxWidth' => null, // if not set, will automatic calculation
'ucfirst' => true, // if not set, will automatic calculation
'ucFirst' => true, // upper first char
], $opts);

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

if ($hasKey && $opts['keyMaxWidth']) {
$key = str_pad($key, $opts['keyMaxWidth'], ' ');
$text .= ($keyStyle ? "<{$keyStyle}>$key</{$keyStyle}> " : $key) . $opts['sepChar'];
// $text .= ($keyStyle ? "<{$keyStyle}>$key</{$keyStyle}> " : $key) . $opts['sepChar'];
$text .= self::wrapTag($key, $keyStyle) . $opts['sepChar'];
}

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

$temp .= (!is_numeric($k) ? "$k: " : '') . "<info>$val</info>, ";
$temp .= (!is_numeric($k) ? "$k: " : '') . "$val, ";
}

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

$value = $hasKey && $opts['ucfirst'] ? ucfirst($value) : $value;
$text .= "$value\n";
$value = $hasKey && $opts['ucFirst'] ? ucfirst($value) : $value;
$text .= self::wrapTag($value, $opts['valStyle']) . "\n";
}

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

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

if ($startMem) {
$startMem = array_sum(explode(' ', $startMem));
Expand Down
Loading

0 comments on commit 93c4a97

Please sign in to comment.