ConfigReader::getContentsAsArray()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 3
nop 1
1
<?php
2
namespace UltraLite\ConfigReader;
3
4
use UltraLite\ConfigReader\ConfigReaderException\FileFormatNotSupported;
5
use UltraLite\ConfigReader\ConfigReaderException\FileNotReadable;
6
use UltraLite\ConfigReader\FileParser\IniFileParser;
7
use UltraLite\ConfigReader\FileParser\JsonFileParser;
8
use UltraLite\ConfigReader\FileParser\PhpArrayFileParser;
9
10
class ConfigReader
11
{
12
    /** @var FileParser[] */
13
    private $fileParsers;
14
15
    public function __construct(array $fileParsers = null)
16
    {
17
        $this->fileParsers = $fileParsers ?: [new IniFileParser(), new JsonFileParser(), new PhpArrayFileParser()];
18
    }
19
20
    public function addFileParser(FileParser $fileParser)
21
    {
22
        $this->fileParsers[] = $fileParser;
23
    }
24
25
    /**
26
     * @throws ConfigReaderException
27
     */
28
    public function getConfigArray(string $pathToConfig): array
29
    {
30
        $this->assertIsReadable($pathToConfig);
31
        return $this->getContentsAsArray($pathToConfig);
32
    }
33
34
    private function getContentsAsArray(string $path): array
35
    {
36
        $fileExtension = pathinfo($path)['extension'];
37
38
        foreach ($this->fileParsers as $fileParser) {
39
            if ($fileParser->supportsFileExtension($fileExtension)) {
40
                return $fileParser->getFileContentsAsArray($path);
41
            }
42
        }
43
44
        throw FileFormatNotSupported::constructFromPath($path);
45
    }
46
47
    private function assertIsReadable(string $path)
48
    {
49
        if (!is_readable($path)) {
50
            throw FileNotReadable::constructFromPath($path);
51
        }
52
    }
53
}
54