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
|
|
|
|