Completed
Push — master ( 8e3b2f...ffac26 )
by Michał
04:23
created

Options::set()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 24
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 24
c 0
b 0
f 0
rs 8.5125
cc 5
eloc 10
nc 5
nop 2
1
<?php namespace nyx\console\input\parameter\values;
2
3
// External dependencies
4
use nyx\core;
5
6
// Internal dependencies
7
use nyx\console\input\parameter;
8
use nyx\console\input;
9
10
/**
11
 * Input Options
12
 *
13
 * @version     0.1.0
14
 * @author      Michal Chojnacki <[email protected]>
15
 * @copyright   2012-2017 Nyx Dev Team
16
 * @link        https://github.com/unyx/nyx
17
 */
18
class Options extends parameter\Values
19
{
20
    /**
21
     * {@inheritdoc}
22
     *
23
     * Overridden to enforce a stricter Definitions collection type.
24
     */
25
    public function __construct(parameter\definitions\Options $definition)
26
    {
27
        parent::__construct($definition);
28
    }
29
30
    /**
31
     * {@inheritdoc}
32
     */
33
    public function set($name, $value) : core\collections\interfaces\Map
34
    {
35
        $option = $this->assertIsDefined($name);
36
37
        // Handle value expectations appropriately.
38
        if (!$expected = $option->getValue()) {
39
            if (isset($value)) {
40
                throw new \RuntimeException("The option [--$name] does not take any values.");
41
            }
42
        } elseif (isset($value)) {
43
            if ($expected->is(input\Value::REQUIRED)) {
44
                throw new \RuntimeException("The option [--$name] requires a value.");
45
            }
46
47
            // Grab the default value in this case, since we're dealing with an optional value that was
48
            // not explicitly set.
49
            $value = $expected->getDefault();
50
        }
51
52
        // Slight overhead, because the parent will grab the definition again, but at the same time
53
        // it handles multiple value parameters for us. Setting boolean true here if $value is still
54
        // not set, which covers Options which do not accept values but still get set (ie. flags).
55
        return parent::set($name, $value ?? true);
56
    }
57
}
58