-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCLI.php
More file actions
131 lines (122 loc) · 2.72 KB
/
CLI.php
File metadata and controls
131 lines (122 loc) · 2.72 KB
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
<?php
/**
* CommandLine class
*
* Command Line Interface (CLI) utility class.
*
* @author Patrick Fisher <patrick@pwfisher.com>
* @since August 21, 2009
* @see https://github.com/pwfisher/CommandLine.php
*/
class CLI
{
public static $args;
/**
* PARSE ARGUMENTS
*
* This command line option parser supports any combination of three types
* of options (switches, flags and arguments) and returns a simple array.
*
* @param array $argv
* @usage $args = CommandLine::parseArgs($_SERVER['argv']);
* @return array
*/
public static function parseArguments($argv = NULL)
{
if( is_null($argv) )
{
$argv = $_SERVER['argv'];
}
array_shift($argv);
$out = array();
foreach ($argv as $arg)
{
if (substr($arg,0,2) == '--') // --foo --bar=baz
{
$eqPos = strpos($arg,'=');
if ($eqPos === false) // --foo
{
$key = substr($arg,2);
$value = isset($out[$key]) ? $out[$key] : true;
$out[$key] = $value;
}
else // --bar=baz
{
$key = substr($arg,2,$eqPos-2);
$value = substr($arg,$eqPos+1);
$out[$key] = $value;
}
}
else if (substr($arg,0,1) == '-') // -k=value -abc
{
if (substr($arg,2,1) == '=') // -k=value
{
$key = substr($arg,1,1);
$value = substr($arg,3);
$out[$key] = $value;
}
else // -abc
{
$chars = str_split(substr($arg,1));
foreach ($chars as $char)
{
$key = $char;
$value = isset($out[$key]) ? $out[$key] : true;
$out[$key] = $value;
}
}
}
else // plain-arg
{
$value = $arg;
$out[] = $value;
}
}
self::$args = $out;
return $out;
}
/**
* GET BOOLEAN
*/
public static function getBoolean($key, $default = false)
{
if (!isset(self::$args[$key]))
{
return $default;
}
$value = self::$args[$key];
if (is_bool($value))
{
return $value;
}
if (is_int($value))
{
return (bool)$value;
}
if (is_string($value))
{
$map = array
(
'y' => true,
'n' => false,
'yes' => true,
'no' => false,
'true' => true,
'false' => false,
'1' => true,
'0' => false,
'on' => true,
'off' => false,
);
if (isset($map[strtolower($value)]))
{
return $map[$value];
}
else
{
return $value;
}
}
return $default;
}
}