Completed
Pull Request — master (#52)
by Tom
04:13
created

JSONFileReader   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
c 1
b 0
f 0
lcom 1
cbo 2
dl 0
loc 50
rs 10

3 Methods

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