1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
|
<?php
namespace SMW\Tests\Utils\File;
use RuntimeException;
/**
* @license GNU GPL v2+
* @since 2.1
*
* @author mwjames
*/
class JsonFileReader {
/**
* @var string|null
*/
private $file = null;
/**
* @var array|null
*/
private $contents = null;
/**
* @since 2.1
*
* @param string|null $file
*/
public function __construct( $file = null ) {
$this->setFile( $file );
}
/**
* @since 2.1
*
* @param string $file
*/
public function setFile( $file ) {
$this->file = str_replace( [ '\\', '/' ], DIRECTORY_SEPARATOR, $file );
$this->contents = null;
}
/**
* @since 2.1
*
* @return array
* @throws RuntimeException
*/
public function read() {
if ( $this->contents === null && $this->isReadable() ) {
$this->contents = $this->decodeJsonFileContentsToArray( $this->file );
}
if ( $this->contents !== null ) {
return $this->contents;
}
throw new RuntimeException( "Expected a readable {$this->file} file" );
}
/**
* @since 2.1
*
* @return boolean
*/
public function isReadable() {
return is_file( $this->file ) && is_readable( $this->file );
}
/**
* @since 2.1
*
* @return integer
* @throws RuntimeException
*/
public function getModificationTime() {
if ( $this->isReadable() ) {
return filemtime( $this->file );
}
throw new RuntimeException( "Expected a readable {$this->file} file" );
}
private function decodeJsonFileContentsToArray( $file ) {
$json = file_get_contents( $file );
$json = preg_replace(
'~ ("(?:[^\\\"]+|\\\.)*") |' . // preserve strings
'/\* (?:[^*]+|\*+(?!/))* \*/ |' . // strip multi-line comments
'//\V* ~sx', // strip //-comments
'$1', $json );
$contents = json_decode( $json, true );
if ( $contents !== null && json_last_error() === JSON_ERROR_NONE ) {
return $contents;
}
throw new RuntimeException( $this->printDescriptiveJsonError( json_last_error() ) );
}
private function printDescriptiveJsonError( $errorCode ) {
$errorMessages = [
JSON_ERROR_STATE_MISMATCH => 'Underflow or the modes mismatch, malformed JSON',
JSON_ERROR_CTRL_CHAR => 'Unexpected control character found, possibly incorrectly encoded',
JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON',
JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded',
JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded'
];
return sprintf(
"Expected a JSON compatible format but failed with '%s'",
$errorMessages[$errorCode]
);
}
}
|