ArrayLoader   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 3
dl 0
loc 64
ccs 26
cts 26
cp 1
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
loadFile() 0 1 ?
A compile() 0 4 1
A load() 0 4 1
A createArrayByKey() 0 13 2
A loadFiles() 0 10 3
1
<?php
2
/**
3
 * Yii 2 config loader
4
 *
5
 * @see       https://github.com/sergeymakinen/yii2-config
6
 * @copyright Copyright (c) 2016 Sergey Makinen (https://makinen.ru)
7
 * @license   https://github.com/sergeymakinen/yii2-config/blob/master/LICENSE The MIT License
8
 */
9
10
namespace sergeymakinen\yii\config;
11
12
use yii\helpers\ArrayHelper;
13
14
/**
15
 * Parseable config loader.
16
 */
17
abstract class ArrayLoader extends Loader
18
{
19
    /**
20
     * @var string|null the key in a dot notation format to insert into the config.
21
     */
22
    public $key;
23
24
    /**
25
     * @inheritDoc
26
     */
27 19
    public function compile()
28
    {
29 19
        $this->loadFiles();
30 19
    }
31
32
    /**
33
     * @inheritDoc
34
     */
35 33
    public function load()
36
    {
37 33
        $this->loadFiles();
38 31
    }
39
40
    /**
41
     * Returns the config for the resolved file.
42
     * @param string $path the file path.
43
     * @return array the config.
44
     */
45
    abstract protected function loadFile($path);
46
47
    /**
48
     * Returns an array with the value set in the key specified in a dot notation format.
49
     * @param string $key the key name in a dot notation format.
50
     * @param mixed $value the value.
51
     * @return array a result array.
52
     */
53 12
    protected function createArrayByKey($key, $value)
54
    {
55 12
        $array = [];
56 12
        $current = &$array;
57 12
        $keys = explode('.', $key);
58 12
        while (count($keys) > 1) {
59 8
            $key = array_shift($keys);
60 8
            $current[$key] = [];
61 8
            $current = &$current[$key];
62 8
        }
63 12
        $current[array_shift($keys)] = $value;
64 12
        return $array;
65
    }
66
67
    /**
68
     * Loads resolved files into the internal config object.
69
     */
70 49
    private function loadFiles()
71
    {
72 49
        foreach ($this->resolveFiles() as $file) {
73 43
            $value = $this->loadFile($file);
74 43
            if ($this->key !== null) {
75 12
                $value = $this->createArrayByKey($this->key, $value);
76 12
            }
77 43
            $this->storage->config = ArrayHelper::merge($this->storage->config, $value);
78 47
        }
79 47
    }
80
}
81