-
Notifications
You must be signed in to change notification settings - Fork 105
/
cli.php
94 lines (84 loc) · 2.52 KB
/
cli.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
<?php
namespace Helper;
class Cli extends \Prefab
{
/**
* Parse CLI options with defaults
*
* Also shows argument help if "-h" or "--help" is passed, and exits
* with a relevant message if required arguments are not specified.
*
* @param array $options Associative array, argument keys => default values
* @param array $argv
* @return array|null
*/
public function parseOptions(array $options, ?array $argv = null): ?array
{
$keys = array_keys($options);
if ($argv === null) {
$argv = $_SERVER['argv'];
}
// Show argument help
if (getopt('h', ['help']) || (is_countable($argv) ? count($argv) : 0) == 1) {
$this->showHelp($keys, $options);
return null;
}
// Parse options
$data = getopt('', $keys);
// Check that required options are set
foreach ($keys as $key) {
if (substr_count($key, ':') != 1) {
continue;
}
$o = rtrim($key, ':');
if (!array_key_exists($o, $data)) {
echo "Required argument --$o not specified.", PHP_EOL;
exit(1);
}
}
// Fill result with defaults
$result = [];
foreach ($keys as $o) {
$key = rtrim($o, ':');
$result[$key] = $data[$key] ?? $options[$o];
}
return $result;
}
/**
* Output help message showing parseOptions() options and defaults
*/
protected function showHelp(array $options, array $defaultMap): void
{
$required = [];
$optional = [];
$flags = [];
foreach ($options as $o) {
$colons = substr_count($o, ':');
if ($colons == 2) {
$optional[] = $o;
} elseif ($colons == 1) {
$required[] = $o;
} else {
$flags[] = $o;
}
}
echo 'Required values:', PHP_EOL;
foreach ($required as $key) {
$o = rtrim($key, ':');
echo "--$o={$defaultMap[$key]}", PHP_EOL;
}
echo PHP_EOL;
echo 'Optional values:', PHP_EOL;
foreach ($optional as $key) {
$o = rtrim($key, ':');
echo "--$o={$defaultMap[$key]}", PHP_EOL;
}
echo PHP_EOL;
echo 'Optional flags:', PHP_EOL;
foreach ($flags as $key) {
$o = rtrim($key, ':');
echo "--$o", PHP_EOL;
}
echo PHP_EOL;
}
}