|
1
|
|
|
<?php |
|
2
|
|
|
namespace SamBurns\ConfigFileParser; |
|
3
|
|
|
|
|
4
|
|
|
use SamBurns\ConfigFileParser\Exception\FileFormatNotParsable; |
|
5
|
|
|
use SamBurns\ConfigFileParser\Exception\FileNotReadable; |
|
6
|
|
|
use SamBurns\ConfigFileParser\File\ParsableFile; |
|
7
|
|
|
use SamBurns\ConfigFileParser\File\ParsableFile\IniFile; |
|
8
|
|
|
use SamBurns\ConfigFileParser\File\ParsableFile\JsonFile; |
|
9
|
|
|
use SamBurns\ConfigFileParser\File\ParsableFile\PhpArrayFile; |
|
10
|
|
|
use SamBurns\ConfigFileParser\File\ParsableFile\YamlFile; |
|
11
|
|
|
use SamBurns\ConfigFileParser\FileReading\FileContentsRetriever; |
|
12
|
|
|
use Symfony\Component\Yaml\Parser as YamlParser; |
|
13
|
|
|
|
|
14
|
|
|
class ConfigFileParser |
|
15
|
|
|
{ |
|
16
|
|
|
/** |
|
17
|
|
|
* @throws FileFormatNotParsable |
|
18
|
|
|
* @throws FileNotReadable |
|
19
|
|
|
*/ |
|
20
|
|
|
public function parseConfigFile(string $pathToFile): array |
|
21
|
|
|
{ |
|
22
|
|
|
$file = $this->getParsableFileFromPath($pathToFile); |
|
23
|
|
|
return $file->toArray(); |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* @throws FileFormatNotParsable |
|
28
|
|
|
*/ |
|
29
|
|
|
private function getParsableFileFromPath(string $pathToFile): ParsableFile |
|
30
|
|
|
{ |
|
31
|
|
|
$fileExtension = pathinfo($pathToFile)['extension']; |
|
32
|
|
|
|
|
33
|
|
|
$fileContentsRetriever = new FileContentsRetriever(); |
|
34
|
|
|
|
|
35
|
|
|
switch ($fileExtension) { |
|
36
|
|
|
case ('ini'): |
|
37
|
|
|
return new IniFile($pathToFile, $fileContentsRetriever); |
|
38
|
|
|
case ('php'): |
|
39
|
|
|
return new PhpArrayFile($pathToFile); |
|
40
|
|
|
case ('json'): |
|
41
|
|
|
return new JsonFile($pathToFile, $fileContentsRetriever); |
|
42
|
|
|
case ('yaml'): |
|
43
|
|
|
return new YamlFile($pathToFile, $fileContentsRetriever, new YamlParser()); |
|
44
|
|
|
case ('yml'): |
|
45
|
|
|
return new YamlFile($pathToFile, $fileContentsRetriever, new YamlParser()); |
|
46
|
|
|
default: |
|
47
|
|
|
throw FileFormatNotParsable::constructWithFilePath($pathToFile); |
|
48
|
|
|
} |
|
49
|
|
|
} |
|
50
|
|
|
} |
|
51
|
|
|
|