1 | <?php |
||
2 | |||
3 | namespace SimpleDIC\Parser; |
||
4 | |||
5 | use SimpleDIC\Exceptions\ParserException; |
||
6 | |||
7 | class Parser |
||
8 | { |
||
9 | /** |
||
10 | * @var array |
||
11 | */ |
||
12 | private static $allowedExtensions = ['json', 'ini', 'xml', 'yaml', 'yml']; |
||
13 | |||
14 | /** |
||
15 | * @param string $filename |
||
16 | * |
||
17 | * @return array |
||
18 | * @throws ParserException |
||
19 | */ |
||
20 | public static function parse($filename) |
||
21 | { |
||
22 | $ext = self::getExt($filename); |
||
23 | |||
24 | if (false === in_array($ext, self::$allowedExtensions)) { |
||
25 | throw new ParserException($ext . ' is not a valid extension [json, ini, xml, yaml, yml are supported].'); |
||
26 | } |
||
27 | |||
28 | $parser = self::getParser($ext); |
||
29 | |||
30 | try { |
||
31 | return $parser->parse($filename); |
||
0 ignored issues
–
show
|
|||
32 | } catch (\Exception $e) { |
||
33 | throw new ParserException($filename . ' cannot be parsed [' . $ext . ' driver used]'); |
||
34 | } |
||
35 | } |
||
36 | |||
37 | /** |
||
38 | * @param string $filename |
||
39 | * |
||
40 | * @return string |
||
41 | */ |
||
42 | private static function getExt($filename) |
||
43 | { |
||
44 | return pathinfo($filename, PATHINFO_EXTENSION); |
||
45 | } |
||
46 | |||
47 | /** |
||
48 | * @param string $ext |
||
49 | * |
||
50 | * @return ParserInterface |
||
51 | */ |
||
52 | private static function getParser($ext) |
||
53 | { |
||
54 | switch ($ext) { |
||
55 | case 'ini': |
||
56 | return new IniParser(); |
||
57 | |||
58 | case 'json': |
||
59 | return new JsonParser(); |
||
60 | |||
61 | case 'xml': |
||
62 | return new XmlParser(); |
||
63 | |||
64 | case 'yaml': |
||
65 | case 'yml': |
||
66 | return new YamlParser(); |
||
67 | } |
||
68 | } |
||
69 | } |
||
70 |
If the returned type also contains false, it is an indicator that maybe an error condition leading to the specific return statement remains unhandled.