Passed
Push — master ( 577a19...cdf890 )
by Vsevolods
03:00
created

JsonConfigParser::parseFile()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 4.679

Importance

Changes 0
Metric Value
cc 3
eloc 4
nc 2
nop 1
dl 0
loc 8
ccs 3
cts 7
cp 0.4286
crap 4.679
rs 9.4285
c 0
b 0
f 0
1
<?php declare(strict_types = 1);
2
3
namespace Venta\Config\Parser;
4
5
use League\Flysystem\FilesystemInterface;
6
use Venta\Contracts\Config\ConfigFileParser;
7
use Venta\Contracts\Config\ConfigStringParser;
8
9
/**
10
 * Class JsonConfigParser
11
 *
12
 * @package Venta\Config\Parser
13
 */
14
class JsonConfigParser implements ConfigFileParser, ConfigStringParser
15
{
16
    /**
17
     * @var FilesystemInterface
18
     */
19
    private $filesystem;
20
21
    /**
22
     * Construct function.
23
     *
24
     * @param FilesystemInterface $filesystem
25
     */
26 3
    public function __construct(FilesystemInterface $filesystem)
27
    {
28 3
        $this->filesystem = $filesystem;
29 3
    }
30
31
    /**
32
     * @inheritDoc
33
     */
34 1
    public function parseFile(string $filename): array
35
    {
36 1
        if ($this->filesystem->has($filename) && $contents = $this->filesystem->read($filename)) {
37 1
            return $this->parseString($contents);
38
        }
39
40
        throw new \RuntimeException(sprintf('Unable to parse configuration file: "%s".', $filename));
41
    }
42
43
    /**
44
     * @inheritDoc
45
     */
46 2
    public function parseString(string $configuration): array
47
    {
48 2
        $array = json_decode($configuration, true);
49 2
        if (json_last_error() !== JSON_ERROR_NONE) {
50 1
            throw new \RuntimeException(
51 1
                sprintf('Unable to parse configuration string: "%s".', json_last_error_msg()),
52
                json_last_error()
53
            );
54
        }
55
56 2
        return $array;
57
    }
58
59
    /**
60
     * @inheritDoc
61
     */
62 1
    public function supportedExtensions(): array
63
    {
64 1
        return ['json'];
65
    }
66
}