1 | <?php |
||
2 | /** |
||
3 | * 命令行参数 |
||
4 | * |
||
5 | * @author mybsdc <[email protected]> |
||
6 | * @date 2020/1/3 |
||
7 | * @time 16:32 |
||
8 | */ |
||
9 | |||
10 | namespace Luolongfei\Lib; |
||
11 | |||
12 | class Argv |
||
13 | { |
||
14 | /** |
||
15 | * @var Argv |
||
16 | */ |
||
17 | protected static $instance; |
||
18 | |||
19 | /** |
||
20 | * @var array 所有命令行传参 |
||
21 | */ |
||
22 | public $allArgvs = []; |
||
23 | |||
24 | public function __construct() |
||
25 | { |
||
26 | if ($this->get('help') || $this->get('h')) { |
||
27 | $desc = <<<FLL |
||
28 | Description |
||
29 | Params: |
||
30 | -c: <string> 指定要实例化的类名。默认调用FreeNom类 |
||
31 | -m: <string> 指定要调用的方法名(不支持静态方法)。默认调用handle方法 |
||
32 | -h: 显示说明 |
||
33 | |||
34 | Example: |
||
35 | $ php run -c=FreeNom -m=handle |
||
36 | |||
37 | FLL; |
||
38 | echo $desc; |
||
39 | exit(0); |
||
0 ignored issues
–
show
|
|||
40 | } |
||
41 | } |
||
42 | |||
43 | /** |
||
44 | * @return Argv |
||
45 | */ |
||
46 | public static function instance() |
||
47 | { |
||
48 | if (!self::$instance instanceof self) { |
||
49 | self::$instance = new self(); |
||
50 | } |
||
51 | |||
52 | return self::$instance; |
||
53 | } |
||
54 | |||
55 | /** |
||
56 | * 获取命令行参数 |
||
57 | * |
||
58 | * @param string $name |
||
59 | * @param string $default |
||
60 | * |
||
61 | * @return mixed|string |
||
62 | */ |
||
63 | public function get(string $name, string $default = '') |
||
64 | { |
||
65 | if (!$this->allArgvs) { |
||
0 ignored issues
–
show
The expression
$this->allArgvs of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.
This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent. Consider making the comparison explicit by using ![]() |
|||
66 | $this->setAllArgvs(); |
||
67 | } |
||
68 | |||
69 | return $this->allArgvs[$name] ?? $default; |
||
70 | } |
||
71 | |||
72 | /** |
||
73 | * 设置命令行所有参数 |
||
74 | * |
||
75 | * @return array |
||
76 | */ |
||
77 | public function setAllArgvs() |
||
78 | { |
||
79 | global $argv; |
||
80 | |||
81 | foreach ($argv as $a) { // Windows默认命令行无法正确传入使用引号括住的带空格参数,换个命令行终端就好,Linux不受影响 |
||
82 | if (preg_match('/^-{1,2}(?P<name>\w+)(?:=([\'"]|)(?P<val>[^\n\t\v\f\r\'"]+)\2)?$/i', $a, $m)) { |
||
83 | $this->allArgvs[$m['name']] = $m['val'] ?? true; |
||
84 | } |
||
85 | } |
||
86 | |||
87 | return $this->allArgvs; |
||
88 | } |
||
89 | } |
In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.