Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New features and some fixes - Variadic arguments flexibility and grouping, Negative numbers #94

Closed
wants to merge 22 commits into from
Closed
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
d78e60c
New Tokenize and Token classes for argv parsing Striped Normalizer bu…
shlomohass Sep 29, 2023
fc20eb0
added phpstan to dev just to check and later fix all the crazy warnin…
shlomohass Sep 29, 2023
53d1980
small phpstan fixes that actually make sense
shlomohass Sep 29, 2023
1d69be1
Helper class to support older php versions... should be removed when …
shlomohass Sep 29, 2023
f7a305b
Parser new version to use the tokenizer and support the new argv synt…
shlomohass Sep 29, 2023
7c0a276
adapted to be used with the new tokenizer and parser
shlomohass Sep 29, 2023
cdc128c
small phpstan fix with actionCalled not defined
shlomohass Sep 29, 2023
59a1b9b
New test + Removed invalid test for the extended argv syntax parser
shlomohass Sep 29, 2023
a459c0d
removed comments
shlomohass Sep 29, 2023
2149fa4
Merge branch 'main' of github.com:shlomohass/php-cli
shlomohass Sep 29, 2023
7a1ea62
small fix filter should return int
shlomohass Sep 29, 2023
8af5946
simplified option parsing and removed literal handling as they are ex…
shlomohass Sep 29, 2023
8778eaf
added "insane" tests just to make sure
shlomohass Sep 29, 2023
811c71d
added line break when an exception is raised
shlomohass Sep 29, 2023
6bd6448
codefactor formatting fixes + removed polyfill code
shlomohass Oct 2, 2023
c0ec41e
formatting fixes - NL before returns
shlomohass Oct 2, 2023
6d8cf80
removed extra continue from the parse loop
shlomohass Oct 2, 2023
e3bbc1d
single line commects formatting fix
shlomohass Oct 2, 2023
7ddc17c
removed extra comments
shlomohass Oct 2, 2023
cdd3a65
Improved code for cleaner look and feel
shlomohass Oct 2, 2023
d6b1a3b
use global scope \ removed
shlomohass Oct 2, 2023
a1464ad
codefactor formatting fixes
shlomohass Oct 2, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,12 @@
"php": ">=8.0"
},
"require-dev": {
"phpunit/phpunit": "^9.0"
"phpunit/phpunit": "^9.0",
"phpstan/phpstan": "^1.10"
},
"scripts": {
"test": "phpunit",
"testdox": "phpunit --testdox --colors=always",
"test:cov": "phpunit --coverage-text --coverage-clover coverage.xml --coverage-html vendor/cov",
"cs:sniff": "tools/phpcs",
"cs:fix": "tools/phpcbf"
Expand Down
2 changes: 1 addition & 1 deletion src/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ class Application
/** @var callable The callable to perform exit */
protected $onExit;

/** @var callable The callable to catch exception, receives exception & exit code, may rethrow exception or may exit program */
/** @var null|callable The callable to catch exception, receives exception & exit code, may rethrow exception or may exit program */
protected $onException = null;

public function __construct(protected string $name, protected string $version = '0.0.1', callable $onExit = null)
Expand Down
42 changes: 8 additions & 34 deletions src/Helper/Normalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,9 @@
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.
* Currently used by Input\Parser. To "normalize" values before setting them to parameters.
*
* @author Jitendra Adhikari <[email protected]>
* @license MIT
Expand All @@ -31,46 +25,26 @@
*/
class Normalizer
{
/**
* Normalize argv args. Like splitting `-abc` and `--xyz=...`.
*/
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));
} else {
$normalized[] = $arg;
}
}

return $normalized;
}

/**
* Normalizes value as per context and runs thorugh filter if possible.
*
* @param Parameter $parameter
* @param string|null $value
*
* @return mixed
*/
public function normalizeValue(Parameter $parameter, string $value = null): mixed
public function normalizeValue(Parameter $parameter, ?string $value = null): mixed
{
if ($parameter instanceof Option && $parameter->bool()) {
return !$parameter->default();
}

if ($parameter->variadic()) {
return (array) $value;
}

if (null === $value) {
return $parameter->required() ? null : true;
}

return $parameter->filter($value);
}

}
12 changes: 7 additions & 5 deletions src/Helper/OutputHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
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;
Expand Down Expand Up @@ -77,7 +76,7 @@ public function printTrace(Throwable $e): void

$this->writer->colors(
"{$eClass} <red>{$e->getMessage()}</end><eol/>" .
"(thrown in <yellow>{$e->getFile()}</end><white>:{$e->getLine()})</end>"
"(thrown in <yellow>{$e->getFile()}</end><white>:{$e->getLine()})</end><eol/>"
);

// @codeCoverageIgnoreStart
Expand All @@ -87,7 +86,7 @@ public function printTrace(Throwable $e): void
}
// @codeCoverageIgnoreEnd

$traceStr = '<eol/><eol/><bold>Stack Trace:</end><eol/><eol/>';
$traceStr = '<eol/><bold>Stack Trace:</end><eol/><eol/>';

