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

JsonConfigParser   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 53.85%

Importance

Changes 0
Metric Value
dl 0
loc 53
ccs 14
cts 26
cp 0.5385
rs 10
c 0
b 0
f 0
wmc 7
lcom 1
cbo 1

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A parseFile() 0 8 3
A parseString() 0 12 2
A supportedExtensions() 0 4 1
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
}