1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the PHP-CLI package. |
5
|
|
|
* |
6
|
|
|
* (c) Jitendra Adhikari <[email protected]> |
7
|
|
|
* <https://github.com/adhocore> |
8
|
|
|
* |
9
|
|
|
* Licensed under MIT license. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Ahc\Cli\Helper; |
13
|
|
|
|
14
|
|
|
use Ahc\Cli\Input\Option; |
15
|
|
|
use Ahc\Cli\Input\Parameter; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Internal value &/or argument normalizer. Has little to no usefulness as public api. |
19
|
|
|
* |
20
|
|
|
* @author Jitendra Adhikari <[email protected]> |
21
|
|
|
* @license MIT |
22
|
|
|
* |
23
|
|
|
* @link https://github.com/adhocore/cli |
24
|
|
|
*/ |
25
|
|
|
class Normalizer |
26
|
|
|
{ |
27
|
|
|
/** |
28
|
|
|
* Normalize argv args. Like splitting `-abc` and `--xyz=...`. |
29
|
|
|
* |
30
|
|
|
* @param array $args |
31
|
|
|
* |
32
|
|
|
* @return array |
33
|
|
|
*/ |
34
|
|
|
public function normalizeArgs(array $args): array |
35
|
|
|
{ |
36
|
|
|
$normalized = []; |
37
|
|
|
|
38
|
|
|
foreach ($args as $arg) { |
39
|
|
|
if (\preg_match('/^\-\w=/', $arg)) { |
40
|
|
|
$normalized = \array_merge($normalized, explode('=', $arg)); |
41
|
|
|
} elseif (\preg_match('/^\-\w{2,}/', $arg)) { |
42
|
|
|
$splitArg = \implode(' -', \str_split(\ltrim($arg, '-'))); |
43
|
|
|
$normalized = \array_merge($normalized, \explode(' ', '-' . $splitArg)); |
44
|
|
|
} elseif (\preg_match('/^\-\-([^\s\=]+)\=/', $arg)) { |
45
|
|
|
$normalized = \array_merge($normalized, explode('=', $arg)); |
46
|
|
|
} else { |
47
|
|
|
$normalized[] = $arg; |
48
|
|
|
} |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
return $normalized; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* Normalizes value as per context and runs thorugh filter if possible. |
56
|
|
|
* |
57
|
|
|
* @param Parameter $parameter |
58
|
|
|
* @param string|null $value |
59
|
|
|
* |
60
|
|
|
* @return mixed |
61
|
|
|
*/ |
62
|
|
|
public function normalizeValue(Parameter $parameter, string $value = null) |
63
|
|
|
{ |
64
|
|
|
if ($parameter instanceof Option && $parameter->bool()) { |
65
|
|
|
return !$parameter->default(); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
if ($parameter->variadic()) { |
69
|
|
|
return (array) $value; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
if (null === $value) { |
73
|
|
|
return $parameter->required() ? null : true; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
return $parameter->filter($value); |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|