Skip to content

Commit

Permalink
Parser: added Normalizer
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Nov 26, 2023
1 parent 9d67d4c commit 3ff03cf
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/CommandLine/Parser.php
Expand Up @@ -21,6 +21,7 @@ class Parser
Repeatable = 'repeatable',
Enum = 'enum',
RealPath = 'realpath',
Normalizer = 'normalizer',
Default = 'default';

/** @deprecated use Parser::Argument */
Expand Down Expand Up @@ -139,9 +140,11 @@ public function parse(?array $args = null): array
}
}

$this->checkArg($opt, $arg);

if (
!empty($opt[self::Enum])
&& !in_array($arg, $opt[self::Enum], true)
&& !in_array(is_array($arg) ? reset($arg) : $arg, $opt[self::Enum], true)
&& !(
$opt[self::Optional]
&& $arg === true
Expand All @@ -150,8 +153,6 @@ public function parse(?array $args = null): array
throw new \Exception("Value of option $name must be " . implode(', or ', $opt[self::Enum]) . '.');
}

$this->checkArg($opt, $arg);

if (empty($opt[self::Repeatable])) {
$params[$name] = $arg;
} else {
Expand Down Expand Up @@ -187,6 +188,10 @@ public function help(): void

public function checkArg(array $opt, &$arg): void
{
if (isset($opt[self::Normalizer])) {
$arg = $opt[self::Normalizer]($arg);
}

if (!empty($opt[self::RealPath])) {
$path = realpath($arg);
if ($path === false) {
Expand Down
30 changes: 30 additions & 0 deletions tests/Parser.phpt
Expand Up @@ -194,6 +194,36 @@ test('realpath', function () {



test('normalizer', function () {
$cmd = new Parser('
-p param
', [
'-p' => [Parser::Normalizer => function ($arg) { return "$arg-normalized"; }],
]);

Assert::same(['-p' => 'val-normalized'], $cmd->parse(explode(' ', '-p val')));


$cmd = new Parser('
-p <a|b>
', [
'-p' => [Parser::Normalizer => function () { return 'a'; }],
]);

Assert::same(['-p' => 'a'], $cmd->parse(explode(' ', '-p xxx')));


$cmd = new Parser('
-p <a|b>
', [
'-p' => [Parser::Normalizer => function () { return ['a', 'foo']; }],
]);

Assert::same(['-p' => ['a', 'foo']], $cmd->parse(explode(' ', '-p xxx')));
});



test('positional arguments', function () {
$cmd = new Parser('', [
'pos' => [],
Expand Down

0 comments on commit 3ff03cf

Please sign in to comment.