Completed
Push — master ( 3c559e...05a21e )
by Nikola
02:55
created

Options::toArray()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
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 6
    protected function __construct(array $options)
18
    {
19 6
        $this->options = $options;
20 6
    }
21
22 7
    public static function fromArray(array $options)
23
    {
24 7
        self::validateOptions($options);
25 6
        $options = self::normalizeOptions($options);
26
27 6
        return new static($options);
28
    }
29
30 7
    final protected static function validateOptions(array $options)
31
    {
32 7
        foreach ($options as $key => $value) {
33 6
            if (!is_string($key)) {
34 6
                throw InvalidOptionsException::forInvalidKeys();
35
            }
36
        }
37 6
    }
38
39 6
    final protected static function normalizeOptions(array $options) : array
40
    {
41 6
        $normalizedOptions = [];
42
43 6
        foreach ($options as $key => $value) {
44 5
            $normalizedKey = str_replace(' ', '', ucwords(str_replace(['_', '-'], ' ', $key)));
45 5
            $normalizedKey[0] = strtolower($normalizedKey[0]);
46
47 5
            $normalizedOptions[$normalizedKey] = $value;
48
        }
49
50 6
        return $normalizedOptions;
51
    }
52
53 5
    public function has(string $key) : bool
54
    {
55 5
        return array_key_exists($key, $this->options);
56
    }
57
58 5
    public function get(string $key)
59
    {
60 5
        if (!$this->has($key)) {
61 4
            throw OptionNotSetException::forKey($key);
62
        }
63
64 4
        return $this->options[$key];
65
    }
66
}
67