Optionable::options()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 7
rs 10
1
<?php
2
3
namespace Cesargb\Log;
4
5
use LogicException;
6
7
trait Optionable
8
{
9
    /**
10
     * @var string[]
11
     */
12
    private array $validMethods = [];
13
14
    /**
15
     * Set options
16
     *
17
     * @param mixed[] $options
18
     * @throws LogicException
19
     * @return self
20
     */
21
    public function options(array $options): self
22
    {
23
        foreach ($options as $key => $value) {
24
            $this->setMethod($key, $value);
25
        }
26
27
        return $this;
28
    }
29
30
    /**
31
     * @param string[] $methods
32
     */
33
    protected function methodsOptionables(array $methods): self
34
    {
35
        $this->validMethods = $methods;
36
37
        return $this;
38
    }
39
40
    private function setMethod(string $key, mixed $value): void
41
    {
42
        $method = $this->convert($key);
43
44
        if (in_array($method, $this->validMethods)) {
45
            $this->{$method}($value);
46
        } else {
47
            throw new LogicException("option {$key} is not valid.", 30);
48
        }
49
    }
50
51
    private function convert(string $key): string
52
    {
53
        return lcfirst(
54
            str_replace(
55
                ' ',
56
                '',
57
                ucwords(str_replace(['-', '_'], ' ', $key))
58
            )
59
        );
60
    }
61
62
63
}
64