forked from adhocore/php-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathParameter.php
147 lines (121 loc) · 2.78 KB
/
Parameter.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
<?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\Input;
use Ahc\Cli\Helper\InflectsString;
use function Ahc\Cli\t;
use function json_encode;
use function ltrim;
use function strpos;
/**
* Cli Parameter.
*
* @author Jitendra Adhikari <[email protected]>
* @license MIT
*
* @link https://github.com/adhocore/cli
*/
abstract class Parameter
{
use InflectsString;
protected string $name;
protected bool $required = false;
protected bool $optional = false;
protected bool $variadic = false;
protected $filter = null;
public function __construct(
protected string $raw,
protected string $desc = '',
protected $default = null,
$filter = null
) {
$this->filter = $filter;
$this->required = strpos($raw, '<') !== false;
$this->optional = strpos($raw, '[') !== false;
$this->variadic = strpos($raw, '...') !== false;
$this->parse($raw);
}
/**
* Parse raw string representation of parameter.
*/
abstract protected function parse(string $raw): void;
/**
* Get raw definition.
*/
public function raw(): string
{
return $this->raw;
}
/**
* Get name.
*/
public function name(): string
{
return $this->name;
}
/**
* Get description.
*/
public function desc(bool $withDefault = false): string
{
if (!$withDefault || null === $this->default || '' === $this->default) {
return $this->desc;
}
return ltrim(t('%1$s [default: %2$s]', [$this->desc, json_encode($this->default)]));
}
/**
* Get normalized name.
*/
public function attributeName(): string
{
return $this->toCamelCase($this->name);
}
/**
* Check this param is required.
*/
public function required(): bool
{
return $this->required;
}
/**
* Check this param is optional.
*/
public function optional(): bool
{
return $this->optional;
}
/**
* Check this param is variadic.
*/
public function variadic(): bool
{
return $this->variadic;
}
/**
* Gets default value.
*/
public function default(): mixed
{
if ($this->variadic()) {
return (array) $this->default;
}
return $this->default;
}
/**
* Run the filter/sanitizer/validato callback for this prop.
*/
public function filter(mixed $raw): mixed
{
if ($this->filter) {
$callback = $this->filter;
return $callback($raw);
}
return $raw;
}
}