Completed
Pull Request — master (#33)
by Christian
02:42
created

Config::loadFromArray()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 2
nop 1
crap 3
1
<?php
2
3
namespace uuf6429\ElderBrother\Config;
4
5
use Psr\Log\LoggerAwareInterface;
6
use Psr\Log\LoggerInterface;
7
use uuf6429\ElderBrother\Action\ActionAbstract;
8
9
class Config implements ConfigInterface
10
{
11
    /**
12
     * @var array
13
     */
14
    protected $config = [];
15
16
    /**
17
     * {@inheritdoc}
18
     */
19
    public function loadFromFile($fileName, LoggerInterface $logger)
20
    {
21
        $eventActions = include $fileName;
22
        $this->initActions($eventActions, $logger);
23
        $this->loadFromArray($eventActions);
24
    }
25
26
    /**
27
     * {@inheritdoc}
28
     */
29 3
    public function loadFromArray($eventActions)
30
    {
31 3
        foreach ($eventActions as $event => $prioritizedActions) {
32
            // merge config
33 3
            $this->config[$event] = array_merge(
34 3
                isset($this->config[$event]) ? $this->config[$event] : [],
35
                $prioritizedActions
36
            );
37
38
            // reorder actions
39 3
            ksort($this->config[$event]);
40
        }
41 3
    }
42
43
    /**
44
     * {@inheritdoc}
45
     */
46
    public function getAllEventActions()
47
    {
48
        return (array) $this->config;
49
    }
50
51
    /**
52
     * {@inheritdoc}
53
     */
54 3
    public function getActionsForEvent($event, $supportedOnly = true)
55
    {
56 3
        $config = isset($this->config[$event])
57 3
            ? array_values($this->config[$event]) : [];
58
59 3
        if ($supportedOnly) {
60 3
            $config = array_filter(
61
                $config,
62 3
                function (ActionAbstract $action) {
63 2
                    return $action->isSupported();
64 3
                }
65
            );
66
        }
67
68 3
        return $config;
69
    }
70
71
    /**
72
     * @param array<string,ActionAbstract[]> $eventActions
73
     * @param LoggerInterface                $logger
74
     */
75
    private function initActions(&$eventActions, LoggerInterface $logger)
76
    {
77
        foreach ($eventActions as $actionList) {
78
            foreach ($actionList as $action) {
79
                if ($action instanceof ConfigAwareInterface) {
80
                    $action->setConfig($this);
81
                }
82
                if ($action instanceof LoggerAwareInterface) {
83
                    $action->setLogger($logger);
84
                }
85
            }
86
        }
87
    }
88
}
89