Code Coverage |
||||||||||||||||
Lines |
Branches |
Paths |
Functions and Methods |
Classes and Traits |
||||||||||||
| Total | |
100.00% |
2 / 2 |
|
87.50% |
7 / 8 |
|
50.00% |
3 / 6 |
|
0.00% |
0 / 1 |
CRAP | |
0.00% |
0 / 1 |
| Opt | |
100.00% |
2 / 2 |
|
87.50% |
7 / 8 |
|
50.00% |
3 / 6 |
|
100.00% |
1 / 1 |
4.12 | |
100.00% |
1 / 1 |
| __construct | |
100.00% |
2 / 2 |
|
87.50% |
7 / 8 |
|
50.00% |
3 / 6 |
|
100.00% |
1 / 1 |
4.12 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Celema\Console; |
| 6 | |
| 7 | use Attribute; |
| 8 | use ValueError; |
| 9 | |
| 10 | /** |
| 11 | * Declares an `__invoke()` parameter as an option. |
| 12 | * |
| 13 | * The option takes its name from the parameter, converted to kebab-case: |
| 14 | * `$dryRun` becomes `--dry-run`. Every option needs a default, which the |
| 15 | * command receives when the option is absent and which the help renders |
| 16 | * as `[default: ...]`. The declared type decides the form: |
| 17 | * |
| 18 | * - `bool`: a flag without value, such as `--force`. With a default of |
| 19 | * `true` or `null`, `--no-force` sets it to `false`. |
| 20 | * - `string`, `int`, `float`, or a backed enum: one `--name=<value>`, |
| 21 | * converted to the type. |
| 22 | * - `array`: repeatable, `--tag=a --tag=b`, collecting the values as |
| 23 | * strings. |
| 24 | * |
| 25 | * `short` adds an alias of one character, like `-p`. `value` overrides the |
| 26 | * `<value>` label, which defaults to the option name. `bare` makes the |
| 27 | * value optional: a bare `--name` then stands for `--name=<bare>`, and the |
| 28 | * help renders `--name[=<value>]`. |
| 29 | * |
| 30 | * @api |
| 31 | */ |
| 32 | #[Attribute(Attribute::TARGET_PARAMETER)] |
| 33 | final class Opt |
| 34 | { |
| 35 | public function __construct( |
| 36 | public readonly string $description = '', |
| 37 | public readonly string $short = '', |
| 38 | public readonly string $value = '', |
| 39 | public readonly ?string $bare = null, |
| 40 | ) { |
| 41 | if ($short !== '' && preg_match('/^-[^-=\s]\z/u', $short) !== 1) { |
| 42 | throw new ValueError("Short option name '{$short}' must be a dash and one character"); |
| 43 | } |
| 44 | } |
| 45 | } |