foreach ($e->getTrace() as $i => $trace) {
$trace += ['class' => '', 'type' => '', 'function' => '', 'file' => '', 'line' => '', 'args' => []];
Expand Down Expand Up @@ -279,8 +278,11 @@ protected function sortItems(array $items, &$max = 0): array
$max = max(array_map(fn ($item) => strlen($this->getName($item)), $items));

uasort($items, static function ($a, $b) {
$aName = $a instanceof Groupable ? $a->group() . $a->name() : $a->name();
$bName = $b instanceof Groupable ? $b->group() . $b->name() : $b->name();
// Fix for:
// Was groupable, but its problematic since groupable does not have name.
// Only commands have groupable. So we need to check instanceof Command.
$aName = $a instanceof Command ? $a->group() . $a->name() : $a->name();
$bName = $b instanceof Command ? $b->group() . $b->name() : $b->name();

return $aName <=> $bName;
});
Expand Down
48 changes: 48 additions & 0 deletions src/Helper/Polyfill.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

/*
* This file is part of the PHP-CLI package.
*
* (c) Jitendra Adhikari <[email protected]>
* <https://github.com/adhocore>
*
* Licensed under MIT license.
*/

namespace Ahc\Cli\Helper;

/**
* Polyfill class is for using newer php syntax
* and still maintaining backword compatibility
*
* @author Shlomo Hassid <[email protected]>
* @license MIT
*
* @link https://github.com/adhocore/cli
*/
class Polyfill
{
public static function str_contains($haystack, $needle)
shlomohass marked this conversation as resolved.
Show resolved Hide resolved
{
if (function_exists('str_contains')) {
return str_contains($haystack, $needle);
}
return $needle !== '' && strpos($haystack, $needle) !== false;
}

public static function str_starts_with($haystack, $needle)
{
if (function_exists('str_starts_with')) {
return str_starts_with($haystack, $needle);
}
return (string) $needle !== '' && strncmp($haystack, $needle, strlen($needle)) === 0;
}

public static function str_ends_with($haystack, $needle)
{
if (function_exists('str_ends_with')) {
return str_ends_with($haystack, $needle);
}
return $needle !== '' && substr($haystack, -strlen($needle)) === (string) $needle;
}
}
11 changes: 0 additions & 11 deletions src/Input/Command.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
namespace Ahc\Cli\Input;

use Ahc\Cli\Application as App;
use Ahc\Cli\Exception\InvalidParameterException;
use Ahc\Cli\Exception\RuntimeException;
use Ahc\Cli\Helper\InflectsString;
use Ahc\Cli\Helper\OutputHelper;
Expand Down Expand Up @@ -54,8 +53,6 @@ class Command extends Parser implements Groupable

private array $_events = [];

private bool $_argVariadic = false;

/**
* Constructor.
*
Expand Down Expand Up @@ -173,14 +170,6 @@ public function argument(string $raw, string $desc = '', $default = null): self
{
$argument = new Argument($raw, $desc, $default);

if ($this->_argVariadic) {
throw new InvalidParameterException('Only last argument can be variadic');
}

if ($argument->variadic()) {
$this->_argVariadic = true;
}

$this->register($argument);

return $this;
Expand Down
38 changes: 31 additions & 7 deletions src/Input/Option.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace Ahc\Cli\Input;

use Ahc\Cli\Helper\Polyfill;
use function preg_match;
use function preg_split;
use function str_replace;
Expand All @@ -30,6 +31,10 @@ class Option extends Parameter

protected string $long = '';

// We export those to be used while parsing:
shlomohass marked this conversation as resolved.
Show resolved Hide resolved
public const SIGN_SHORT = '-';
public const SIGN_LONG = '--';

/**
* {@inheritdoc}
*/
Expand All @@ -41,16 +46,35 @@ protected function parse(string $raw): void
$this->default = true;
}

$parts = preg_split('/[\s,\|]+/', $raw);

$this->short = $this->long = $parts[0];
if (isset($parts[1])) {
$this->long = $parts[1];
}
[$this->short, $this->long] = $this->namingParts($raw);

$this->name = str_replace(['--', 'no-', 'with-'], '', $this->long);
$this->name = str_replace(
[self::SIGN_LONG, 'no-', 'with-'], '',
$this->long
);
}

/**
* parses a raw option declaration string
* and return its parts
* @param string $raw
* @return array 2 elements, short and long name
*/
protected function namingParts(string $raw): array {
$short = '';
$long = '';
foreach (preg_split('/[\s,\|]+/', $raw) as $part) {
if (Polyfill::str_starts_with($part, self::SIGN_LONG)) {
$long = $part;
} elseif (Polyfill::str_starts_with($part, self::SIGN_SHORT)) {
$short = $part;
}
}
return [
shlomohass marked this conversation as resolved.
Show resolved Hide resolved
$short,
$long ?: self::SIGN_LONG.ltrim($short, self::SIGN_SHORT)
];
}
/**
* Get long name.
*/
Expand Down
Loading
Loading