Completed
Push — dev ( edab28...49e8ae )
by James Ekow Abaka
01:13
created

ArgumentParser::fillInDefaults()   B

Complexity

Conditions 8
Paths 10

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 8

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 7.7777
c 0
b 0
f 0
ccs 5
cts 5
cp 1
cc 8
eloc 9
nc 10
nop 1
crap 8
1
<?php
2
3
namespace clearice\argparser;
4
use clearice\utils\ProgramControl;
5
6
7
/**
8
 * Class ArgumentParser
9
 *
10
 * @package clearice\argparser
11
 */
12
class ArgumentParser
13
{
14
    private $description;
15
16
    private $footer;
17
18
    private $name;
19
20
    private $commands = [];
21
22
    /**
23
     * @var array
24
     */
25
    private $optionsCache = [];
26
27
    /**
28
     * All the possible options for arguments.
29
     * @var array
30
     */
31
    private $options = [];
32
33
    /**
34
     * An instance of the help generator.
35
     * @var HelpMessageGenerator
36
     */
37
    private $helpGenerator;
38
39
    private $programControl;
40 14
41
    private $helpEnabled = false;
42 14
43 14
    public function __construct($helpWriter = null, $programControl = null)
44
    {
45
        $this->helpGenerator = $helpWriter ?? new HelpMessageGenerator();
46
        $this->programControl = $programControl ?? new ProgramControl();
47
    }
48
49
    /**
50
     * Add a value to the available possible options for later parsing.
51
     *
52 13
     * @param string $key
53
     * @param array $value
54 13
     * @throws OptionExistsException
55 1
     */
56
    private function addToOptionCache(string $key, array $value) : void
57
    {
58
        if (!isset($value[$key])) {
59 13
            return;
60
        }
61 2
        $cacheKey = "${value['command']}${value[$key]}";
62 2
        if (!isset($this->optionsCache[$cacheKey])) {
63
            $this->optionsCache[$cacheKey] = $value;
64
        } else {
65 13
            throw new OptionExistsException(
66
                "An argument option with $key {$value['command']} {$value[$key]} already exists."
67
            );
68
        }
69
    }
70
71
    /**
72
     * @param array $option
73
     * @throws InvalidArgumentDescriptionException
74 14
     * @throws UnknownCommandException
75 1
     */
76
    private function validateOption($option) : void
77 13
    {
78 1
        if (!isset($option['name'])) {
79
            throw new InvalidArgumentDescriptionException("Argument must have a name");
80 13
        }
81
        if (isset($option['command']) && !isset($this->commands[$option['command']])) {
82
            throw new UnknownCommandException("The command {$option['command']} is unknown");
83
        }
84
    }
85
86
    /**
87
     * Add an option to be parsed.
88
     * Arguments are presented as a structured array with the following possible keys.
89
     *
90
     *  name: The name of the option prefixed with a double dash --
91
     *  short_name: A shorter single character option prefixed with a single dash -
92
     *  type: Required for all options that take values. An option specified without a type is considered to be a
93
     *        boolean flag.
94
     *  repeats: A boolean value that states whether the option can be repeated or not. Repeatable options are returned
95
     *        as arrays.
96
     *  default: A default value for the option.
97
     *  help: A help message for the option
98
     *
99
     * @param array $option
100
     * @throws OptionExistsException
101
     * @throws InvalidArgumentDescriptionException
102 14
     * @throws UnknownCommandException
103 13
     */
104 13
    public function addOption(array $option): void
105 13
    {
106 13
        $this->validateOption($option);
107 13
        $option['command'] = $option['command'] ?? '';
108 13
        $option['repeats'] = $option['repeats'] ?? false;
109
        $this->options[] = $option;
110
        $this->addToOptionCache('name', $option);
111
        $this->addToOptionCache('short_name', $option);
112
    }
113
114
    /**
115
     * @param $arguments
116
     * @param $argPointer
117
     * @return mixed
118 5
     * @throws InvalidValueException
119 3
     */
120 3
    private function getNextValueOrFail($arguments, &$argPointer, $name)
121
    {
122 2
        if (isset($arguments[$argPointer + 1]) && $arguments[$argPointer + 1][0] != '-') {
123
            $argPointer++;
124
            return $arguments[$argPointer];
125
        } else {
126
            throw new InvalidValueException("A value must be passed along with argument $name.");
127
        }
128
    }
129
130
    /**
131
     * Parse a long argument that is prefixed with a double dash "--"
132
     *
133
     * @param $arguments
134
     * @param $argPointer
135 5
     * @throws InvalidValueException
136 5
     */
137 5
    private function parseLongArgument($command, $arguments, &$argPointer, &$output)
138 5
    {
139 5
        $string = substr($arguments[$argPointer], 2);
140
        preg_match("/(?<name>[a-zA-Z_0-9-]+)(?<equal>=?)(?<value>.*)/", $string, $matches);
141 5
        $name = $command . $matches['name'];
142 4
        $option = $this->optionsCache[$name];
143 1
        $value = true;
144
145 4
        if (isset($option['type'])) {
146
            if ($matches['equal'] === '=') {
147
                $value = $matches['value'];
148
            } else {
149 4
                $value = $this->getNextValueOrFail($arguments, $argPointer, $name);
150 4
            }
151
        }
152
153
        $this->assignValue($option, $output, $option['name'], $value);
154
    }
155
156
    /**
157
     * Parse a short argument that is prefixed with a single dash '-'
158
     *
159
     * @param $command
160
     * @param $arguments
161
     * @param $argPointer
162 3
     * @throws InvalidValueException
163 3
     */
164 3
    public function parseShortArgument($command, $arguments, &$argPointer, &$output)
165 3
    {
166
        $argument = $arguments[$argPointer];
167 3
        $key = $command . substr($argument, 1, 1);
168 3
        $option = $this->optionsCache[$key];
169 2
        $value = true;
170
171 2
        if (isset($option['type'])) {
172
            if (substr($argument, 2) != "") {
173
                $value = substr($argument, 2);
174
            } else {
175 2
                $value = $this->getNextValueOrFail($arguments, $argPointer, $option['name']);
176 2
            }
177
        }
178
179
        $this->assignValue($option, $output, $option['name'], $value);
180 5
    }
181 1
182
    private function assignValue($option, &$output, $key, $value)
183 4
    {
184
        if($option['repeats']) {
185 5
            $output[$key] = isset($output[$key]) ? array_merge($output[$key], [$value]) : [$value];
186
        } else {
187
            $output[$key] = $value;
188
        }
189
    }
190
191
    /**
192
     * @param $arguments
193
     * @param $argPointer
194
     * @param $output
195 7
     * @throws InvalidValueException
196 7
     */
197 7
    private function parseArgumentArray($arguments, &$argPointer, &$output)
198 7
    {
199 7
        $numArguments = count($arguments);
200 5
        $command = $output['__command'] ?? '';
201 3
        for (; $argPointer < $numArguments; $argPointer++) {
202 3
            $arg = $arguments[$argPointer];
203
            if (substr($arg, 0, 2) == "--") {
204 1
                $this->parseLongArgument($command, $arguments, $argPointer, $output);
205
            } else if ($arg[0] == '-') {
206
                $this->parseShortArgument($command, $arguments, $argPointer, $output);
207 5
            } else {
208
                $output['__args'] = isset($output['__args']) ? array_merge($output['__args'], [$arg]) : [$arg];
209
            }
210
        }
211 6
    }
212 2
213 2
    /**
214 2
     * @param $output
215 2
     * @throws HelpMessageRequestedException
216
     */
217
    private function maybeShowHelp($output)
218 4
    {
219
        if ((isset($output['help']) && $output['help'] && $this->helpEnabled)) {
220
            print $this->getHelpMessage($output['__command'] ?? null);
221
            throw new HelpMessageRequestedException();
222
        }
223 7
    }
224 1
225 1
    public function parseCommand($arguments, &$argPointer, &$output)
226
    {
227 7
        if (count($arguments) > 1 && isset($this->commands[$arguments[$argPointer]])) {
228
            $output["__command"] = $arguments[$argPointer];
229
            $argPointer++;
230
        }
231 5
    }
232 5
233 5
    /**
234
     * @param $parsed
235
     * @throws InvalidArgumentException
236 5
     */
237
    public function fillInDefaults(&$parsed)
238
    {
239
        $required = [];
240
        foreach($this->options as $option) {
241
            if(!isset($parsed[$option['name']]) && isset($option['default'])) {
242
                $parsed[$option['name']] = $option['default'];
243
            }
244
            if(isset($option['required']) && $option['required'] && !isset($parsed[$option['name']])) {
245
                $required[] = $option['name'];
246
            }
247 7
        }
248 7
249 7
        if(!empty(($required))) {
250 7
            throw new InvalidArgumentException(
251 7
                sprintf("The following options are required: %s. Pass the --help option for more information about possible options.", implode(", $required"))
0 ignored issues
show
Bug introduced by
', '.$required of type string is incompatible with the type array expected by parameter $pieces of implode(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

251
                sprintf("The following options are required: %s. Pass the --help option for more information about possible options.", implode(/** @scrutinizer ignore-type */ ", $required"))
Loading history...
252 7
            );
253 7
        }
254 5
    }
255 5
256 5
    /**
257
     * Parses command line arguments and return a structured array of options and their associated values.
258
     *
259
     * @param array $arguments An optional array of arguments that would be parsed instead of those passed to the CLI.
260
     * @return array
261
     * @throws InvalidValueException
262
     */
263
    public function parse($arguments = null)
264
    {
265
        try{
266
            global $argv;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
267
            $arguments = $arguments ?? $argv;
268
            $argPointer = 1;
269
            $parsed = [];
270
            $this->name = $this->name ?? $arguments[0];
271
            $this->parseCommand($arguments, $argPointer, $parsed);
272 2
            $this->parseArgumentArray($arguments, $argPointer, $parsed);
273 2
            $this->fillInDefaults($parsed);
274 2
            $this->maybeShowHelp($parsed);
275 2
            return $parsed;
276 2
        } catch (HelpMessageRequestedException $exception) {
277 2
            $this->programControl->quit();
278
        } catch (InvalidArgumentException $exception) {
279
            print $exception->getMessage();
280
            $this->programControl->quit();
281 1
        }
282
    }
283
284
    /**
285
     * Enables help messages so they show automatically.
286
     *
287
     * @param string $name
288
     * @param string $description
289
     * @param string $footer
290
     *
291 5
     * @throws InvalidArgumentDescriptionException
292 1
     * @throws OptionExistsException
293
     * @throws UnknownCommandException
294 5
     */
295 1
    public function enableHelp(string $description = null, string $footer = null, string $name = null) : void
296
    {
297 5
        $this->name = $name;
298 5
        $this->description = $description;
299
        $this->footer = $footer;
300
        $this->helpEnabled = true;
301
        $this->addOption(['name' => 'help', 'short_name' => 'h', 'help' => "display this help message"]);
302
    }
303
304
    public function getHelpMessage($command = '')
305
    {
306
        return $this->helpGenerator->generate(
307
            $this->name, $command ?? null,
308
            ['options' => $this->options, 'commands' => $this->commands],
309
            $this->description, $this->footer
310
        );
311
    }
312
313
    /**
314
     * @param $command
315
     * @throws CommandExistsException
316
     * @throws InvalidArgumentDescriptionException
317
     */
318
    public function addCommand($command)
319
    {
320
        if (!isset($command['name'])) {
321
            throw new InvalidArgumentDescriptionException("Command description must contain a name");
322
        }
323
        if (isset($this->commands[$command['name']])) {
324
            throw new CommandExistsException("Command ${command['name']} already exists.");
325
        }
326
        $this->commands[$command['name']] = $command;
327
    }
328
}
329