Options::normalize()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 8
cts 8
cp 1
rs 9.7998
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cascader;
6
7
use Cascader\Exception\InvalidOptionsException;
8
use Cascader\Exception\OptionNotSetException;
9
10
class Options
11
{
12
    /**
13
     * @var array
14
     */
15
    protected $options;
16
17 9
    final protected function __construct(array $options)
18
    {
19 9
        $this->options = $options;
20 9
    }
21
22 10
    public static function fromArray(array $options)
23
    {
24 10
        self::validate($options);
25 9
        $options = self::normalize($options);
26
27 9
        return new static($options);
28
    }
29
30 10
    final protected static function validate(array $options)
31
    {
32 10
        foreach ($options as $key => $value) {
33 9
            if (! \is_string($key)) {
34 1
                throw InvalidOptionsException::invalidKeys();
35
            }
36
        }
37 9
    }
38
39 9
    final protected static function normalize(array $options) : array
40
    {
41 9
        $normalizedOptions = [];
42
43 9
        foreach ($options as $key => $value) {
44 8
            $normalizedOptions[$key] = $value;
45
46 8
            $normalizedKey = str_replace(' ', '', ucwords(str_replace(['_', '-'], ' ', $key)));
47 8
            $normalizedKey[0] = strtolower($normalizedKey[0]);
48 8
            $normalizedOptions[$normalizedKey] = $value;
49
        }
50
51 9
        return $normalizedOptions;
52
    }
53
54 8
    public function has(string $key) : bool
55
    {
56 8
        return array_key_exists($key, $this->options);
57
    }
58
59 8
    public function get(string $key)
60
    {
61 8
        if (! $this->has($key)) {
62 6
            throw OptionNotSetException::forKey($key);
63
        }
64
65 7
        return $this->options[$key];
66
    }
67
}
68