Completed
Push — master ( ad5456...f93915 )
by Amine
10s
created

ConfigLoader::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php namespace Tarsana\Command\Config;
2
3
use Tarsana\Command\Config\Config;
4
use Tarsana\Command\Helpers\Decoders\JsonDecoder;
5
use Tarsana\Command\Interfaces\Config\ConfigInterface;
6
use Tarsana\Command\Interfaces\Config\ConfigLoaderInterface;
7
use Tarsana\IO\Interfaces\Filesystem as FilesystemInterface;
8
9
/**
10
 * Loads configuration from multiple files.
11
 */
12
class ConfigLoader implements ConfigLoaderInterface {
13
14
    protected static $decoders = [
15
        'json' => JsonDecoder::class
16
    ];
17
18
    protected $fs;
19
20
    public function __construct(FilesystemInterface $fs)
21
    {
22
        $this->fs = $fs;
23
    }
24
25
    public function load(array $paths) : ConfigInterface
26
    {
27
        if (empty($paths))
28
            return new Config([]);
29
        $data = [];
30
        foreach ($paths as $path) {
31
            $data[] = $this->decode($path);
32
        }
33
        $data = call_user_func_array('array_replace_recursive', $data);
34
        return new Config($data);
35
    }
36
37
    protected function decode(string $path) : array {
38
        if (! $this->fs->isFile($path))
39
            return [];
40
        $file = $this->fs->file($path);
41
        $ext  = $file->extension();
42
        if (! array_key_exists($ext, static::$decoders))
43
            throw new \Exception("Unknown configuration file extension '{$ext}'");
44
        $decoderClass = static::$decoders[$ext];
45
        $decoder = new $decoderClass;
46
        return $decoder->decode($file->content());
47
    }
48
}
49