Skip to content

Commit

Permalink
fix some error, update some
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Dec 31, 2018
1 parent 6ac9a8c commit d4b73b5
Show file tree
Hide file tree
Showing 10 changed files with 137 additions and 95 deletions.
10 changes: 10 additions & 0 deletions examples/Controllers/ShowController.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,16 @@ public static function commandAliases(): array
];
}

/**
* @return array
*/
protected function commonOptions(): array
{
return \array_merge(parent::commonOptions(), [
'-c, --command' => 'This is a common option for all sub-commands',
]);
}

/**
* output format message: title
*/
Expand Down
1 change: 1 addition & 0 deletions src/Base/AbstractApplication.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
namespace Inhere\Console\Base;

use Inhere\Console\BuiltIn\ErrorHandler;
use Inhere\Console\Face\CommandInterface;
use Inhere\Console\Face\ErrorHandlerInterface;
use Inhere\Console\IO\Input;
use Inhere\Console\IO\InputInterface;
Expand Down
111 changes: 66 additions & 45 deletions src/Base/AbstractCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,6 @@ abstract class AbstractCommand implements BaseCommandInterface
*/
protected static $coroutine = false;

/** @var array */
protected static $commandOptions = [
'--skip-invalid' => 'Whether ignore invalid arguments and options, when use input definition',
];

/**
* Allow display message tags in the command annotation
* @var array
Expand All @@ -63,16 +58,20 @@ abstract class AbstractCommand implements BaseCommandInterface
'arguments' => true,
'options' => true,
'example' => true,
'help' => true,
];

/** @var Application */
protected $app;

/** @var array common options for all sub-commands */
private $commonOptions;

/** @var InputDefinition|null */
private $definition;

/** @var string */
private $processTitle;
private $processTitle = '';

/** @var array */
private $annotationVars;
Expand Down Expand Up @@ -111,6 +110,7 @@ public function __construct(Input $input, Output $output, InputDefinition $defin
$this->definition = $definition;
}

$this->commonOptions = $this->commonOptions();
$this->annotationVars = $this->annotationVars();

$this->init();
Expand Down Expand Up @@ -143,11 +143,21 @@ protected function createDefinition(): InputDefinition
return $this->definition;
}

/**
* @return array
*/
protected function commonOptions(): array
{
return [
'--skip-invalid' => 'Whether ignore invalid arguments and options, when use input definition',
];
}

/**
* 为命令注解提供可解析解析变量. 可以在命令的注释中使用
* @return array
*/
public function annotationVars(): array
protected function annotationVars(): array
{
// e.g: `more info see {name}:index`
return [
Expand All @@ -157,7 +167,7 @@ public function annotationVars(): array
'script' => $this->input->getScript(), // bin/app
'binName' => $this->input->getScript(), // bin/app
'command' => $this->input->getCommand(), // demo OR home:test
'fullCommand' => $this->input->getScript() . ' ' . $this->input->getCommand(),
'fullCommand' => $this->input->getFullCommand(),
];
}

Expand Down Expand Up @@ -256,48 +266,23 @@ protected function afterExecute()
{
}

/**
* display help information
* @return bool
*/
protected function showHelp(): bool
{
if (!$definition = $this->getDefinition()) {
return false;
}

// 创建了 InputDefinition , 则使用它的信息(此时不会再解析和使用命令的注释)
$help = $definition->getSynopsis();
$help['usage:'] = \sprintf('%s %s %s', $this->getScriptName(), $this->getCommandName(), $help['usage:']);
$help['global options:'] = FormatUtil::alignOptions(Application::getInternalOptions());

if (empty($help[0]) && $this->isAlone()) {
$help[0] = self::getDescription();
}

$this->output->mList($help, ['sepChar' => ' ']);
return true;
}

