aboutsummaryrefslogtreecommitdiff
path: root/cli/getopts.php
blob: dde439f8e0191a1f509c5f4c93548f30c0c19a94 (plain)
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
<?php

    /*

        getopts by ALeX Kazik

        Code: https://github.com/alexkazik/getopts
        Docs: https://github.com/alexkazik/getopts/wiki/Documentation
        Homepage: http://alex.kazik.de/195/getopts/

        License: Creative Commons Attribution 3.0 Unported License
        http://creativecommons.org/licenses/by/3.0/

    */

    function getopts($params, $args=NULL, $raw=false){
        // check input
        if(!is_array($params)){
            trigger_error('Invalid params table', E_USER_ERROR);
        }
        if($args === NULL && is_array($_SERVER['argv'])){
            $args = $_SERVER['argv'];
            array_shift($args);
        }
        if(!is_array($args)){
            trigger_error('Invalid args table', E_USER_ERROR);
        }
        if(!is_bool($raw)){
            trigger_error('Invalid raw option', E_USER_ERROR);
        }

        // mb_substr, which returns '' in case of an empty mb_substr (usually false)
        $mb_substr = function ($string, $start, $length = null) { // is not used, only for definition
            $ret = call_user_func_array('mb_substr', func_get_args());
            if ($ret === false){
               return '';
            } else {
                return $ret;
            }
        };

        // get arg (either implicit or the following)
        $get_arg = function (&$next, &$args, &$num) { // pass by reference: num may be changed, others: performance
            if ($next !== true) {
                return $next;
            } elseif ($num + 1 >= count($args)){
                return false;
            } else {
                $num += 1;
                return $args[$num];
            }
        };

        // all types & subtypes
        $types_subtypes = ['S' => 'stcr', 'V' => 'smar', 'O' => 'smar', 'A' => 'sr'];

        // output
        $Ores = [];
        $Oerr = [];
        $Oags = [];

        // parsed options
        $short = [];
        $long = [];
        $type = [];

        // parse options
        foreach($params AS $opt => $names){
            if(is_string($names)){
                $names = preg_split('/ +/', $names);
            }
            if(!is_array($names) || count($names) < 2){
                trigger_error('Invalid type/name(s) to param "'.$opt.'"', E_USER_ERROR);
            }

            $ty = array_shift($names);
            if(!is_string($ty) || mb_strlen($ty) < 1 || mb_strlen($ty) > 2){
                trigger_error('Invalid type to param "'.$opt.'"', E_USER_ERROR);
            }
            $ty0 = $ty[0];
            if(!isset($types_subtypes[$ty0])){
                trigger_error('Invalid type to param "'.$opt.'"', E_USER_ERROR);
            }
            if(mb_strlen($ty) == 1){
                $ty1 = $types_subtypes[$ty0][0];
            }else{
                $ty1 = $ty[1];
                if(mb_strpos($types_subtypes[$ty0], $ty1) === false){
                    trigger_error('Invalid type to param "'.$opt.'"', E_USER_ERROR);
                }
            }
            $type[$opt] = $ty0.$ty1;

            foreach($names AS $name){
                if(!is_string($name)){
                    trigger_error('Invalid names to param "'.$opt.'"', E_USER_ERROR);
                }
                if(!preg_match('!^(-)?([0-9a-zA-Z]+)$!', $name, $r)){
                    trigger_error('Invalid name to param "'.$opt.'"', E_USER_ERROR);
                }
                if($r[1] == '-' || mb_strlen($r[2]) > 1){
                    if(isset($long[$r[2]])){
                        trigger_error('Duplicate option name "'.$r[2].'"', E_USER_ERROR);
                    }
                    $long[$r[2]] = $opt;
                }else{
                    if(isset($short[$r[2]])){
                        trigger_error('Duplicate option name "'.$r[2].'"', E_USER_ERROR);
                    }
                    $short[$r[2]] = $opt;
                }
            }

            $Ores[$opt] = [];
        }

        // parse arguments
        for($num=0; $num<count($args); $num++){
            $arg = $args[$num];

            if($arg == '--'){
                // end of options, copy all other args
                $num++;
                for(; $num<count($args); $num++){
                    $Oags[] = $args[$num];
                }
                break;
            }else if($arg == ''){
                // empty -> skip
                continue;
            }else if($arg[0] != '-'){
                // not an option -> copy to args
                $Oags[] = $arg;
                continue;
            }

            // this arg is an option!
            if($arg[1] == '-'){
                // long option
                $p = mb_strpos($arg, '=');
                if($p !== false){
                    $next = $mb_substr($arg, $p+1);
                    $arg = mb_substr($arg, 2, $p-2);
                }else{
                    $next = true;
                    $arg = mb_substr($arg, 2);
                }
                if(!isset($long[$arg])){
                    $Oerr[] = 'Unknown option "--'.$arg.'"';
                }else{
                    $opt = $long[$arg];
                    $Earg = '--'.$arg;
                    switch($type[$opt][0]){
                    case 'S':
                        $Ores[$opt][] = $next;
                        break;
                    case 'V':
                        if(($val = $get_arg($next,$args,$num)) === false){
                            $Oerr[] = 'Missing artument to option "'.$Earg.'"';
                        }else{
                            $Ores[$opt][] = $val;
                        }
                        break;
                    case 'O':
                        $Ores[$opt][] = $next;
                        break;
                    case 'A':
                        if(($val = $get_arg($next,$args,$num)) === false){
                            $Oerr[] = 'Missing artument to option "'.$Earg.'"';
                        }else{
                            $p = mb_strpos($val, '=');
                            if($p === false){
                                $Oerr[] = 'Malformed artument to option "'.$Earg.'" (a "=" is missing)';
                            }else if(isset($Ores[$opt][mb_substr($val, 0, $p)])){
                                $Oerr[] = 'Duplicate key "'.mb_substr($val, 0, $p).'" to option "'.$Earg.'"';
                            }else{
                                $Ores[$opt][mb_substr($val, 0, $p)] = $mb_substr($val, $p+1);
                            }
                        }
                        break;
                    }
                }
            }else{
                // short option(s)
                for($i=1; $i<mb_strlen($arg); $i++){
                    $c = $arg[$i];
                    $next = $mb_substr($arg, $i+1);
                    if($next == ''){
                        $next = true;
                    }else if($next[0] == '='){
                        $next = $mb_substr($next, 1);
                    }
                    if(!isset($short[$c])){
                        $Oerr[] = 'Unknown option "-'.$c.'"';
                        $i = mb_strlen($arg);
                    }else{
                        $opt = $short[$c];
                        $Earg = '-'.$c;
                        switch($type[$opt][0]){
                        case 'S':
                            $Ores[$opt][] = true;
                            break;
                        case 'V':
                            if(($val = $get_arg($next,$args,$num)) === false){
                                $Oerr[] = 'Missing artument to option "'.$Earg.'"';
                            }else{
                                $Ores[$opt][] = $val;
                            }
                            $i = mb_strlen($arg);
                            break;
                        case 'O':
                            $Ores[$opt][] = $next;
                            $i = mb_strlen($arg);
                            break;
                        case 'A':
                            if(($val = $get_arg($next,$args,$num)) === false){
                                $Oerr[] = 'Missing artument to option "'.$Earg.'"';
                            }else{
                                $p = mb_strpos($val, '=');
                                if($p === false){
                                    $Oerr[] = 'Malformed artument to option "'.$Earg.'" (a "=" is missing)';
                                }else if(isset($Ores[$opt][mb_substr($val, 0, $p)])){
                                    $Oerr[] = 'Duplicate key "'.mb_substr($val, 0, $p).'" to option "'.$Earg.'"';
                                }else{
                                    $Ores[$opt][mb_substr($val, 0, $p)] = $mb_substr($val, $p+1);
                                }
                            }
                            $i = mb_strlen($arg);
                            break;
                        }
                    }
                }
            }
        }

        // reformat result
        if(!$raw){
            foreach($Ores AS $opt => &$r){
                switch($type[$opt]){
                case 'Ss':
                    $r = count($r) > 0;
                    break;
                case 'St':
                    $r = (count($r) & 1) == 1;
                    break;
                case 'Sc':
                    $r = count($r);
                    break;

                case 'Vs':
                    if(count($r) == 0){
                        // no option
                        $r = false;
                    }else{
                        // pick last entry
                        $r = array_pop($r);
                    }
                    break;

                case 'Os':
                    if(count($r) == 0){
                        // no option
                        $r = false;
                    }else{
                        // pick last entry; if possible last used (non true) entry
                        do{
                            $rr = array_pop($r);
                        }while($rr === true && count($r) > 0);
                        $r = $rr;
                    }
                    break;

                case 'Vm':
                case 'Om':
                    if(count($r) == 0){
                        // no option
                        $r = false;
                    }else{
                        // as array
                        // (already done)
                    }
                    break;

                case 'Va':
                case 'Oa':
                    // false if none, direct (string) if only one, array otherwise
                    if(count($r) == 0){
                        // no option
                        $r = false;
                    }else if(count($r) == 1){
                        // a single option
                        $r = array_pop($r);
                    }else{
                        // as array
                        // (already done)
                    }
                    break;

                case 'As':
                    // as array
                    // (already done)
                    break;

                }
            }
        }

        // errors?
        if(count($Oerr) == 0){
            $Oerr = false;
        }

        // result
        return [$Oerr, $Ores, $Oags];
    }

?>