Autodetect::setParsers()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
3
namespace TheIconic\Config\Parser;
4
5
use TheIconic\Config\Exception\ParserException;
6
use Exception;
7
8
/**
9
 * auto-detecting parser - invokes specific parser based on config file extension
10
 *
11
 * @package Shared\Helper\Config\Parser
12
 */
13
class Autodetect extends AbstractParser
14
{
15
    /**
16
     * @var array
17
     */
18
    protected $parsers = [];
19
20
    /**
21
     * invokes specific parser based on config file extension
22
     *
23
     * @param string $file
24
     * @return array
25
     * @throws Exception
26
     */
27
    public function parse($file)
28
    {
29
        $extension = pathinfo($file, PATHINFO_EXTENSION);
30
31
        $parsers = $this->getParsers();
32
33
        if (!isset($parsers[$extension])) {
34
            throw new ParserException(sprintf('No parser found for config file with extension \'%s\'', $extension));
35
        }
36
37
        /** @var AbstractParser $parser */
38
        $parser = $parsers[$extension];
39
40
        return $parser->parse($file);
41
    }
42
43
    /**
44
     * @return array
45
     */
46
    public function getParsers(): array
47
    {
48
        if (empty($this->parsers)) {
49
            $this->parsers = [
50
                'ini' => new Ini(),
51
                'php' => new Php(),
52
                'json' => new Json(),
53
            ];
54
        }
55
56
        return $this->parsers;
57
    }
58
59
    /**
60
     * @param array $parsers
61
     * @return Autodetect
62
     */
63
    public function setParsers(array $parsers): Autodetect
64
    {
65
        $this->parsers = $parsers;
66
67
        return $this;
68
    }
69
}
70