JSONFileReader::getJsonError()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 0
1
<?php
2
3
namespace TomPHP\ContainerConfigurator\FileReader;
4
5
use Assert\Assertion;
6
use TomPHP\ContainerConfigurator\Exception\InvalidConfigException;
7
8
/**
9
 * @internal
10
 */
11
final class JSONFileReader implements FileReader
12
{
13
    const JSON_ERRORS = [
14
        JSON_ERROR_NONE             => null,
15
        JSON_ERROR_DEPTH            => 'Maximum stack depth exceeded',
16
        JSON_ERROR_STATE_MISMATCH   => 'Underflow or the modes mismatch',
17
        JSON_ERROR_CTRL_CHAR        => 'Unexpected control character found',
18
        JSON_ERROR_SYNTAX           => 'Syntax error, malformed JSON',
19
        JSON_ERROR_UTF8             => 'Malformed UTF-8 characters, possibly incorrectly encoded',
20
    ];
21
22
    /**
23
     * @var string
24
     */
25
    private $filename;
26
27
    public function read($filename)
28
    {
29
        Assertion::file($filename);
30
31
        $this->filename = $filename;
32
33
        $config = json_decode(file_get_contents($filename), true);
34
35
        if (json_last_error() !== JSON_ERROR_NONE) {
36
            throw InvalidConfigException::fromJSONFileError($filename, $this->getJsonError());
37
        }
38
39
        return $config;
40
    }
41
42
    /**
43
     * @return string
44
     */
45
    private function getJsonError()
46
    {
47
        if (function_exists('json_last_error_msg')) {
48
            return json_last_error_msg();
49
        }
50
51
        return self::JSON_ERRORS[json_last_error()];
52
    }
53
}
54