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