Args::getArguments()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 16
ccs 9
cts 9
cp 1
rs 9.2
cc 4
eloc 9
nc 4
nop 1
crap 4
1
<?php
2
3
/*
4
 * This file is part of the webmozart/console package.
5
 *
6
 * (c) Bernhard Schussek <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Webmozart\Console\Api\Args;
13
14
use Webmozart\Console\Api\Args\Format\ArgsFormat;
15
use Webmozart\Console\Api\Args\Format\CommandName;
16
use Webmozart\Console\Api\Args\Format\CommandOption;
17
18
/**
19
 * The parsed console arguments.
20
 *
21
 * The parsed arguments provide access to the options and arguments passed via
22
 * the command line. Usually you can construct an {@link Args} instance by
23
 * parsing a {@link RawArgs} instance with an {@link ArgsParser}:
24
 *
25
 * ```php
26
 * $format = ArgsFormat::build()
27
 *     ->addCommandName(new CommandName('server'))
28
 *     ->addCommandName(new CommandName('add'))
29
 *     ->addOption(new Option('port', 'p', Option::VALUE_REQUIRED | Option::INTEGER))
30
 *     ->addArgument(new Argument('host', Argument::REQUIRED))
31
 *     ->getFormat();
32
 *
33
 * $args = $parser->parseArgs($rawArgs, $format);
34
 * ```
35
 *
36
 * The {@link ArgsFormat} defines which rules the console arguments must adhere
37
 * to.
38
 *
39
 * You can also create {@link Args} instances manually. This is especially
40
 * useful in tests:
41
 *
42
 * ```php
43
 * $format = ArgsFormat::build()
44
 *     ->addOption(new Option('port', 'p', Option::VALUE_REQUIRED | Option::INTEGER))
45
 *     ->addArgument(new Argument('host', Argument::REQUIRED))
46
 *     ->getFormat();
47
 *
48
 * $args = new Args($format);
49
 * $args->setOption('port', 80);
50
 * $args->setArgument('host', 'localhost');
51
 * ```
52
 *
53
 * @since  1.0
54
 *
55
 * @author Bernhard Schussek <[email protected]>
56
 *
57
 * @see    RawArgs, ArgsFormat, ArgsParser
58
 */
