1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace clearice; |
4
|
|
|
|
5
|
|
|
class Options //implements \ArrayAccess, \Iterator |
6
|
|
|
{ |
7
|
|
|
private $options = []; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* A map of all the options the parser recognises. |
11
|
|
|
* The map is actually an array which associates short or long options with |
12
|
|
|
* their appropriate parameters. Options which have both long and short |
13
|
|
|
* versions would be repeated. This structure is used to quickly find the |
14
|
|
|
* paramters of an option whether in the short form or long form. This |
15
|
|
|
* parameter is automatically populated by the library as options are added. |
16
|
|
|
* |
17
|
|
|
* @var array |
18
|
|
|
*/ |
19
|
|
|
private $map; |
20
|
|
|
|
21
|
28 |
|
public function add($options) |
22
|
|
|
{ |
23
|
28 |
|
foreach ($options as $option) { |
24
|
28 |
|
if (is_string($option)) { |
25
|
4 |
|
$option = $this->stringOptionToArray($option); |
26
|
4 |
|
} |
27
|
28 |
|
$option = $this->fillOption($option); |
28
|
28 |
|
$this->options[] = $option; |
29
|
28 |
|
$command = isset($option['command']) ? $option['command'] : '__default__'; |
30
|
28 |
|
if (isset($option['short'])) { |
31
|
26 |
|
$this->map[$command][$option['short']] = $option; |
32
|
26 |
|
} |
33
|
28 |
|
if (isset($option['long'])) { |
34
|
28 |
|
$this->map[$command][$option['long']] = $option; |
35
|
28 |
|
} |
36
|
28 |
|
} |
37
|
28 |
|
$this->options += $options; |
38
|
28 |
|
} |
39
|
|
|
|
40
|
28 |
|
private function fillOption($option) |
41
|
|
|
{ |
42
|
28 |
|
$option['has_value'] = isset($option['has_value']) ? $option['has_value'] : false; |
43
|
28 |
|
$option['command'] = isset($option['command']) ? $option['command'] : null; |
44
|
28 |
|
$option['multi'] = isset($option['multi']) ? $option['multi'] : null; |
45
|
28 |
|
$option['group'] = isset($option['group']) ? $option['group'] : null; |
46
|
28 |
|
return $option; |
47
|
|
|
} |
48
|
|
|
|
49
|
25 |
|
public function getMap() |
50
|
|
|
{ |
51
|
25 |
|
return $this->map; |
52
|
|
|
} |
53
|
|
|
|
54
|
4 |
|
private function stringOptionToArray($option) |
55
|
|
|
{ |
56
|
4 |
|
$newOption = []; |
57
|
4 |
|
if (strlen($option) == 1) { |
58
|
1 |
|
$newOption['short'] = $option; |
59
|
1 |
|
} else { |
60
|
4 |
|
$newOption['long'] = $option; |
61
|
|
|
} |
62
|
4 |
|
return $newOption; |
63
|
|
|
} |
64
|
|
|
|
65
|
8 |
|
public function getArray() |
66
|
|
|
{ |
67
|
8 |
|
return $this->options; |
68
|
|
|
} |
69
|
|
|
|
70
|
25 |
|
public function getDefaults() |
71
|
|
|
{ |
72
|
25 |
|
$defaults = []; |
73
|
25 |
|
foreach($this->options as $option) { |
74
|
25 |
|
if(array_key_exists('default', $option)) { |
75
|
1 |
|
$defaults[$option['long']] = $option['default']; |
76
|
1 |
|
} |
77
|
25 |
|
} |
78
|
25 |
|
return $defaults; |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
|