Completed
Push — master ( 726362...d621a8 )
by Hong
03:08
created

JsonReader::readFile()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 22
rs 8.9197
cc 4
eloc 12
nc 4
nop 1
1
<?php
2
/**
3
 * Phossa Project
4
 *
5
 * PHP version 5.4
6
 *
7
 * @category  Library
8
 * @package   Phossa2\Shared
9
 * @copyright Copyright (c) 2016 phossa.com
10
 * @license   http://mit-license.org/ MIT License
11
 * @link      http://www.phossa.com/
12
 */
13
/*# declare(strict_types=1); */
14
15
namespace Phossa2\Shared\Reader;
16
17
use Phossa2\Shared\Message\Message;
18
use Phossa2\Shared\Exception\RuntimeException;
19
20
/**
21
 * Read & parse json formatted file and return the result
22
 *
23
 * @package Phossa2\Shared
24
 * @author  Hong Zhang <[email protected]>
25
 * @version 2.0.1
26
 * @since   2.0.1 added
27
 */
28
class JsonReader extends ReaderAbstract
29
{
30
    /**
31
     * default json error
32
     *
33
     * @var    array
34
     * @access protected
35
     * @staticvar
36
     */
37
    protected static $error = [
38
        \JSON_ERROR_NONE => 'No error',
39
        \JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
40
        \JSON_ERROR_STATE_MISMATCH => 'State mismatch (invalid or malformed JSON)',
41
        \JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
42
        \JSON_ERROR_SYNTAX => 'Syntax error',
43
        \JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded',
44
        \JSON_ERROR_RECURSION => 'Recursion found',
45
        \JSON_ERROR_INF_OR_NAN => 'NaN found',
46
        \JSON_ERROR_UNSUPPORTED_TYPE => 'Unsupported type found',
47
        \JSON_ERROR_INVALID_PROPERTY_NAME => 'Invalid property name found',
48
        \JSON_ERROR_UTF16 => 'Malformed UTF-16 characters, possibly incorrectly encoded',
49
    ];
50
51
    /**
52
     * {@inheritDoc}
53
     */
54
    public static function readFile(/*# string */ $path)
55
    {
56
        // check first
57
        static::checkPath($path);
58
59
        // read it
60
        $data  = @json_decode(file_get_contents($path), true);
61
62
        // check error if any
63
        $error = json_last_error();
64
        if ($error !== \JSON_ERROR_NONE) {
65
            if (function_exists('json_last_error_msg')) {
66
                $message = json_last_error_msg();
67
            } else {
68
                $message = isset(static::$error[$error]) ?
69
                    static::$error[$error] : 'Unknown JSON error';
70
            }
71
            throw new RuntimeException(Message::get($message), $error);
72
        }
73
74
        return $data;
75
    }
76
}
77