-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArrayArgs.php
135 lines (115 loc) · 3.25 KB
/
ArrayArgs.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
<?php
namespace Dframe\Console;
use Dframe\Console\Exceptions\ConsoleException;
class ArrayArgs implements InputInterface
{
/**
* @var array
*/
protected $options;
/**
* @var string
*/
protected $name;
/**
* @param $args
*
* @return array
* @throws ConsoleException
*/
public function __construct($args)
{
array_shift($args);
$endOfOptions = false;
$ret = [
'commands' => [],
'options' => [],
'flags' => [],
'arguments' => [],
];
while ($arg = array_shift($args)) {
// if we have reached end of options,
// we cast all remaining argv's as arguments
if ($endOfOptions) {
$ret['arguments'][] = $arg;
continue;
}
// Is it a command? (prefixed with --)
if (substr($arg, 0, 2) === '--') {
// is it the end of options flag?
if (!isset($arg[3])) {
$endOfOptions = true; // end of options;
continue;
}
$value = "";
$com = substr($arg, 2);
// is it the syntax '--option=argument'?
if (strpos($com, '=')) {
[$com, $value] = explode("=", $com, 2);
} elseif (strpos(
$args[0],
'-'
) !== 0) { // is the option not followed by another option but by arguments
while (strpos($args[0], '-') !== 0) {
$value .= array_shift($args) . ' ';
}
$value = rtrim($value, ' ');
}
$ret['options'][$com] = !empty($value) ? $value : true;
continue;
}
// Is it a flag or a serial of flags? (prefixed with -)
if (substr($arg, 0, 1) === '-') {
for ($i = 1; isset($arg[$i]); $i++) {
$ret['flags'][] = $arg[$i];
}
continue;
}
// finally, it is not option, nor flag, nor argument
$ret['commands'][] = $arg;
continue;
}
if (!count($ret['options']) && !count($ret['flags'])) {
$ret['arguments'] = array_merge($ret['commands'], $ret['arguments']);
$ret['commands'] = [];
}
if (isset($ret['commands'][0])) {
$name = $ret['commands'][0];
} elseif (isset($ret['arguments'][0])) {
$name = $ret['commands'][0];
} else {
throw new ConsoleException('Invalid File.');
}
$this->setName($name);
$this->setOptions($ret['options']);
return $ret;
}
/**
* @return array
*/
public function getOptions()
{
return $this->options;
}
/**
* @param array $options
*/
public function setOptions($options)
{
$this->options = $options;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
}
}