Completed
Push — master ( ef5909...624335 )
by Brad
12s
created

Config::fromArray()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Transitions;
4
5
class Config
6
{
7
8
    /**
9
     * The header key for the applicable transition version.
10
     * @var string
11
     */
12
    protected $headerKey;
13
14
    /**
15
     * An array of transitions to apply, keyed by version date.
16
     * @var array
17
     */
18
    protected $transitions;
19
20
    public function __construct(string $headerKey = '', array $transitions = [])
21
    {
22
23
        $this->setHeaderKey($headerKey)
24
             ->setTransitions($transitions);
25
    }
26
27
    public static function fromArray(array $attributes) : Config
28
    {
29
30
        return new static($attributes['headerKey'] ?? '', $attributes['transitions'] ?? []);
31
    }
32
33
    public function headerKey() : string
34
    {
35
36
        return $this->headerKey;
37
    }
38
39
    /**
40
     * Get the applicable transitions for the given version.
41
     *
42
     * @param string|int $version
43
     * @return array|Transition[]
44
     */
45
    public function transitionsForVersion($version) : array
46
    {
47
48
        return array_reduce($this->filterStages($version), function (array $applicable, array $classes) {
49
50
            return array_merge($applicable, $classes);
51
        }, []);
52
    }
53
54
    /**
55
     * @param string|int $version
56
     * @return array
57
     */
58
    private function filterStages($version) : array
59
    {
60
61
        return array_filter($this->transitions, function ($key) use ($version) {
62
63
            return $version <= $key or $key === '*';
64
        }, ARRAY_FILTER_USE_KEY);
65
    }
66
67
    public function setHeaderKey(string $headerKey = '') : Config
68
    {
69
70
        if (empty($headerKey)) {
71
            throw HeaderKeyNotDefined::new();
72
        }
73
        $this->headerKey = $headerKey;
74
75
        return $this;
76
    }
77
78
    public function setTransitions(array $transitions = []) : Config
79
    {
80
81
        $this->transitions = $transitions;
82
        return $this;
83
    }
84
}
85