Skip to content

Commit

Permalink
refactor(*): use imports instead of FQN
Browse files Browse the repository at this point in the history
  • Loading branch information
adhocore committed Oct 8, 2022
1 parent cbfe911 commit bd0a70c
Show file tree
Hide file tree
Showing 17 changed files with 359 additions and 189 deletions.
45 changes: 29 additions & 16 deletions src/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,19 @@
use Ahc\Cli\Helper\OutputHelper;
use Ahc\Cli\Input\Command;
use Ahc\Cli\IO\Interactor;
use ReflectionClass;
use ReflectionFunction;
use Throwable;
use function array_diff_key;
use function array_fill_keys;
use function array_keys;
use function count;
use function func_num_args;
use function in_array;
use function is_array;
use function is_int;
use function method_exists;
use function sprintf;

/**
* A cli application.
Expand Down Expand Up @@ -48,7 +61,7 @@ class Application

public function __construct(protected string $name, protected string $version = '0.0.1', callable $onExit = null)
{
$this->onExit = $onExit ?? fn (int $exitCode = 0) => exit($exitCode);
$this->onExit = $onExit ?? static fn (int $exitCode = 0) => exit($exitCode);

$this->command('__default__', 'Default command', '', true)->on([$this, 'showHelp'], 'help');
}
Expand Down Expand Up @@ -100,7 +113,7 @@ public function argv(): array
*/
public function logo(string $logo = null)
{
if (\func_num_args() === 0) {
if (func_num_args() === 0) {
return $this->logo;
}

Expand Down Expand Up @@ -140,7 +153,7 @@ public function add(Command $command, string $alias = '', bool $default = false)
$this->aliases[$alias] ??
null
) {
throw new InvalidArgumentException(\sprintf('Command "%s" already added', $name));
throw new InvalidArgumentException(sprintf('Command "%s" already added', $name));
}

if ($alias) {
Expand Down Expand Up @@ -206,7 +219,7 @@ public function io(Interactor $io = null)
$this->io = $io ?? new Interactor;
}

if (\func_num_args() === 0) {
if (func_num_args() === 0) {
return $this->io;
}

Expand All @@ -229,7 +242,7 @@ public function parse(array $argv): Command

// Eat the cmd name!
foreach ($argv as $i => $arg) {
if (\in_array($arg, $aliases)) {
if (in_array($arg, $aliases)) {
unset($argv[$i]);

break;
Expand All @@ -248,7 +261,7 @@ public function parse(array $argv): Command
*/
public function handle(array $argv): mixed
{
if (\count($argv) < 2) {
if (count($argv) < 2) {
return $this->showHelp();
}

Expand All @@ -257,8 +270,8 @@ public function handle(array $argv): mixed
try {
$command = $this->parse($argv);
$result = $this->doAction($command);
$exitCode = \is_int($result) ? $result : 0;
} catch (\Throwable $e) {
$exitCode = is_int($result) ? $result : 0;
} catch (Throwable $e) {
$this->outputHelper()->printTrace($e);
}

Expand All @@ -272,10 +285,10 @@ protected function aliasesFor(Command $command): array
{
$aliases = [$name = $command->name()];

foreach ($this->aliases as $alias => $command) {
if (\in_array($name, [$alias, $command])) {
foreach ($this->aliases as $alias => $cmd) {
if (in_array($name, [$alias, $cmd], true)) {
$aliases[] = $alias;
$aliases[] = $command;
$aliases[] = $cmd;
}
}

Expand Down Expand Up @@ -319,7 +332,7 @@ protected function doAction(Command $command): mixed
// Let the command collect more data (if missing or needs confirmation)
$command->interact($this->io());

if (!$command->action() && !\method_exists($command, 'execute')) {
if (!$command->action() && !method_exists($command, 'execute')) {
return null;
}

Expand All @@ -340,17 +353,17 @@ protected function doAction(Command $command): mixed
*/
protected function notFound(): mixed
{
$available = \array_keys($this->commands() + $this->aliases);
$available = array_keys($this->commands() + $this->aliases);
$this->outputHelper()->showCommandNotFound($this->argv[1], $available);

return ($this->onExit)(127);
}

protected function getActionParameters(callable $action): array
{
$reflex = \is_array($action)
? (new \ReflectionClass($action[0]))->getMethod($action[1])
: new \ReflectionFunction($action);
$reflex = is_array($action)
? (new ReflectionClass($action[0]))->getMethod($action[1])
: new ReflectionFunction($action);

return $reflex->getParameters();
}
Expand Down
4 changes: 3 additions & 1 deletion src/Exception.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@

namespace Ahc\Cli;

interface Exception extends \Throwable
use Throwable;

interface Exception extends Throwable
{
// ;)
}
15 changes: 10 additions & 5 deletions src/Helper/InflectsString.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@

namespace Ahc\Cli\Helper;

use function lcfirst;
use function str_replace;
use function trim;
use function ucwords;

/**
* Performs inflection on strings.
*
Expand All @@ -26,20 +31,20 @@ trait InflectsString
*/
public function toCamelCase(string $string): string
{
$words = \str_replace(['-', '_'], ' ', $string);
$words = str_replace(['-', '_'], ' ', $string);

$words = \str_replace(' ', '', \ucwords($words));
$words = str_replace(' ', '', ucwords($words));

return \lcfirst($words);
return lcfirst($words);
}

/**
* Convert a string to capitalized words.
*/
public function toWords(string $string): string
{
$words = \trim(\str_replace(['-', '_'], ' ', $string));
$words = trim(str_replace(['-', '_'], ' ', $string));

return \ucwords($words);
return ucwords($words);
}
}
20 changes: 13 additions & 7 deletions src/Helper/Normalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@

use Ahc\Cli\Input\Option;
use Ahc\Cli\Input\Parameter;
use function array_merge;
use function explode;
use function implode;
use function ltrim;
use function preg_match;
use function str_split;

/**
* Internal value &/or argument normalizer. Has little to no usefulness as public api.
Expand All @@ -32,13 +38,13 @@ public function normalizeArgs(array $args): array
$normalized = [];

foreach ($args as $arg) {
if (\preg_match('/^\-\w=/', $arg)) {
$normalized = \array_merge($normalized, explode('=', $arg));
} elseif (\preg_match('/^\-\w{2,}/', $arg)) {
$splitArg = \implode(' -', \str_split(\ltrim($arg, '-')));
$normalized = \array_merge($normalized, \explode(' ', '-' . $splitArg));
} elseif (\preg_match('/^\-\-([^\s\=]+)\=/', $arg)) {
$normalized = \array_merge($normalized, explode('=', $arg));
if (preg_match('/^\-\w=/', $arg)) {
$normalized = array_merge($normalized, explode('=', $arg));
} elseif (preg_match('/^\-\w{2,}/', $arg)) {
$splitArg = implode(' -', str_split(ltrim($arg, '-')));
$normalized = array_merge($normalized, explode(' ', '-' . $splitArg));
} elseif (preg_match('/^\-\-([^\s\=]+)\=/', $arg)) {
$normalized = array_merge($normalized, explode('=', $arg));
} else {
$normalized[] = $arg;
}
Expand Down
72 changes: 50 additions & 22 deletions src/Helper/OutputHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,37 @@
use Ahc\Cli\Exception;
use Ahc\Cli\Input\Argument;
use Ahc\Cli\Input\Command;
use Ahc\Cli\Input\Groupable;
use Ahc\Cli\Input\Option;
use Ahc\Cli\Input\Parameter;
use Ahc\Cli\Output\Writer;
use Throwable;
use function array_map;
use function array_shift;
use function asort;
use function explode;
use function get_class;
use function gettype;
use function implode;
use function is_array;
use function is_object;
use function is_scalar;
use function key;
use function levenshtein;
use function max;
use function method_exists;
use function preg_replace;
use function preg_replace_callback;
use function realpath;
use function str_contains;
use function str_pad;
use function str_replace;
use function strlen;
use function strrpos;
use function trim;
use function uasort;
use function var_export;
use const STR_PAD_LEFT;

/**
* This helper helps you by showing you help information :).
Expand All @@ -41,9 +69,9 @@ public function __construct(Writer $writer = null)
/**
* Print stack trace and error msg of an exception.
*/
public function printTrace(\Throwable $e): void
public function printTrace(Throwable $e): void
{
$eClass = \get_class($e);
$eClass = get_class($e);

$this->writer->colors(
"{$eClass} <red>{$e->getMessage()}</end><eol/>" .
Expand All @@ -66,7 +94,7 @@ public function printTrace(\Throwable $e): void

$traceStr .= " <comment>$i)</end> <red>$symbol</end><comment>($args)</end>";
if ('' !== $trace['file']) {
$file = \realpath($trace['file']);
$file = realpath($trace['file']);
$traceStr .= "<eol/> <yellow>at $file</end><white>:{$trace['line']}</end><eol/>";
}
}
Expand All @@ -82,24 +110,24 @@ protected function stringifyArgs(array $args): string
$holder[] = $this->stringifyArg($arg);
}

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

protected function stringifyArg($arg): string
{
if (\is_scalar($arg)) {
return \var_export($arg, true);
if (is_scalar($arg)) {
return var_export($arg, true);
}

if (\is_object($arg)) {
return \method_exists($arg, '__toString') ? (string) $arg : \get_class($arg);
if (is_object($arg)) {
return method_exists($arg, '__toString') ? (string) $arg : get_class($arg);
}

if (\is_array($arg)) {
if (is_array($arg)) {
return '[' . $this->stringifyArgs($arg) . ']';
}

return \gettype($arg);
return gettype($arg);
}

/**
Expand Down Expand Up @@ -139,7 +167,7 @@ public function showOptionsHelp(array $options, string $header = '', string $foo
*/
public function showCommandsHelp(array $commands, string $header = '', string $footer = ''): self
{
$this->maxCmdName = $commands ? \max(\array_map(fn (Command $cmd) => \strlen($cmd->name()), $commands)) : 0;
$this->maxCmdName = $commands ? max(array_map(static fn (Command $cmd) => strlen($cmd->name()), $commands)) : 0;

$this->showHelp('Commands', $commands, $header, $footer);

Expand Down Expand Up @@ -189,24 +217,24 @@ protected function showHelp(string $for, array $items, string $header = '', stri
*/
public function showUsage(string $usage): self
{
$usage = \str_replace('$0', $_SERVER['argv'][0] ?? '[cmd]', $usage);
$usage = str_replace('$0', $_SERVER['argv'][0] ?? '[cmd]', $usage);

if (!\str_contains($usage, ' ## ')) {
if (!str_contains($usage, ' ## ')) {
$this->writer->eol()->boldGreen('Usage Examples:', true)->colors($usage)->eol();

return $this;
}

$lines = \explode("\n", \str_replace(['<eol>', '<eol/>', '</eol>', "\r\n"], "\n", $usage));
$lines = explode("\n", str_replace(['<eol>', '<eol/>', '</eol>', "\r\n"], "\n", $usage));
foreach ($lines as $i => &$pos) {
if (false === $pos = \strrpos(\preg_replace('~</?\w+/?>~', '', $pos), ' ##')) {
if (false === $pos = strrpos(preg_replace('~</?\w+/?>~', '', $pos), ' ##')) {
unset($lines[$i]);
}
}

$maxlen = ($lines ? \max($lines) : 0) + 4;
$usage = \preg_replace_callback('~ ## ~', function () use (&$lines, $maxlen) {
return \str_pad('# ', $maxlen - \array_shift($lines), ' ', \STR_PAD_LEFT);
$maxlen = ($lines ? max($lines) : 0) + 4;
$usage = preg_replace_callback('~ ## ~', function () use (&$lines, $maxlen) {
return str_pad('# ', $maxlen - array_shift($lines), ' ', STR_PAD_LEFT);
}, $usage);

$this->writer->eol()->boldGreen('Usage Examples:', true)->colors($usage)->eol();
Expand All @@ -218,16 +246,16 @@ public function showCommandNotFound(string $attempted, array $available): self
{
$closest = [];
foreach ($available as $cmd) {
$lev = \levenshtein($attempted, $cmd);
$lev = levenshtein($attempted, $cmd);
if ($lev > 0 || $lev < 5) {
$closest[$cmd] = $lev;
}
}

$this->writer->error("Command $attempted not found", true);
if ($closest) {
\asort($closest);
$closest = \key($closest);
asort($closest);
$closest = key($closest);
$this->writer->bgRed("Did you mean $closest?", true);
}

Expand Down Expand Up @@ -268,7 +296,7 @@ protected function getName($item): string
$name = $item->name();

if ($item instanceof Command) {
return \trim(\str_pad($name, $this->maxCmdName) . ' ' . $item->alias());
return trim(str_pad($name, $this->maxCmdName) . ' ' . $item->alias());
}

return $this->label($item);
Expand Down
Loading

0 comments on commit bd0a70c

Please sign in to comment.