JsonConfigDriver::supports()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Igorw\Silex;
4
5
class JsonConfigDriver implements ConfigDriver
6
{
7
    public function load($filename)
8
    {
9
        $config = $this->parseJson($filename);
10
11
        if (JSON_ERROR_NONE !== json_last_error()) {
12
            $jsonError = $this->getJsonError(json_last_error());
13
            throw new \RuntimeException(
14
                sprintf('Invalid JSON provided "%s" in "%s"', $jsonError, $filename));
15
        }
16
17
        return $config ?: array();
18
    }
19
20
    public function supports($filename)
21
    {
22
        return (bool) preg_match('#\.json(\.dist)?$#', $filename);
23
    }
24
25
    private function parseJson($filename)
26
    {
27
        $json = file_get_contents($filename);
28
29
        // handle empty as []
0 ignored issues
show
Unused Code Comprehensibility introduced by
45% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
30
        if(empty($json)) {
31
            return array();
32
        }
33
34
        return json_decode($json, true);
35
    }
36
37
    private function getJsonError($code)
38
    {
39
        $errorMessages = array(
40
            JSON_ERROR_DEPTH            => 'The maximum stack depth has been exceeded',
41
            JSON_ERROR_STATE_MISMATCH   => 'Invalid or malformed JSON',
42
            JSON_ERROR_CTRL_CHAR        => 'Control character error, possibly incorrectly encoded',
43
            JSON_ERROR_SYNTAX           => 'Syntax error',
44
            JSON_ERROR_UTF8             => 'Malformed UTF-8 characters, possibly incorrectly encoded',
45
        );
46
47
        return isset($errorMessages[$code]) ? $errorMessages[$code] : 'Unknown';
48
    }
49
}
50