59
class Args
60
{
61
    /**
62
     * @var ArgsFormat
63
     */
64
    private $format;
65
66
    /**
67
     * @var RawArgs
68
     */
69
    private $rawArgs;
70
71
    /**
72
     * @var array
73
     */
74
    private $options = array();
75
76
    /**
77
     * @var array
78
     */
79
    private $arguments = array();
80
81
    /**
82
     * Creates the console arguments.
83
     *
84
     * @param ArgsFormat $format  The format that the arguments and options must
85
     *                            adhere to.
86
     * @param RawArgs    $rawArgs The raw console arguments.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $rawArgs not be null|RawArgs?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
87
     */
88 403
    public function __construct(ArgsFormat $format, RawArgs $rawArgs = null)
89
    {
90 403
        $this->format = $format;
91 403
        $this->rawArgs = $rawArgs;
92 403
    }
93
94
    /**
95
     * Returns the PHP script as it was called on the console.
96
     *
97
     * @return string|null The script name or null if no script name is
98
     *                     available.
99
     */
100
    public function getScriptName()
101
    {
102
        return $this->rawArgs ? $this->rawArgs->getScriptName() : null;
103
    }
104
105
    /**
106
     * Returns the command names as array.
107
     *
108
     * @return CommandName[] The command names.
109
     */
110 1
    public function getCommandNames()
111
    {
112 1
        return $this->format->getCommandNames();
113
    }
114
115
    /**
116
     * Returns the command options as array.
117
     *
118
     * @return CommandOption[] The command options.
119
     */
120 1
    public function getCommandOptions()
121
    {
122 1
        return $this->format->getCommandOptions();
123
    }
124
125
    /**
126
     * Returns an option.
127
     *
128
     * If the option accepts a value, the value set for that option is returned.
129
     * If no value was set with {@link setOption()}, the default value of the
130
     * option is returned.j
131
     *
132
     * If the option accepts no value, the method returns `true` if the option
133
     * was set and `false` otherwise.
134
     *
135
     * @param string $name The long or short option name.
136
     *
137
     * @return mixed The option value or `true`/`false` for options without
138
     *               values.
139
     *
140
     * @throws NoSuchOptionException If the option does not exist.
141
     */
142 13
    public function getOption($name)
143
    {
144 13
        $option = $this->format->getOption($name);
145
146 12
        if (array_key_exists($option->getLongName(), $this->options)) {
147 9
            return $this->options[$option->getLongName()];
148
        }
149
150 4
        if ($option->acceptsValue()) {
151 2
            return $option->getDefaultValue();
152
        }
153
154 2
        return false;
155
    }
156
157
    /**
158
     * Returns all options.
159
     *
160
     * By default, this method also includes the default values set for options
161
     * with values. You can disable this behavior by passing `false` for
162
     * `$includeDefaults`.
163
     *
164
     * @param bool $includeDefaults Whether to return the default values for
165
     *                              options that were not set.
166
     *
167
     * @return array The option values and `true`/`false` for options without
168
     *               values.
169
     *
170
     * @see getOption()
171
     */
172 38
    public function getOptions($includeDefaults = true)
173
    {
174 38
        $options = $this->options;
175
176 38
        if ($includeDefaults) {
177 8
            foreach ($this->format->getOptions() as $option) {
178 8
                $name = $option->getLongName();
179
180 8
                if (!array_key_exists($name, $options)) {
181 8
                    $options[$name] = $option->acceptsValue() ? $option->getDefaultValue() : false;
182
                }
183
            }
184
        }
185
186 38
        return $options;
187
    }
188
189
    /**
190
     * Sets an option.
191
     *
192
     * For options with values, you can pass the value in the second argument.
193
     * The value is converted to the type defined by the argument format.
194
     *
195
     * For options without values, you can omit the second argument. Optionally,
196
     * you can pass `true`/`false` explicitly to enable/disable the option.
197
     *
198
     * @param string $name  The long or short option name.
199
     * @param mixed  $value The value to set for the option.
200
     *
201
     * @return static The current instance.
202
     *
203
     * @throws NoSuchOptionException If the option does not exist.
204
     */
205 245
    public function setOption($name, $value = true)
206
    {
207 245
        $option = $this->format->getOption($name);
208
209 244
        if ($option->isMultiValued()) {
210 2
            $value = (array) $value;
211
212 2
            foreach ($value as $k => $v) {
213 2
                $value[$k] = $option->parseValue($v);
214
            }
215 242
        } elseif ($option->acceptsValue()) {
216 125
            $value = $option->parseValue($value);
217 121
        } elseif (false === $value) {
218 2
            unset($this->options[$option->getLongName()]);
219
220 2
            return $this;
221
        } else {
222 120
            $value = true;
223
        }
224
225 243
        $this->options[$option->getLongName()] = $value;
226
227 243
        return $this;
228
    }
229
230
    /**
231
     * Sets the values of multiple options.
232
     *
233
     * The existing options are preserved.
234
     *
235
     * @param array $options The options indexed by their long or short names
236
     *                       and their values.
237
     *
238
     * @return static The current instance.
239
     *
240
     * @see setOption()
241
     */
242 5
    public function addOptions(array $options)
243
    {
244 5
        foreach ($options as $name => $value) {
245 5
            $this->setOption($name, $value);
246
        }
247
248 5
        return $this;
249
    }
250
251
    /**
252
     * Sets the values of multiple options.
253
     *
254
     * The existing options are unset.
255
     *
256
     * @param array $options The options indexed by their long or short names
257
     *                       and their values.
258
     *
259
     * @return static The current instance.
260
     *
261
     * @see setOption()
262
     */
263 4
    public function setOptions(array $options)
264
    {
265 4
        $this->options = array();
266
267 4
        $this->addOptions($options);
268
269 4
        return $this;
270
    }
271
272
    /**
273
     * Returns whether an option is set.
274
     *
275
     * @param string $name The long or short option name.
276
     *
277
     * @return bool Returns `true` if the option is set and `false` otherwise.
278
     */
279 34
    public function isOptionSet($name)
280
    {
281 34
        return array_key_exists($name, $this->options);
282
    }
283
284
    /**
285
     * Returns whether an option is defined in the format.
286
     *
287
     * @param string $name The long or short option name.
288
     *
289
     * @return bool Returns `true` if the option exists and `false` otherwise.
290
     */
291 2
    public function isOptionDefined($name)
292
    {
293 2
        return $this->format->hasOption($name);
294
    }
295
296
    /**
297
     * Returns the value of an argument.
298
     *
299
     * If the argument is not set, the default value configured in the argument
300
     * format is returned.
301
     *
302
     * @param string|int $name The argument name or its 0-based position in the
303
     *                         argument list.
304
     *
305
     * @return mixed The value of the argument.
306
     *
307
     * @throws NoSuchArgumentException If the argument does not exist.
308
     */
309 38
    public function getArgument($name)
310
    {
311 38
        $argument = $this->format->getArgument($name);
312
313 37
        if (array_key_exists($argument->getName(), $this->arguments)) {
314 36
            return $this->arguments[$argument->getName()];
315
        }
316
317 2
        return $argument->getDefaultValue();
318
    }
319
320
    /**
321
     * Returns the values of all arguments.
322
     *
323
     * By default, this method also includes the default values of unset
324
     * arguments. You can disable this behavior by passing `false` for
325
     * `$includeDefaults`.
326
     *
327
     * @param bool $includeDefaults Whether to return the default values for
328
     *                              arguments that were not set.
329
     *
330
     * @return array The argument values.
331
     *
332
     * @see getArgument()
333
     */
334 36
    public function getArguments($includeDefaults = true)
335
    {
336 36
        $arguments = array();
337
338 36
        foreach ($this->format->getArguments() as $argument) {
339 24
            $name = $argument->getName();
340
341 24
            if (array_key_exists($name, $this->arguments)) {
342 23
                $arguments[$name] = $this->arguments[$name];
343 9
            } elseif ($includeDefaults) {
344 24
                $arguments[$name] = $argument->getDefaultValue();
345
            }
346
        }
347
348 36
        return $arguments;
349
    }
350
351
    /**
352
     * Sets the value of an argument.
353
     *
354
     * The value is converted to the type defined by the argument format.
355
     *
356
     * @param string|int $name  The argument name or its 0-based position in the
357
     *                          argument list.
358
     * @param mixed      $value The value of the argument.
359
     *
360
     * @return static The current instance.
361
     *
362
     * @throws NoSuchArgumentException If the argument does not exist.
363
     */
364 153
    public function setArgument($name, $value)
365
    {
366 153
        $argument = $this->format->getArgument($name);
367
368 152
        if ($argument->isMultiValued()) {
369 5
            $value = (array) $value;
370
371 5
            foreach ($value as $k => $v) {
372 5
                $value[$k] = $argument->parseValue($v);
373
            }
374
        } else {
375 147
            $value = $argument->parseValue($value);
376
        }
377
378 152
        $this->arguments[$argument->getName()] = $value;
379
380 152
        return $this;
381
    }
382
383
    /**
384
     * Sets the values of multiple arguments.
385
     *
386
     * The existing arguments are preserved.
387
     *
388
     * @param array $arguments The argument values indexed by the argument names
389
     *                         or their 0-based positions in the argument list.
390
     *
391
     * @return static The current instance.
392
     *
393
     * @see setArgument()
394
     */
395 5
    public function addArguments(array $arguments)
396
    {
397 5
        foreach ($arguments as $name => $value) {
398 5
            $this->setArgument($name, $value);
399
        }
400
401 5
        return $this;
402
    }
403
404
    /**
405
     * Sets the values of multiple arguments.
406
     *
407
     * The existing arguments are unset.
408
     *
409
     * @param array $arguments The argument values indexed by the argument names
410
     *                         or their 0-based positions in the argument list.
411
     *
412
     * @return static The current instance.
413
     *
414
     * @see setArgument()
415
     */
416 4
    public function setArguments(array $arguments)
417
    {
418 4
        $this->arguments = array();
419
420 4
        $this->addArguments($arguments);
421
422 4
        return $this;
423
    }
424
425
    /**
426
     * Returns whether an argument is set.
427
     *
428
     * @param string|int $name The argument name or its 0-based position in the
429
     *                         argument list.
430
     *
431
     * @return bool Returns `true` if the argument is set and `false` otherwise.
432
     */
433 59
    public function isArgumentSet($name)
434
    {
435 59
        return array_key_exists($name, $this->arguments);
436
    }
437
438
    /**
439
     * Returns whether an argument is defined in the format.
440
     *
441
     * @param string|int $name The argument name or its 0-based position in the
442
     *                         argument list.
443
     *
444
     * @return bool Returns `true` if the argument exists and `false` otherwise.
445
     */
446 2
    public function isArgumentDefined($name)
447
    {
448 2
        return $this->format->hasArgument($name);
449
    }
450
451
    /**
452
     * Returns the format of the console arguments.
453
     *
454
     * @return ArgsFormat The format.
455
     */
456 1
    public function getFormat()
457
    {
458 1
        return $this->format;
459
    }
460
461
    /**
462
     * Returns the raw console arguments.
463
     *
464
     * @return RawArgs The raw arguments.
465
     */
466 55
    public function getRawArgs()
467
    {
468 55
        return $this->rawArgs;
469
    }
470
}
471