/**
* prepare run
* @throws \InvalidArgumentException
* @throws \RuntimeException
*/
protected function prepare(): bool
{
if ($this->processTitle) {
if ($this->processTitle && 'Darwin' !== \PHP_OS) {
if (\function_exists('cli_set_process_title')) {
if (false === @cli_set_process_title($this->processTitle)) {
$error = \error_get_last();

if ($error && 'Darwin' !== PHP_OS) {
throw new \RuntimeException($error['message']);
}
}
\cli_set_process_title($this->processTitle);
} elseif (\function_exists('setproctitle')) {
\setproctitle($this->processTitle);
}

if ($error = \error_get_last()) {
throw new \RuntimeException($error['message']);
}
}

return $this->validateInput();
Expand Down Expand Up @@ -379,7 +364,8 @@ public function validateInput(): bool

if (\count($missingOpts) > 0) {
$out->liteError(
\sprintf('Not enough options parameters (missing: "%s").', \implode(', ', $missingOpts))
\sprintf('Not enough options parameters (missing: "%s").',
\implode(', ', $missingOpts))
);

return false;
Expand Down Expand Up @@ -458,12 +444,39 @@ public function isAlone(): bool
return $this instanceof CommandInterface;
}

/**********************************************************
* display help information
**********************************************************/

/**
* display help information
* @return bool
*/
public function isDebug(): bool
protected function showHelp(): bool
{
return $this->input->boolOpt('debug');
if (!$definition = $this->getDefinition()) {
return false;
}

// 创建了 InputDefinition , 则使用它的信息(此时不会再解析和使用命令的注释)
$help = $definition->getSynopsis();
$help['usage:'] = \sprintf('%s %s %s', $this->getScriptName(), $this->getCommandName(), $help['usage:']);
$help['global options:'] = FormatUtil::alignOptions(Application::getInternalOptions());

if (empty($help[0]) && $this->isAlone()) {
$help[0] = self::getDescription();
}

if (empty($help[0])) {
$help[0] = 'No description message for the command';
}

// output description
$this->write(\ucfirst($help[0]) . \PHP_EOL);
unset($help[0]);

$this->output->mList($help, ['sepChar' => ' ']);
return true;
}

/**
Expand Down Expand Up @@ -497,7 +510,7 @@ protected function showHelpByMethodAnnotations(string $method, string $action =

if ($aliases) {
$realName = $action ?: self::getName();
$help['Command:'] = sprintf('%s(alias: <info>%s</info>)', $realName, implode(',', $aliases));
$help['Command:'] = \sprintf('%s(alias: <info>%s</info>)', $realName, \implode(',', $aliases));
}

foreach (\array_keys(self::$annotationTags) as $tag) {
Expand Down Expand Up @@ -531,11 +544,11 @@ protected function showHelpByMethodAnnotations(string $method, string $action =

if (isset($help['Description:'])) {
$description = $help['Description:'] ?: 'No description message for the command';
$this->write(ucfirst($description) . PHP_EOL);
$this->write(\ucfirst($description) . \PHP_EOL);
unset($help['Description:']);
}

$help['Global Options:'] = FormatUtil::alignOptions(\array_merge(Application::getInternalOptions(), static::$commandOptions));
$help['Global Options:'] = FormatUtil::alignOptions(\array_merge(Application::getInternalOptions(), $this->commonOptions));

$this->output->mList($help, [
'sepChar' => ' ',
Expand Down Expand Up @@ -640,6 +653,14 @@ public function setDefinition(InputDefinition $definition)
$this->definition = $definition;
}

/**
* @return array
*/
public function getCommonOptions(): array
{
return $this->commonOptions;
}

/**
* @return array
*/
Expand Down
2 changes: 1 addition & 1 deletion src/BuiltIn/ErrorHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public function handle(\Throwable $e, AbstractApplication $app)
\n<error> Error </error> <mga>%s</mga>
At File <cyan>%s</cyan> line <bold>%d</bold>
Exception $class
Exception class is <magenta>$class</magenta>
<comment>Code View:</comment>\n\n%s
<comment>Code Trace:</comment>\n\n%s\n
ERR;
Expand Down
2 changes: 1 addition & 1 deletion src/Components/Style/Color.php
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ public function toStyle(): string
$values[] = static::$knownOptions[$option];
}

return implode(';', $values);
return \implode(';', $values);
}

