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