Completed
Push — master ( 6ff8ac...850b68 )
by Tom
86:44 queued 66:31
created

JSONFileReader::read()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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