Completed
Push — master ( 5c0ad8...d30cdc )
by Filip
08:38 queued 07:33
created

Json::getSupportedExtensions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
namespace Noodlehaus\Parser;
4
5
use Noodlehaus\Exception\ParseException;
6
7
/**
8
 * JSON parser
9
 *
10
 * @package    Config
11
 * @author     Jesus A. Domingo <[email protected]>
12
 * @author     Hassan Khan <[email protected]>
13
 * @author     Filip Š <[email protected]>
14
 * @link       https://github.com/noodlehaus/config
15
 * @license    MIT
16
 */
17
class Json implements ParserInterface
18
{
19
    /**
20
     * {@inheritDoc}
21
     * Parses an JSON file as an array
22
     *
23
     * @throws ParseException If there is an error parsing the JSON file
24
     */
25 6
    public function parseFile($filename)
26
    {
27 6
        $data = json_decode(file_get_contents($filename), true);
28
29 6
        return (array)$this->parse($data, $filename);
30
    }
31
32
    /**
33
     * {@inheritDoc}
34
     * Parses an JSON string as an array
35
     *
36
     * @throws ParseException If there is an error parsing the JSON string
37
     */
38 3
    public function parseString($config)
39
    {
40 3
        $data = json_decode($config, true);
41
42 3
        return (array)$this->parse($data);
43
    }
44
45
    /**
46
     * Completes parsing of JSON data
47
     *
48
     * @param  array  $data
49
     * @param  string $filename
50
     * @return array|null
51
     *
52
     * @throws ParseException If there is an error parsing the JSON data
53
     */
54 6
    protected function parse($data = null, $filename = null)
55
    {
56 6
        if (json_last_error() !== JSON_ERROR_NONE) {
57 3
            $error_message  = 'Syntax error';
58 3
            if (function_exists('json_last_error_msg')) {
59 3
                $error_message = json_last_error_msg();
60
            }
61
62
            $error = [
63 3
                'message' => $error_message,
64 3
                'type'    => json_last_error(),
65 3
                'file'    => $filename,
66
            ];
67
68 3
            throw new ParseException($error);
69
        }
70
71 3
        return $data;
72
    }
73
74
    /**
75
     * {@inheritDoc}
76
     */
77 3
    public static function getSupportedExtensions()
78
    {
79 3
        return ['json'];
80
    }
81
}
82