-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcmd.php
More file actions
63 lines (59 loc) · 1.68 KB
/
cmd.php
File metadata and controls
63 lines (59 loc) · 1.68 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
<?php
/**
* Handle common command line jobs
* like parsing cmd line options
*/
class CMD
{
private function __construct() {
# code...
}
/**
* parse command line args if nothing is passed in use global $argv
*
* @param array $argv
* @return array
*/
public static function parseArgs($argv = null) {
if ($argv === null) {
$argv = $GLOBALS['argv'];
}
array_shift($argv); // remove script name from front
$out = array();
foreach ($argv as $arg) {
// handle options with double hypen followed by multiple characters
if (substr($arg, 0, 2) == '--') {
$eqPos = strpos($arg, '=');
if ($eqPos === false) {
// handle --key
$key = substr($arg, 2);
$out[$key] = isset($out[$key]) ? $out[$key] : true;
} else {
// handle --key=value
$key = substr($arg, 2, $eqPos-2);
$out[$key] = substr($arg, $eqPos+1);
}
} else if (substr($arg, 0, 1) == '-') {
// handle options with single hyphen followed by one or more characters, each a single option
if (substr($arg, 2, 1) == '=') {
// handle -k=value
$key = substr($arg, 1, 1);
$out[$key] = substr($arg, 3);
} else {
// handle singfle letter switches -k
// -kvm is the same as -k -v -m
$chars = str_split(substr($arg, 1));
foreach ($chars as $char) {
$key = $char;
$out[$key] = isset($out[$key]) ? $out[$key] : true;
}
}
} else {
// it's a string just place it in the next empty numeric array position
$out[] = $arg;
}
}
return $out;
}
}
?>