/**
Expand Down
28 changes: 12 additions & 16 deletions src/Components/Style/Style.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,11 +93,7 @@ public static function create(): Style
public function __construct($fg = '', $bg = '', array $options = [])
{
if ($fg || $bg || $options) {
$this->add('base', [
'fg' => $fg,
'bg' => $bg,
'options' => $options
]);
$this->add('base', $fg, $bg, $options);
}

$this->loadDefaultStyles();
Expand All @@ -112,7 +108,7 @@ public function __construct($fg = '', $bg = '', array $options = [])
public function __call($method, array $args)
{
if (isset($args[0]) && $this->hasStyle($method)) {
return $this->format(sprintf('<%s>%s</%s>', $method, $args[0], $method));
return $this->format(\sprintf('<%s>%s</%s>', $method, $args[0], $method));
}

throw new \InvalidArgumentException("You called method is not exists: $method");
Expand All @@ -138,7 +134,7 @@ protected function loadDefaultStyles()
->add(self::COMMENT, ['fg' => 'yellow',])//'options' => ['bold']
->add(self::QUESTION, ['fg' => 'black', 'bg' => 'cyan'])
->add(self::DANGER, ['fg' => 'red',])// 'bg' => 'magenta', 'options' => ['bold']
->add(self::ERROR, ['fg' => 'black', 'bg' => 'red'])
->add(self::ERROR, ['fg' => 'white', 'bg' => 'red', 'options' => ['bold']])
->add('underline', ['fg' => 'normal', 'options' => ['underscore']])
->add('blue', ['fg' => 'blue'])
->add('cyan', ['fg' => 'cyan'])
Expand Down Expand Up @@ -176,7 +172,7 @@ public function render($text)
*/
public function format(string $text)
{
if (!$text || false === strpos($text, '<')) {
if (!$text || false === \strpos($text, '</')) {
return $text;
}

Expand All @@ -192,11 +188,11 @@ public function format(string $text)
foreach ((array)$matches[0] as $i => $m) {
$key = $matches[1][$i];

if (array_key_exists($key, $this->styles)) {
if (\array_key_exists($key, $this->styles)) {
$text = $this->replaceColor($text, $key, $matches[2][$i], (string)$this->styles[$key]);

/** Custom style format @see Color::makeByString() */
} elseif (strpos($key, '=')) {
} elseif (\strpos($key, '=')) {
$text = $this->replaceColor($text, $key, $matches[2][$i], (string)Color::makeByString($key));
}
}
Expand All @@ -216,7 +212,7 @@ protected function replaceColor($text, $tag, $match, $style): string
{
$replace = self::$noColor ? $match : sprintf("\033[%sm%s\033[0m", $style, $match);

return str_replace("<$tag>$match</$tag>", $replace, $text);
return \str_replace("<$tag>$match</$tag>", $replace, $text);
// return sprintf("\033[%sm%s\033[%sm", implode(';', $setCodes), $text, implode(';', $unsetCodes));
}

Expand All @@ -228,7 +224,7 @@ protected function replaceColor($text, $tag, $match, $style): string
public static function stripColor(string $string)
{
// $text = strip_tags($text);
return preg_replace(self::STRIP_TAG, '', $string);
return \preg_replace(self::STRIP_TAG, '', $string);
}

/****************************************************************************
Expand Down Expand Up @@ -282,8 +278,8 @@ public function addByArray(string $name, array $styleConfig): self
'options' => []
];

$config = array_merge($style, $styleConfig);
list($fg, $bg, $extra, $options) = array_values($config);
$config = \array_merge($style, $styleConfig);
list($fg, $bg, $extra, $options) = \array_values($config);

$this->styles[$name] = Color::make($fg, $bg, $options, $extra);

Expand All @@ -295,15 +291,15 @@ public function addByArray(string $name, array $styleConfig): self
*/
public function getStyleNames(): array
{
return array_keys($this->styles);
return \array_keys($this->styles);
}

/**
* @return array
*/
public function getNames(): array
{
return array_keys($this->styles);
return \array_keys($this->styles);
}

/**
Expand Down
Loading

0 comments on commit d4b73b5

Please sign in to comment.