From 30eb0f129bb4fb798dcc586139309a3f70595704 Mon Sep 17 00:00:00 2001 From: inhere Date: Mon, 24 Jun 2019 21:46:27 +0800 Subject: [PATCH] inspact and reformat codes --- libs/autoload.php | 1 - libs/cli-utils/example/down.php | 3 +- libs/cli-utils/example/high.php | 3 +- libs/cli-utils/src/App.php | 88 ++++++++++------- libs/cli-utils/src/Cli.php | 102 ++++++++++++-------- libs/cli-utils/src/Color.php | 55 +++++++---- libs/cli-utils/src/ColorTag.php | 26 +++++- libs/cli-utils/src/Download.php | 85 +++++++++++------ libs/cli-utils/src/Flags.php | 92 +++++++++++------- libs/cli-utils/src/Highlighter.php | 135 ++++++++++++++++++--------- libs/cli-utils/src/Terminal.php | 18 +++- libs/cli-utils/test/ColorTagTest.php | 1 + libs/cli-utils/test/ColorTest.php | 1 + 13 files changed, 408 insertions(+), 202 deletions(-) diff --git a/libs/autoload.php b/libs/autoload.php index 3084d72..a0127c9 100644 --- a/libs/autoload.php +++ b/libs/autoload.php @@ -35,7 +35,6 @@ ]; spl_autoload_register(function ($class) use ($map) { - $file = null; foreach ($map as $np => $dir) { if (0 === strpos($class, $np)) { $path = str_replace('\\', '/', substr($class, strlen($np))); diff --git a/libs/cli-utils/example/down.php b/libs/cli-utils/example/down.php index 271c5e0..094fe5b 100644 --- a/libs/cli-utils/example/down.php +++ b/libs/cli-utils/example/down.php @@ -3,11 +3,12 @@ * demo for cli download file. */ +use Toolkit\Cli\App; use Toolkit\Cli\Download; require dirname(__DIR__) . '/test/boot.php'; -$app = new \Toolkit\Cli\App(); +$app = new App(); $url = 'http://no2.php.net/distributions/php-7.2.5.tar.bz2'; $down = Download::create($url); diff --git a/libs/cli-utils/example/high.php b/libs/cli-utils/example/high.php index a45af21..ae5b5a5 100644 --- a/libs/cli-utils/example/high.php +++ b/libs/cli-utils/example/high.php @@ -6,6 +6,7 @@ * Time: 下午3:13 */ +use Toolkit\Cli\Cli; use Toolkit\Cli\Highlighter; require dirname(__DIR__) . '/test/boot.php'; @@ -15,4 +16,4 @@ // this is an comment $rendered = Highlighter::create()->highlight(file_get_contents(__FILE__)); -\Toolkit\Cli\Cli::write($rendered); +Cli::write($rendered); diff --git a/libs/cli-utils/src/App.php b/libs/cli-utils/src/App.php index f44ca26..9f2af10 100644 --- a/libs/cli-utils/src/App.php +++ b/libs/cli-utils/src/App.php @@ -8,8 +8,23 @@ namespace Toolkit\Cli; +use InvalidArgumentException; +use Throwable; +use function array_shift; +use function array_values; +use function class_exists; +use function function_exists; +use function getcwd; +use function is_array; +use function is_string; +use function method_exists; +use function str_pad; +use function strlen; +use function trim; + /** * Class App - A lite CLI Application + * * @package Inhere\Console */ class App @@ -27,10 +42,14 @@ class App */ private $opts = []; - /** @var string */ + /** + * @var string + */ private $script; - /** @var string */ + /** + * @var string + */ private $command = ''; /** @@ -50,24 +69,26 @@ class App /** * Class constructor. + * * @param array|null $argv */ public function __construct(array $argv = null) { // get current dir - $this->pwd = \getcwd(); + $this->pwd = getcwd(); // parse cli argv $argv = $argv ?? (array)$_SERVER['argv']; // get script file - $this->script = \array_shift($argv); + $this->script = array_shift($argv); // parse flags - [$this->args, $this->opts] = Flags::simpleParseArgv($argv); + [$this->args, $this->opts] = Flags::parseArgv($argv); } /** * @param bool $exit - * @throws \InvalidArgumentException + * + * @throws InvalidArgumentException */ public function run(bool $exit = true): void { @@ -81,7 +102,8 @@ public function run(bool $exit = true): void /** * @param bool $exit - * @throws \InvalidArgumentException + * + * @throws InvalidArgumentException */ public function dispatch(bool $exit = true): void { @@ -98,7 +120,7 @@ public function dispatch(bool $exit = true): void } else { $this->displayHelp("The command {$command} not exists!"); } - } catch (\Throwable $e) { + } catch (Throwable $e) { $status = $this->handleException($e); } @@ -118,51 +140,47 @@ public function stop($code = 0): void /** * @param string $command * @param $handler + * * @return mixed - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ public function runHandler(string $command, $handler) { - if (\is_string($handler)) { + if (is_string($handler)) { // function name - if (\function_exists($handler)) { + if (function_exists($handler)) { return $handler($this); } - if (\class_exists($handler)) { + if (class_exists($handler)) { $handler = new $handler; // $handler->execute() - if (\method_exists($handler, 'execute')) { + if (method_exists($handler, 'execute')) { return $handler->execute($this); } } } // a \Closure OR $handler->__invoke() - if (\method_exists($handler, '__invoke')) { + if (method_exists($handler, '__invoke')) { return $handler($this); } - throw new \InvalidArgumentException("Invalid handler of the command: $command"); + throw new InvalidArgumentException("Invalid handler of the command: $command"); } /** - * @param \Throwable $e + * @param Throwable $e + * * @return int */ - protected function handleException(\Throwable $e): int + protected function handleException(Throwable $e): int { $code = $e->getCode() !== 0 ? $e->getCode() : 133; - printf( - "Exception(%d): %s\nFile: %s(Line %d)\nTrace:\n%s\n", - $code, - $e->getMessage(), - $e->getFile(), - $e->getLine(), - $e->getTraceAsString() - ); + printf("Exception(%d): %s\nFile: %s(Line %d)\nTrace:\n%s\n", $code, $e->getMessage(), $e->getFile(), + $e->getLine(), $e->getTraceAsString()); return $code; } @@ -171,33 +189,35 @@ protected function handleException(\Throwable $e): int * @param string $command * @param callable $handler * @param string $description - * @throws \InvalidArgumentException + * + * @throws InvalidArgumentException */ public function addCommand(string $command, callable $handler, string $description = ''): void { if (!$command || !$handler) { - throw new \InvalidArgumentException('Invalid arguments'); + throw new InvalidArgumentException('Invalid arguments'); } - if (($len = \strlen($command)) > $this->keyWidth) { + if (($len = strlen($command)) > $this->keyWidth) { $this->keyWidth = $len; } $this->commands[$command] = $handler; - $this->messages[$command] = \trim($description); + $this->messages[$command] = trim($description); } /** * @param array $commands - * @throws \InvalidArgumentException + * + * @throws InvalidArgumentException */ public function commands(array $commands): void { foreach ($commands as $command => $handler) { $des = ''; - if (\is_array($handler)) { - $conf = \array_values($handler); + if (is_array($handler)) { + $conf = array_values($handler); $handler = $conf[0]; $des = $conf[1] ?? ''; } @@ -224,7 +244,7 @@ public function displayHelp(string $err = ''): void $help = "Welcome to the Lite Console Application.\n\nAvailable Commands:\n"; foreach ($this->messages as $command => $desc) { - $command = \str_pad($command, $commandWidth, ' '); + $command = str_pad($command, $commandWidth, ' '); $desc = $desc ?: 'No description for the command'; $help .= " $command $desc\n"; } @@ -236,6 +256,7 @@ public function displayHelp(string $err = ''): void /** * @param string|int $name * @param mixed $default + * * @return mixed|null */ public function getArg($name, $default = null) @@ -246,6 +267,7 @@ public function getArg($name, $default = null) /** * @param string $name * @param mixed $default + * * @return mixed|null */ public function getOpt(string $name, $default = null) diff --git a/libs/cli-utils/src/Cli.php b/libs/cli-utils/src/Cli.php index 586a82a..1e0d88c 100644 --- a/libs/cli-utils/src/Cli.php +++ b/libs/cli-utils/src/Cli.php @@ -8,10 +8,37 @@ namespace Toolkit\Cli; +use function date; +use function defined; +use function fflush; +use function fgets; +use function function_exists; +use function fwrite; use function getenv; +use function implode; +use function is_array; +use function is_int; +use function is_numeric; +use function json_encode; +use function preg_replace; +use function sprintf; +use function strpos; +use function strtoupper; +use function trim; +use const DIRECTORY_SEPARATOR; +use const JSON_PRETTY_PRINT; +use const JSON_UNESCAPED_SLASHES; +use const PHP_EOL; +use const PHP_WINDOWS_VERSION_BUILD; +use const PHP_WINDOWS_VERSION_MAJOR; +use const PHP_WINDOWS_VERSION_MINOR; +use const STDERR; +use const STDIN; +use const STDOUT; /** * Class Cli + * * @package Toolkit\Cli */ class Cli @@ -31,7 +58,8 @@ class Cli /** * @param string $message - * @param bool $nl + * @param bool $nl + * * @return string */ public static function read(string $message = '', bool $nl = false): string @@ -40,7 +68,7 @@ public static function read(string $message = '', bool $nl = false): string self::write($message, $nl); } - return \trim(\fgets(\STDIN)); + return trim(fgets(STDIN)); } /** @@ -49,19 +77,20 @@ public static function read(string $message = '', bool $nl = false): string */ public static function writef(string $format, ...$args): void { - self::write(\sprintf($format, ...$args)); + self::write(sprintf($format, ...$args)); } /** * Write message to console + * * @param string|array $messages * @param bool $nl * @param bool|int $quit */ public static function write($messages, bool $nl = true, $quit = false): void { - if (\is_array($messages)) { - $messages = \implode($nl ? \PHP_EOL : '', $messages); + if (is_array($messages)) { + $messages = implode($nl ? PHP_EOL : '', $messages); } self::stdout(Color::parseTag($messages), $nl, $quit); @@ -69,16 +98,17 @@ public static function write($messages, bool $nl = true, $quit = false): void /** * Logs data to stdout + * * @param string $message * @param bool $nl * @param bool|int $quit */ public static function stdout(string $message, bool $nl = true, $quit = false): void { - \fwrite(\STDOUT, $message . ($nl ? \PHP_EOL : '')); - \fflush(\STDOUT); + fwrite(STDOUT, $message . ($nl ? PHP_EOL : '')); + fflush(STDOUT); - if (($isTrue = true === $quit) || \is_int($quit)) { + if (($isTrue = true === $quit) || is_int($quit)) { $code = $isTrue ? 0 : $quit; exit($code); } @@ -86,16 +116,17 @@ public static function stdout(string $message, bool $nl = true, $quit = false): /** * Logs data to stderr + * * @param string $message * @param bool $nl * @param bool|int $quit */ public static function stderr(string $message, $nl = true, $quit = -1): void { - \fwrite(\STDERR, self::color('[ERROR] ', 'red') . $message . ($nl ? PHP_EOL : '')); - \fflush(\STDOUT); + fwrite(STDERR, self::color('[ERROR] ', 'red') . $message . ($nl ? PHP_EOL : '')); + fflush(STDOUT); - if (($isTrue = true === $quit) || \is_int($quit)) { + if (($isTrue = true === $quit) || is_int($quit)) { $code = $isTrue ? 0 : $quit; exit($code); } @@ -108,6 +139,7 @@ public static function stderr(string $message, $nl = true, $quit = -1): void /** * @param $text * @param string|int|array $style + * * @return string */ public static function color(string $text, $style = null): string @@ -117,43 +149,38 @@ public static function color(string $text, $style = null): string /** * print log to console + * * @param string $msg * @param array $data * @param string $type * @param array $opts - * [ + * [ * '_category' => 'application', * 'process' => 'work', * 'pid' => 234, * 'coId' => 12, - * ] + * ] */ public static function log(string $msg, array $data = [], string $type = 'info', array $opts = []): void { if (isset(self::LOG_LEVEL2TAG[$type])) { - $type = ColorTag::add(\strtoupper($type), self::LOG_LEVEL2TAG[$type]); + $type = ColorTag::add(strtoupper($type), self::LOG_LEVEL2TAG[$type]); } $userOpts = []; foreach ($opts as $n => $v) { - if (\is_numeric($n) || \strpos($n, '_') === 0) { + if (is_numeric($n) || strpos($n, '_') === 0) { $userOpts[] = "[$v]"; } else { $userOpts[] = "[$n:$v]"; } } - $optString = $userOpts ? ' ' . \implode(' ', $userOpts) : ''; + $optString = $userOpts ? ' ' . implode(' ', $userOpts) : ''; - self::write(\sprintf( - '%s [%s]%s %s %s', - \date('Y/m/d H:i:s'), - $type, - $optString, - \trim($msg), - $data ? \PHP_EOL . \json_encode($data, \JSON_UNESCAPED_SLASHES | \JSON_PRETTY_PRINT) : '' - )); + self::write(sprintf('%s [%s]%s %s %s', date('Y/m/d H:i:s'), $type, $optString, trim($msg), + $data ? PHP_EOL . json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) : '')); } /******************************************************************************* @@ -172,24 +199,21 @@ public static function supportColor(): bool * Returns true if STDOUT supports colorization. * This code has been copied and adapted from * \Symfony\Component\Console\Output\OutputStream. + * * @return boolean */ public static function isSupportColor(): bool { - if (\DIRECTORY_SEPARATOR === '\\') { - return - '10.0.10586' === \PHP_WINDOWS_VERSION_MAJOR . '.' . \PHP_WINDOWS_VERSION_MINOR . '.' . \PHP_WINDOWS_VERSION_BUILD - || false !== getenv('ANSICON') - || 'ON' === getenv('ConEmuANSI') - || 'xterm' === getenv('TERM')// || 'cygwin' === getenv('TERM') + if (DIRECTORY_SEPARATOR === '\\') { + return '10.0.10586' === PHP_WINDOWS_VERSION_MAJOR . '.' . PHP_WINDOWS_VERSION_MINOR . '.' . PHP_WINDOWS_VERSION_BUILD || false !== getenv('ANSICON') || 'ON' === getenv('ConEmuANSI') || 'xterm' === getenv('TERM')// || 'cygwin' === getenv('TERM') ; } - if (!\defined('STDOUT')) { + if (!defined('STDOUT')) { return false; } - return self::isInteractive(\STDOUT); + return self::isInteractive(STDOUT); } /** @@ -197,7 +221,7 @@ public static function isSupportColor(): bool */ public static function isSupport256Color(): bool { - return \DIRECTORY_SEPARATOR === '/' && strpos(getenv('TERM'), '256color') !== false; + return DIRECTORY_SEPARATOR === '/' && strpos(getenv('TERM'), '256color') !== false; } /** @@ -205,7 +229,7 @@ public static function isSupport256Color(): bool */ public static function isAnsiSupport(): bool { - if (\DIRECTORY_SEPARATOR === '\\') { + if (DIRECTORY_SEPARATOR === '\\') { return getenv('ANSICON') === true || getenv('ConEmuANSI') === 'ON'; } @@ -214,21 +238,25 @@ public static function isAnsiSupport(): bool /** * Returns if the file descriptor is an interactive terminal or not. - * @param int|resource $fileDescriptor + * + * @param int|resource $fileDescriptor + * * @return boolean */ public static function isInteractive($fileDescriptor): bool { - return \function_exists('posix_isatty') && @posix_isatty($fileDescriptor); + return function_exists('posix_isatty') && @posix_isatty($fileDescriptor); } /** * clear Ansi Code + * * @param string $string + * * @return string */ public static function stripAnsiCode(string $string): string { - return \preg_replace('/\033\[[\d;?]*\w/', '', $string); + return preg_replace('/\033\[[\d;?]*\w/', '', $string); } } diff --git a/libs/cli-utils/src/Color.php b/libs/cli-utils/src/Color.php index 18246f5..2269f2e 100644 --- a/libs/cli-utils/src/Color.php +++ b/libs/cli-utils/src/Color.php @@ -8,8 +8,21 @@ namespace Toolkit\Cli; +use function array_filter; +use function array_keys; +use function implode; +use function is_array; +use function is_string; +use function preg_match_all; +use function preg_replace; +use function sprintf; +use function str_replace; +use function strip_tags; +use function strpos; + /** * Class Color + * * @package Toolkit\Cli * // basic * @method string red(string $text) @@ -89,6 +102,7 @@ class Color /** * some styles * custom style: fg;bg;opt + * * @var array */ public const STYLES = [ @@ -163,6 +177,7 @@ class Color /** * @param string $method * @param array $args + * * @return string */ public static function __callStatic(string $method, array $args) @@ -176,8 +191,10 @@ public static function __callStatic(string $method, array $args) /** * Apply style for text + * * @param string $style * @param string $text + * * @return string */ public static function apply(string $style, string $text): string @@ -187,12 +204,13 @@ public static function apply(string $style, string $text): string /** * Format and print to STDOUT + * * @param string $format * @param mixed ...$args */ public static function printf(string $format, ...$args): void { - echo self::render(\sprintf($format, ...$args)); + echo self::render(sprintf($format, ...$args)); } /******************************************************************************* @@ -201,10 +219,12 @@ public static function printf(string $format, ...$args): void /** * Render text, apply color code + * * @param string $text * @param string|array $style * - string: 'green', 'blue' * - array: [Color::FG_GREEN, Color::BG_WHITE, Color::UNDERSCORE] + * * @return string */ public static function render(string $text, $style = null): string @@ -218,31 +238,33 @@ public static function render(string $text, $style = null): string } // use defined style: 'green' - if (\is_string($style)) { + if (is_string($style)) { $color = self::STYLES[$style] ?? '0'; // custom style: [self::FG_GREEN, self::BG_WHITE, self::UNDERSCORE] - } elseif (\is_array($style)) { - $color = \implode(';', $style); + } elseif (is_array($style)) { + $color = implode(';', $style); // user color tag: message - } elseif (\strpos($text, ' 0) { + } elseif (strpos($text, ' 0) { return self::parseTag($text); } else { return $text; } // $result = chr(27). "$color{$text}" . chr(27) . chr(27) . "[0m". chr(27); - return \sprintf(self::COLOR_TPL, $color, $text); + return sprintf(self::COLOR_TPL, $color, $text); } /** * parse color tag e.g: message + * * @param string $text + * * @return mixed|string */ public static function parseTag(string $text) { - if (!$text || false === \strpos($text, '$match", $repl, $text); + $repl = sprintf("\033[%sm%s\033[0m", $style, $match); + $text = str_replace("<$tag>$match", $repl, $text); } } @@ -271,20 +293,18 @@ public static function parseTag(string $text) /** * @param string $text * @param bool $stripTag + * * @return string */ public static function clearColor(string $text, bool $stripTag = true): string { // return preg_replace('/\033\[(?:\d;?)+m/', '' , "\033[0;36mtext\033[0m"); - return \preg_replace( - '/\033\[(?:\d;?)+m/', - '', - $stripTag ? \strip_tags($text) : $text - ); + return preg_replace('/\033\[(?:\d;?)+m/', '', $stripTag ? strip_tags($text) : $text); } /** * @param string $style + * * @return bool */ public static function hasStyle(string $style): bool @@ -294,12 +314,13 @@ public static function hasStyle(string $style): bool /** * get all style names + * * @return array */ public static function getStyles(): array { - return \array_filter(\array_keys(self::STYLES), function ($style) { - return !\strpos($style, '_'); + return array_filter(array_keys(self::STYLES), function ($style) { + return !strpos($style, '_'); }); } } diff --git a/libs/cli-utils/src/ColorTag.php b/libs/cli-utils/src/ColorTag.php index ed10cc5..bc6f6c1 100644 --- a/libs/cli-utils/src/ColorTag.php +++ b/libs/cli-utils/src/ColorTag.php @@ -8,8 +8,13 @@ namespace Toolkit\Cli; +use function preg_match_all; +use function preg_replace; +use function strpos; + /** * Class ColorTag + * * @package Toolkit\Cli */ class ColorTag @@ -22,8 +27,10 @@ class ColorTag /** * Alias of the wrap() + * * @param string $text * @param string $tag + * * @return string */ public static function add(string $text, string $tag): string @@ -33,8 +40,10 @@ public static function add(string $text, string $tag): string /** * wrap a color style tag + * * @param string $text * @param string $tag + * * @return string */ public static function wrap(string $text, string $tag): string @@ -48,11 +57,12 @@ public static function wrap(string $text, string $tag): string /** * @param string $text + * * @return array */ public static function matchAll(string $text): array { - if (!\preg_match_all(self::MATCH_TAG, $text, $matches)) { + if (!preg_match_all(self::MATCH_TAG, $text, $matches)) { return []; } @@ -61,22 +71,26 @@ public static function matchAll(string $text): array public static function parse(string $text): string { - + return ''; } /** * Exists color tags + * * @param string $text + * * @return bool */ public static function exists(string $text): bool { - return \strpos($text, ' 0; + return strpos($text, ' 0; } /** * Alias of the strip() + * * @param string $text + * * @return string */ public static function clear(string $text): string @@ -86,16 +100,18 @@ public static function clear(string $text): string /** * Strip color tags from a string. + * * @param string $text + * * @return mixed */ public static function strip(string $text): string { - if (false === \strpos($text, ' + * * @param string $url * @param string $saveAs * @param string $type + * * @return Download - * @throws \RuntimeException + * @throws RuntimeException */ public static function file(string $url, string $saveAs = '', string $type = self::PROGRESS_TEXT): Download { @@ -57,6 +83,7 @@ public static function file(string $url, string $saveAs = '', string $type = sel /** * Download constructor. + * * @param string $url * @param string $saveAs * @param string $type @@ -71,43 +98,44 @@ public function __construct(string $url, string $saveAs = '', $type = self::PROG /** * start download + * * @return $this - * @throws \RuntimeException + * @throws RuntimeException */ public function start(): self { if (!$this->url) { - throw new \RuntimeException("Please the property 'url' and 'saveAs'.", -1); + throw new RuntimeException("Please the property 'url' and 'saveAs'.", -1); } // default save to current dir. if (!$save = $this->saveAs) { - $save = \getcwd() . '/' . \basename($this->url); + $save = getcwd() . '/' . basename($this->url); // reset $this->saveAs = $save; } - $ctx = \stream_context_create(); + $ctx = stream_context_create(); // register stream notification callback - \stream_context_set_params($ctx, [ + stream_context_set_params($ctx, [ 'notification' => [$this, 'progressShow'] ]); Cli::write("Download: {$this->url}\nSave As: {$save}\n"); - $fp = \fopen($this->url, 'rb', false, $ctx); + $fp = fopen($this->url, 'rb', false, $ctx); - if (\is_resource($fp) && \file_put_contents($save, $fp)) { + if (is_resource($fp) && file_put_contents($save, $fp)) { Cli::write("\nDone!"); } else { - $err = \error_get_last(); + $err = error_get_last(); Cli::stderr("\nErr.rrr..orr...\n {$err['message']}\n", true, -1); } // close resource - if (\is_resource($fp)) { - \fclose($fp); + if (is_resource($fp)) { + fclose($fp); } $this->fileSize = null; @@ -115,47 +143,47 @@ public function start(): self } /** - * @param int $notifyCode stream notify code - * @param int $severity severity code - * @param string $message Message text - * @param int $messageCode Message code + * @param int $notifyCode stream notify code + * @param int $severity severity code + * @param string $message Message text + * @param int $messageCode Message code * @param int $transferredBytes Have been transferred bytes - * @param int $maxBytes Target max length bytes + * @param int $maxBytes Target max length bytes */ public function progressShow($notifyCode, $severity, $message, $messageCode, $transferredBytes, $maxBytes): void { $msg = ''; switch ($notifyCode) { - case \STREAM_NOTIFY_RESOLVE: - case \STREAM_NOTIFY_AUTH_REQUIRED: - case \STREAM_NOTIFY_COMPLETED: - case \STREAM_NOTIFY_FAILURE: - case \STREAM_NOTIFY_AUTH_RESULT: + case STREAM_NOTIFY_RESOLVE: + case STREAM_NOTIFY_AUTH_REQUIRED: + case STREAM_NOTIFY_COMPLETED: + case STREAM_NOTIFY_FAILURE: + case STREAM_NOTIFY_AUTH_RESULT: $msg = "NOTIFY: $message(NO: $messageCode, Severity: $severity)"; /* Ignore */ break; - case \STREAM_NOTIFY_REDIRECTED: + case STREAM_NOTIFY_REDIRECTED: $msg = "Being redirected to: $message"; break; - case \STREAM_NOTIFY_CONNECT: + case STREAM_NOTIFY_CONNECT: $msg = 'Connected ...'; break; - case \STREAM_NOTIFY_FILE_SIZE_IS: + case STREAM_NOTIFY_FILE_SIZE_IS: $this->fileSize = $maxBytes; // print size $size = sprintf('%2d', $maxBytes / 1024); $msg = "Got the file size: $size kb"; break; - case \STREAM_NOTIFY_MIME_TYPE_IS: + case STREAM_NOTIFY_MIME_TYPE_IS: $msg = "Found the mime-type: $message"; break; - case \STREAM_NOTIFY_PROGRESS: + case STREAM_NOTIFY_PROGRESS: if ($transferredBytes > 0) { $this->showProgressByType($transferredBytes); } @@ -167,6 +195,7 @@ public function progressShow($notifyCode, $severity, $message, $messageCode, $tr /** * @param $transferredBytes + * * @return string */ public function showProgressByType($transferredBytes): string @@ -223,7 +252,7 @@ public function getUrl(): string */ public function setUrl(string $url): void { - $this->url = \trim($url); + $this->url = trim($url); } /** @@ -239,6 +268,6 @@ public function getSaveAs(): string */ public function setSaveAs(string $saveAs): void { - $this->saveAs = \trim($saveAs); + $this->saveAs = trim($saveAs); } } diff --git a/libs/cli-utils/src/Flags.php b/libs/cli-utils/src/Flags.php index 0f4be6a..e5631fc 100644 --- a/libs/cli-utils/src/Flags.php +++ b/libs/cli-utils/src/Flags.php @@ -8,8 +8,25 @@ namespace Toolkit\Cli; +use function array_flip; +use function array_merge; +use function current; +use function escapeshellarg; +use function explode; +use function is_bool; +use function is_int; +use function is_numeric; +use function next; +use function preg_match; +use function str_split; +use function stripos; +use function strpos; +use function substr; +use function trim; + /** * Class FlagsParse - console argument and option parse + * * @package Toolkit\Cli */ class Flags @@ -20,6 +37,7 @@ class Flags /** * @param array $argv + * * @return array [$args, $opts] */ public static function simpleParseArgv(array $argv): array @@ -27,22 +45,22 @@ public static function simpleParseArgv(array $argv): array $args = $opts = []; foreach ($argv as $key => $value) { // opts - if (\strpos($value, '-') === 0) { - $value = \trim($value, '-'); + if (strpos($value, '-') === 0) { + $value = trim($value, '-'); // invalid if (!$value) { continue; } - if (\strpos($value, '=')) { - [$n, $v] = \explode('=', $value); + if (strpos($value, '=')) { + [$n, $v] = explode('=', $value); $opts[$n] = $v; } else { $opts[$value] = true; } - } elseif (\strpos($value, '=')) { - [$n, $v] = \explode('=', $value); + } elseif (strpos($value, '=')) { + [$n, $v] = explode('=', $value); $args[$n] = $v; } else { $args[] = $value; @@ -77,9 +95,12 @@ public static function simpleParseArgv(array $argv): array * --long-opt * --long-opt * --long-opt= + * * @link http://php.net/manual/zh/function.getopt.php#83414 + * * @param array $params * @param array $config + * * @return array [args, short-opts, long-opts] */ public static function parseArgv(array $params, array $config = []): array @@ -88,7 +109,7 @@ public static function parseArgv(array $params, array $config = []): array return [[], [], []]; } - $config = \array_merge([ + $config = array_merge([ // List of parameters without values(bool option keys) 'boolOpts' => [], // ['debug', 'h'] // Whether merge short-opts and long-opts @@ -101,47 +122,47 @@ public static function parseArgv(array $params, array $config = []): array $args = $sOpts = $lOpts = []; // config - $boolOpts = \array_flip((array)$config['boolOpts']); - $arrayOpts = \array_flip((array)$config['arrayOpts']); + $boolOpts = array_flip((array)$config['boolOpts']); + $arrayOpts = array_flip((array)$config['arrayOpts']); // each() will deprecated at 7.2. so,there use current and next instead it. // while (list(,$p) = each($params)) { - while (false !== ($p = \current($params))) { - \next($params); + while (false !== ($p = current($params))) { + next($params); // is options if ($p{0} === '-') { $value = true; - $option = \substr($p, 1); + $option = substr($p, 1); $isLong = false; // long-opt: (--) - if (\strpos($option, '-') === 0) { - $option = \substr($option, 1); + if (strpos($option, '-') === 0) { + $option = substr($option, 1); $isLong = true; // long-opt: value specified inline (--=) - if (\strpos($option, '=') !== false) { - [$option, $value] = \explode('=', $option, 2); + if (strpos($option, '=') !== false) { + [$option, $value] = explode('=', $option, 2); } // short-opt: value specified inline (-=) } elseif (isset($option{1}) && $option{1} === '=') { - [$option, $value] = \explode('=', $option, 2); + [$option, $value] = explode('=', $option, 2); } // check if next parameter is a descriptor or a value - $nxt = \current($params); + $nxt = current($params); // next elem is value. fix: allow empty string '' if ($value === true && !isset($boolOpts[$option]) && self::nextIsValue($nxt)) { // list(,$val) = each($params); $value = $nxt; - \next($params); + next($params); // short-opt: bool opts. like -e -abc } elseif (!$isLong && $value === true) { - foreach (\str_split($option) as $char) { + foreach (str_split($option) as $char) { $sOpts[$char] = true; } continue; @@ -169,8 +190,8 @@ public static function parseArgv(array $params, array $config = []): array // - param doesn't belong to any option, define it is args // value specified inline (=) - if (\strpos($p, '=') !== false) { - [$name, $value] = \explode('=', $p, 2); + if (strpos($p, '=') !== false) { + [$name, $value] = explode('=', $p, 2); $args[$name] = self::filterBool($value); } else { $args[] = $p; @@ -190,7 +211,9 @@ public static function parseArgv(array $params, array $config = []): array * '-h' => true, * ]); * ``` + * * @param array $params + * * @return array */ public static function parseArray(array $params): array @@ -198,21 +221,21 @@ public static function parseArray(array $params): array $args = $sOpts = $lOpts = []; foreach ($params as $key => $val) { - if (\is_int($key)) { // as argument + if (is_int($key)) { // as argument $args[$key] = $val; continue; } - $cleanKey = \trim((string)$key, '-'); + $cleanKey = trim((string)$key, '-'); if ('' === $cleanKey) { // as argument $args[] = $val; continue; } - if (0 === \strpos($key, '--')) { // long option + if (0 === strpos($key, '--')) { // long option $lOpts[$cleanKey] = $val; - } elseif (0 === \strpos($key, '-')) { // short option + } elseif (0 === strpos($key, '-')) { // short option $sOpts[$cleanKey] = $val; } else { $args[$key] = $val; @@ -229,8 +252,9 @@ public static function parseArray(array $params): array * $result = Flags::parseString('foo --bar="foobar"'); * ``` * - * @todo ... * @param string $string + * + * @todo ... */ public static function parseString(string $string): void { @@ -240,21 +264,22 @@ public static function parseString(string $string): void /** * @param string|bool $val * @param bool $enable + * * @return bool|mixed */ public static function filterBool($val, $enable = true) { if ($enable) { - if (\is_bool($val) || \is_numeric($val)) { + if (is_bool($val) || is_numeric($val)) { return $val; } // check it is a bool value. - if (false !== \stripos(self::TRUE_WORDS, "|$val|")) { + if (false !== stripos(self::TRUE_WORDS, "|$val|")) { return true; } - if (false !== \stripos(self::FALSE_WORDS, "|$val|")) { + if (false !== stripos(self::FALSE_WORDS, "|$val|")) { return false; } } @@ -264,6 +289,7 @@ public static function filterBool($val, $enable = true) /** * @param mixed $val + * * @return bool */ public static function nextIsValue($val): bool @@ -279,16 +305,18 @@ public static function nextIsValue($val): bool } // it isn't option or named argument - return $val{0} !== '-' && false === \strpos($val, '='); + return $val{0} !== '-' && false === strpos($val, '='); } /** * Escapes a token through escapeshellarg if it contains unsafe chars. + * * @param string $token + * * @return string */ public static function escapeToken(string $token): string { - return \preg_match('{^[\w-]+$}', $token) ? $token : \escapeshellarg($token); + return preg_match('{^[\w-]+$}', $token) ? $token : escapeshellarg($token); } } diff --git a/libs/cli-utils/src/Highlighter.php b/libs/cli-utils/src/Highlighter.php index dc166f8..8100f1e 100644 --- a/libs/cli-utils/src/Highlighter.php +++ b/libs/cli-utils/src/Highlighter.php @@ -8,11 +8,51 @@ namespace Toolkit\Cli; +use InvalidArgumentException; +use function array_merge; +use function array_slice; +use function defined; +use function end; +use function explode; +use function function_exists; +use function implode; +use function is_array; +use function key; +use function max; +use function str_pad; +use function str_replace; +use function strlen; +use function token_get_all; +use const PHP_EOL; +use const STR_PAD_LEFT; +use const T_CLASS_C; +use const T_CLOSE_TAG; +use const T_COMMENT; +use const T_CONSTANT_ENCAPSED_STRING; +use const T_DIR; +use const T_DNUMBER; +use const T_DOC_COMMENT; +use const T_ENCAPSED_AND_WHITESPACE; +use const T_FILE; +use const T_FUNC_C; +use const T_INLINE_HTML; +use const T_LINE; +use const T_LNUMBER; +use const T_METHOD_C; +use const T_NS_C; +use const T_OPEN_TAG; +use const T_OPEN_TAG_WITH_ECHO; +use const T_STRING; +use const T_TRAIT_C; +use const T_VARIABLE; +use const T_WHITESPACE; + /** * Class Highlighter + * * @package Toolkit\Cli - * @see jakub-onderka/php-console-highlighter - * @link https://github.com/JakubOnderka/PHP-Console-Highlighter/blob/master/src/Highlighter.php + * @see jakub-onderka/php-console-highlighter + * @link https://github.com/JakubOnderka/PHP-Console-Highlighter/blob/master/src/Highlighter.php */ class Highlighter { @@ -59,13 +99,15 @@ public static function create(): self public function __construct() { - $this->hasTokenFunc = \function_exists('token_get_all'); + $this->hasTokenFunc = function_exists('token_get_all'); } /** * highlight a full php file content + * * @param string $source * @param bool $withLineNumber with line number + * * @return string */ public function highlight(string $source, bool $withLineNumber = false): string @@ -77,7 +119,7 @@ public function highlight(string $source, bool $withLineNumber = false): string return $this->lineNumbers($lines); } - return \implode(\PHP_EOL, $lines); + return implode(PHP_EOL, $lines); } /** @@ -85,8 +127,9 @@ public function highlight(string $source, bool $withLineNumber = false): string * @param int $lineNumber * @param int $linesBefore * @param int $linesAfter + * * @return string - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ public function snippet(string $source, int $lineNumber, int $linesBefore = 2, int $linesAfter = 2): string { @@ -98,17 +141,18 @@ public function snippet(string $source, int $lineNumber, int $linesBefore = 2, i * @param int $lineNumber * @param int $linesBefore * @param int $linesAfter + * * @return string - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ public function highlightSnippet($source, $lineNumber, $linesBefore = 2, $linesAfter = 2): string { $tokenLines = $this->getHighlightedLines($source); $offset = $lineNumber - $linesBefore - 1; - $offset = \max($offset, 0); + $offset = max($offset, 0); $length = $linesAfter + $linesBefore + 1; - $tokenLines = \array_slice($tokenLines, $offset, $length, $preserveKeys = true); + $tokenLines = array_slice($tokenLines, $offset, $length, $preserveKeys = true); $lines = $this->colorLines($tokenLines); @@ -117,11 +161,12 @@ public function highlightSnippet($source, $lineNumber, $linesBefore = 2, $linesA /** * @param string $source + * * @return array */ private function getHighlightedLines(string $source): array { - $source = \str_replace(["\r\n", "\r"], "\n", $source); + $source = str_replace(["\r\n", "\r"], "\n", $source); if ($this->hasTokenFunc) { $tokens = $this->tokenize($source); @@ -129,57 +174,58 @@ private function getHighlightedLines(string $source): array } // if no func: token_get_all - return \explode("\n", $source); + return explode("\n", $source); } /** * @param string $source + * * @return array */ private function tokenize(string $source): array { $buffer = ''; $output = []; - $tokens = \token_get_all($source); + $tokens = token_get_all($source); $newType = $currentType = null; foreach ($tokens as $token) { - if (\is_array($token)) { + if (is_array($token)) { switch ($token[0]) { - case \T_INLINE_HTML: + case T_INLINE_HTML: $newType = self::TOKEN_HTML; break; - case \T_COMMENT: - case \T_DOC_COMMENT: + case T_COMMENT: + case T_DOC_COMMENT: $newType = self::TOKEN_COMMENT; break; - case \T_ENCAPSED_AND_WHITESPACE: - case \T_CONSTANT_ENCAPSED_STRING: + case T_ENCAPSED_AND_WHITESPACE: + case T_CONSTANT_ENCAPSED_STRING: $newType = self::TOKEN_STRING; break; - case \T_WHITESPACE: + case T_WHITESPACE: break; - case \T_OPEN_TAG: - case \T_OPEN_TAG_WITH_ECHO: - case \T_CLOSE_TAG: - case \T_STRING: - case \T_VARIABLE: + case T_OPEN_TAG: + case T_OPEN_TAG_WITH_ECHO: + case T_CLOSE_TAG: + case T_STRING: + case T_VARIABLE: // Constants - case \T_DIR: - case \T_FILE: - case \T_METHOD_C: - case \T_DNUMBER: - case \T_LNUMBER: - case \T_NS_C: - case \T_LINE: - case \T_CLASS_C: - case \T_FUNC_C: + case T_DIR: + case T_FILE: + case T_METHOD_C: + case T_DNUMBER: + case T_LNUMBER: + case T_NS_C: + case T_LINE: + case T_CLASS_C: + case T_FUNC_C: //case T_TRAIT_C: $newType = self::TOKEN_DEFAULT; break; default: // Compatibility with PHP 5.3 - if (\defined('T_TRAIT_C') && $token[0] === \T_TRAIT_C) { + if (defined('T_TRAIT_C') && $token[0] === T_TRAIT_C) { $newType = self::TOKEN_DEFAULT; } else { $newType = self::TOKEN_KEYWORD; @@ -199,7 +245,7 @@ private function tokenize(string $source): array $currentType = $newType; } - $buffer .= \is_array($token) ? $token[1] : $token; + $buffer .= is_array($token) ? $token[1] : $token; } if (null !== $newType) { @@ -211,6 +257,7 @@ private function tokenize(string $source): array /** * @param array $tokens + * * @return array */ private function splitToLines(array $tokens): array @@ -218,7 +265,7 @@ private function splitToLines(array $tokens): array $lines = $line = []; foreach ($tokens as $token) { - foreach (\explode("\n", $token[1]) as $count => $tokenLine) { + foreach (explode("\n", $token[1]) as $count => $tokenLine) { if ($count > 0) { $lines[] = $line; $line = []; @@ -237,8 +284,9 @@ private function splitToLines(array $tokens): array /** * @param array[] $tokenLines + * * @return array - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ private function colorLines(array $tokenLines): array { @@ -269,26 +317,25 @@ private function colorLines(array $tokenLines): array /** * @param array $lines * @param null|int $markLine + * * @return string */ private function lineNumbers(array $lines, $markLine = null): string { - \end($lines); + end($lines); $snippet = ''; - $lineLen = \strlen(\key($lines) + 1); + $lineLen = strlen(key($lines) + 1); $lmStyle = $this->defaultTheme[self::ACTUAL_LINE_MARK]; $lnStyle = $this->defaultTheme[self::LINE_NUMBER]; foreach ($lines as $i => $line) { if ($markLine !== null) { $snippet .= ($markLine === $i + 1 ? Color::apply($lmStyle, ' > ') : ' '); - $snippet .= Color::apply( - $markLine === $i + 1 ? $lmStyle : $lnStyle, - \str_pad($i + 1, $lineLen, ' ', \STR_PAD_LEFT) . '| ' - ); + $snippet .= Color::apply($markLine === $i + 1 ? $lmStyle : $lnStyle, + str_pad($i + 1, $lineLen, ' ', STR_PAD_LEFT) . '| '); } else { - $snippet .= Color::apply($lnStyle, \str_pad($i + 1, $lineLen, ' ', \STR_PAD_LEFT) . '| '); + $snippet .= Color::apply($lnStyle, str_pad($i + 1, $lineLen, ' ', STR_PAD_LEFT) . '| '); } $snippet .= $line . PHP_EOL; @@ -310,6 +357,6 @@ public function getDefaultTheme(): array */ public function setDefaultTheme(array $defaultTheme): void { - $this->defaultTheme = \array_merge($this->defaultTheme, $defaultTheme); + $this->defaultTheme = array_merge($this->defaultTheme, $defaultTheme); } } diff --git a/libs/cli-utils/src/Terminal.php b/libs/cli-utils/src/Terminal.php index 096a0a8..f33212d 100644 --- a/libs/cli-utils/src/Terminal.php +++ b/libs/cli-utils/src/Terminal.php @@ -8,8 +8,12 @@ namespace Toolkit\Cli; +use function array_keys; +use function strpos; + /** * Class Terminal - terminal control by ansiCode + * * @package Toolkit\Cli * * 2K 清除本行 @@ -46,12 +50,14 @@ final class Terminal /** * current class's instance + * * @var self */ private static $instance; /** * Control cursor code list + * * @var array */ private static $ctrlCursorCodes = [ @@ -94,6 +100,7 @@ final class Terminal /** * Control screen code list + * * @var array */ private static $ctrlScreenCodes = [ @@ -138,6 +145,7 @@ public static function make(): Terminal * * @param mixed $format * @param string $type + * * @return string */ public static function build($format, $type = 'm'): string @@ -149,9 +157,11 @@ public static function build($format, $type = 'm'): string /** * control cursor + * * @param string $typeName * @param int $arg1 * @param null $arg2 + * * @return $this */ public function cursor($typeName, $arg1 = 1, $arg2 = null): self @@ -163,7 +173,7 @@ public function cursor($typeName, $arg1 = 1, $arg2 = null): self $code = self::$ctrlCursorCodes[$typeName]; // allow argument - if (false !== \strpos($code, '%')) { + if (false !== strpos($code, '%')) { // The special code: ` 'coordinate' => '%dG|%d;%dH' ` if ($typeName === self::CUR_COORDINATE) { $codes = explode('|', $code); @@ -186,8 +196,10 @@ public function cursor($typeName, $arg1 = 1, $arg2 = null): self /** * control screen + * * @param $typeName * @param null $arg + * * @return $this */ public function screen(string $typeName, $arg = null): self @@ -218,7 +230,7 @@ public function reset(): void */ public static function supportedCursorCtrl(): array { - return \array_keys(self::$ctrlCursorCodes); + return array_keys(self::$ctrlCursorCodes); } /** @@ -226,6 +238,6 @@ public static function supportedCursorCtrl(): array */ public static function supportedScreenCtrl(): array { - return \array_keys(self::$ctrlScreenCodes); + return array_keys(self::$ctrlScreenCodes); } } diff --git a/libs/cli-utils/test/ColorTagTest.php b/libs/cli-utils/test/ColorTagTest.php index 51fd608..af9366e 100644 --- a/libs/cli-utils/test/ColorTagTest.php +++ b/libs/cli-utils/test/ColorTagTest.php @@ -13,6 +13,7 @@ /** * Class ColorTagTest + * * @package Toolkit\CliTest */ class ColorTagTest extends TestCase diff --git a/libs/cli-utils/test/ColorTest.php b/libs/cli-utils/test/ColorTest.php index d9fa986..5f5fb3d 100644 --- a/libs/cli-utils/test/ColorTest.php +++ b/libs/cli-utils/test/ColorTest.php @@ -7,6 +7,7 @@ /** * Class ColorTest + * * @package Toolkit\CliTest */ class ColorTest extends TestCase