Completed
Push — dev ( b7757b...454867 )
by James Ekow Abaka
01:37
created

ArgumentParser::setExitCallback()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace clearice\argparser;
4
5
6
/**
7
 * For parsing arguments in ClearIce
8
 *
9
 * @package clearice\argparser
10
 */
11
class ArgumentParser
12
{
13
    /**
14
     * Description to put on top of the help message.
15
     * @var string
16
     */
17
    private $description;
18
19
    /**
20
     * A little message for the foot of the help message.
21
     * @var string
22
     */
23
    private $footer;
24
25
    /**
26
     * The name of the application.
27
     * @var string
28
     */
29
    private $name;
30
31
    /**
32
     * Commands that the application can execute.
33
     * @var array
34
     */
35
    private $commands = [];
36
37
    /**
38
     * A cache of all the options added.
39
     * The array keys represents a concatenation of the command and either the short or long name of the option. Elements
40
     * in this array will be the same as those in the options property. However, options that have both a short and long
41
     * name would appear twice.
42
     * @var array
43
     */
44
    private $optionsCache = [];
45
46
    /**
47
     * All the possible options for arguments.
48
     * @var array
49
     */
50
    private $options = [];
51
52
    /**
53
     * An instance of the help generator.
54
     * @var HelpMessageGenerator
55
     */
56
    private $helpGenerator;
57
58
    /**
59
     * An instance of the validator.
60
     * @var Validator
61
     */
62
    private $validator;
63
64
    /**
65
     * A reference to a function to be called for exitting the entire application.
66
     * @var callable
67
     */
68
    private $exitFunction;
69
70
    /**
71
     * Flag raised when help has been enabled.
72
     * @var bool
73
     */
74
    private $helpEnabled = false;
75
76
    /**
77
     * ArgumentParser constructor.
78
     *
79
     * @param ValidatorInterface $validator
80
     * @param HelpGeneratorInterface $helpWriter
81
     */
82 15
    public function __construct(HelpGeneratorInterface $helpWriter = null, ValidatorInterface $validator = null)
83
    {
84 15
        $this->helpGenerator = $helpWriter ?? new HelpMessageGenerator();
85 15
        $this->validator = $validator ?? new Validator();
86
        $this->exitFunction = function ($code) { exit($code); };
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
87 15
    }
88
89
    /**
90
     * Add an option to the option cache for easy access through associative arrays.
91
     * The option cache associates arguments with their options.
92
     *
93
     * @param string $identifier
94
     * @param mixed $option
95
     * @throws OptionExistsException
96
     */
97 14
    private function addToOptionCache(string $identifier, $option) : void
98
    {
99 14
        if (!isset($option[$identifier])) {
100 2
            return;
101
        }
102 14
        $cacheKey = "${option['command']}${option[$identifier]}";
103 14
        if (!isset($this->optionsCache[$cacheKey])) {
104 14
            $this->optionsCache[$cacheKey] = $option;
105
        } else {
106 2
            throw new OptionExistsException(
107 2
                "An argument option with $identifier {$option['command']} {$option[$identifier]} already exists."
108
            );
109
        }
110 14
    }
111
112
    /**
113
     * @param string $command
114
     * @param string $name
115
     * @return mixed
116
     * @throws InvalidArgumentException
117
     */
118 8
    private function retrieveOptionFromCache(string $command, string $name)
119
    {
120 8
        $key = $command . $name;
121 8
        if(isset($this->optionsCache[$key])) {
122 7
            return $this->optionsCache[$key];
123 1
        } else if(isset($this->optionsCache[$name]) && $this->optionsCache[$name]['command'] == "") {
124 1
            return $this->optionsCache[$name];
125
        } else{
126
            throw new InvalidArgumentException("Unknown option '$name'. Please run with `--help` for more information on valid options.");
127
        }
128
    }
129
130
    /**
131
     * Add an option to be parsed.
132
     * Arguments are presented as a structured array with the following possible keys.
133
     *
134
     *  name: The name of the option prefixed with a double dash --
135
     *  short_name: A shorter single character option prefixed with a single dash -
136
     *  type: Required for all options that take values. An option specified without a type is considered to be a
137
     *        boolean flag.
138
     *  repeats: A boolean value that states whether the option can be repeated or not. Repeatable options are returned
139
     *        as arrays.
140
     *  default: A default value for the option.
141
     *  help: A help message for the option
142
     *
143
     * @param array $option
144
     * @throws OptionExistsException
145
     * @throws InvalidArgumentDescriptionException
146
     * @throws UnknownCommandException
147
     */
148 15
    public function addOption(array $option): void
149
    {
150 15
        $this->validator->validateOption($option, $this->commands);
151 14
        $option['command'] = $option['command'] ?? '';
152 14
        $option['repeats'] = $option['repeats'] ?? false;
153 14
        $this->options[] = $option;
154 14
        $this->addToOptionCache('name', $option);
155 14
        $this->addToOptionCache('short_name', $option);
156 14
    }
157
158
    /**
159
     * @param $arguments
160
     * @param $argPointer
161
     * @return mixed
162
     * @throws InvalidValueException
163
     */
164 5
    private function getNextValueOrFail($arguments, &$argPointer, $name)
165
    {
166 5
        if (isset($arguments[$argPointer + 1]) && $arguments[$argPointer + 1][0] != '-') {
167 3
            $argPointer++;
168 3
            return $arguments[$argPointer];
169
        } else {
170 2
            throw new InvalidValueException("A value must be passed along with argument $name.");
171
        }
172
    }
173
174
    /**
175
     * Parse a long argument that is prefixed with a double dash "--"
176
     *
177
     * @param $arguments
178
     * @param $argPointer
179
     * @throws InvalidValueException
180
     * @throws InvalidArgumentException
181
     */
182 6
    private function parseLongArgument($command, $arguments, &$argPointer, &$output)
183
    {
184 6
        $string = substr($arguments[$argPointer], 2);
185 6
        preg_match("/(?<name>[a-zA-Z_0-9-]+)(?<equal>=?)(?<value>.*)/", $string, $matches);
186 6
        $option = $this->retrieveOptionFromCache($command, $matches['name']);
187 6
        $value = true;
188
189 6
        if (isset($option['type'])) {
190 4
            if ($matches['equal'] === '=') {
191 1
                $value = $matches['value'];
192
            } else {
193 4
                $value = $this->getNextValueOrFail($arguments, $argPointer, $matches['name']);
194
            }
195
        }
196
197 5
        $this->assignValue($option, $output, $option['name'], $value);
198 5
    }
199
200
    /**
201
     * Parse a short argument that is prefixed with a single dash '-'
202
     *
203
     * @param $command
204
     * @param $arguments
205
     * @param $argPointer
206
     * @throws InvalidValueException
207
     * @throws InvalidArgumentException
208
     */
209 3
    private function parseShortArgument($command, $arguments, &$argPointer, &$output)
210
    {
211 3
        $argument = $arguments[$argPointer];
212 3
        $option = $this->retrieveOptionFromCache($command, substr($argument, 1, 1));
213 3
        $value = true;
214
215 3
        if (isset($option['type'])) {
216 3
            if (substr($argument, 2) != "") {
217 2
                $value = substr($argument, 2);
218
            } else {
219 2
                $value = $this->getNextValueOrFail($arguments, $argPointer, $option['name']);
220
            }
221
        }
222
223 2
        $this->assignValue($option, $output, $option['name'], $value);
224 2
    }
225
226 6
    private function assignValue($option, &$output, $key, $value)
227
    {
228 6
        if($option['repeats']) {
229 1
            $output[$key] = isset($output[$key]) ? array_merge($output[$key], [$value]) : [$value];
230
        } else {
231 5
            $output[$key] = $value;
232
        }
233 6
    }
234
235
    /**
236
     * @param $arguments
237
     * @param $argPointer
238
     * @param $output
239
     * @throws InvalidValueException
240
     * @throws InvalidArgumentException
241
     */
242 8
    private function parseArgumentArray($arguments, &$argPointer, &$output)
243
    {
244 8
        $numArguments = count($arguments);
245 8
        $command = $output['__command'] ?? '';
246 8
        for (; $argPointer < $numArguments; $argPointer++) {
247 8
            $arg = $arguments[$argPointer];
248 8
            if (substr($arg, 0, 2) == "--") {
249 6
                $this->parseLongArgument($command, $arguments, $argPointer, $output);
250 3
            } else if ($arg[0] == '-') {
251 3
                $this->parseShortArgument($command, $arguments, $argPointer, $output);
252
            } else {
253 1
                $output['__args'] = isset($output['__args']) ? array_merge($output['__args'], [$arg]) : [$arg];
254
            }
255
        }
256 6
    }
257
258
    /**
259
     * @param $output
260
     * @throws HelpMessageRequestedException
261
     */
262 6
    private function maybeShowHelp($output)
263
    {
264 6
        if ((isset($output['help']) && $output['help'] && $this->helpEnabled)) {
265 1
            print $this->getHelpMessage($output['__command'] ?? null);
266 1
            throw new HelpMessageRequestedException();
267
        }
268
269 5
        if(isset($output['__command']) && $output['__command'] == 'help' && $this->helpEnabled) {
270
            print $this->getHelpMessage($output['__args'][0] ?? null);
271
        }
272 5
    }
273
274 8
    private function parseCommand($arguments, &$argPointer, &$output)
275
    {
276 8
        if (count($arguments) > 1 && isset($this->commands[$arguments[$argPointer]])) {
277 2
            $output["__command"] = $arguments[$argPointer];
278 2
            $argPointer++;
279
        }
280 8
    }
281
282
    /**
283
     * @param $parsed
284
     */
285 5
    private function fillInDefaults(&$parsed)
286
    {
287 5
        foreach($this->options as $option) {
288 5
            if(!isset($parsed[$option['name']]) && isset($option['default']) && $option['command'] == ($parsed['__command'] ?? "")) {
289 1
                $parsed[$option['name']] = $option['default'];
290
            }
291
        }
292 5
    }
293
294
    /**
295
     * A function called to exit the application whenever there's a parsing error or after requested help has been
296
     * displayed/
297
     *
298
     * @param callable $exit
299
     */
300 1
    public function setExitCallback(callable $exit)
301
    {
302 1
        $this->exitFunction = $exit;
303 1
    }
304
305
    /**
306
     * Parses command line arguments and return a structured array of options and their associated values.
307
     *
308
     * @param array $arguments An optional array of arguments that would be parsed instead of those passed to the CLI.
309
     * @return array
310
     * @throws InvalidValueException
311
     */
312 8
    public function parse($arguments = null)
313
    {
314
        try{
315 8
            global $argv;
316 8
            $arguments = $arguments ?? $argv;
317 8
            $argPointer = 1;
318 8
            $parsed = [];
319 8
            $this->name = $this->name ?? $arguments[0];
320 8
            $this->parseCommand($arguments, $argPointer, $parsed);
321 8
            $this->parseArgumentArray($arguments, $argPointer, $parsed);
322 6
            $this->maybeShowHelp($parsed);
323 5
            $this->validator->validateArguments($this->options, $parsed);
324 5
            $this->fillInDefaults($parsed);
325 5
            $parsed['__executed'] = $this->name;
326 5
            return $parsed;
327 3
        } catch (HelpMessageRequestedException $exception) {
328 1
            ($this->exitFunction)(0);
329 2
        } catch (InvalidArgumentException $exception) {
330
            print $exception->getMessage() . PHP_EOL;
331
            ($this->exitFunction)(1024);
332
        }
333 1
    }
334
335
    /**
336
     * Enables help messages so they show automatically.
337
     * This method also allows you to optionally pass the name of the application, a description header for the help 
338
     * message and a footer.
339
     *
340
     * @param string $name The name of the application binary
341
     * @param string $description A description to be displayed on top of the help message
342
     * @param string $footer A footer message to be displayed after the help message
343
     *
344
     * @throws InvalidArgumentDescriptionException
345
     * @throws OptionExistsException
346
     * @throws UnknownCommandException
347
     */
348 2
    public function enableHelp(string $description = null, string $footer = null, string $name = null) : void
349
    {
350 2
        global $argv;
351 2
        $this->name = $name ?? $argv[0];
352 2
        $this->description = $description;
353 2
        $this->footer = $footer;
354 2
        $this->helpEnabled = true;
355 2
        $this->addOption([
356 2
            'name' => 'help',
357
            'short_name' => 'h', 'help' => "display this help message"
358
        ]);
359 2
        if($this->commands) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->commands of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
360 1
            $this->addCommand(['name' => 'help', 'help' => "display help for any command\nUsage: {$this->name} help [command]"]);
361 1
            foreach($this->commands as $command) {
362 1
                $this->addOption([
363 1
                    'name' => 'help',
364 1
                    'help' => 'display this help message',
365 1
                    'command' => $command['name']
366
                ]);
367
            }
368
        }
369 2
    }
370
371 2
    public function getHelpMessage($command = '')
372
    {
373 2
        return $this->helpGenerator->generate(
374 2
            $this->name, $command ?? null,
375 2
            ['options' => $this->options, 'commands' => $this->commands],
376 2
            $this->description, $this->footer
377
        );
378
    }
379
380
    /**
381
     * @param $command
382
     * @throws CommandExistsException
383
     * @throws InvalidArgumentDescriptionException
384
     */
385 6
    public function addCommand($command)
386
    {
387 6
        $this->validator->validateCommand($command, $this->commands);
388 6
        $this->commands[$command['name']] = $command;
389 6
    }
390
}
391