-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathJsonCoder.php
More file actions
160 lines (136 loc) · 4.46 KB
/
JsonCoder.php
File metadata and controls
160 lines (136 loc) · 4.46 KB
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
<?php
/**
* @copyright 2014 Integ S.A.
* @license http://opensource.org/licenses/MIT The MIT License (MIT)
* @author Javier Lorenzana <javier.lorenzana@gointegro.com>
*/
namespace GoIntegro\Json;
// JSON.
use JsonSchema\Validator;
/**
* La fachada del servicio de validación de JSON schemas.
*
* Not using the herrera-io/json lib because validation code should not
* throw exceptions.
*/
class JsonCoder
{
const FAIL_JSON_SCHEMA_MESSAGE = "Failed asserting that the JSON matches the given schema. Violations:\n",
ERROR_CANNOT_READ_FILE = "Could not open the JSON file.",
ERROR_PARSE = "An error occurred while parsing JSON: %s";
/**
* @var array
*/
private static $errorMessages = [
JSON_ERROR_NONE => "No error has occurred.",
JSON_ERROR_DEPTH => "The maximum stack depth has been exceeded.",
JSON_ERROR_STATE_MISMATCH => "Invalid or malformed JSON.",
JSON_ERROR_CTRL_CHAR => "Control character error, possibly incorrectly encoded.",
JSON_ERROR_SYNTAX => "Syntax error.",
JSON_ERROR_UTF8 => "Malformed UTF-8 characters, possibly incorrectly encoded.",
6 => "One or more recursive references in the value to be encoded.", // JSON_ERROR_RECURSION in PHP5.5.
7 => "One or more NAN or INF values in the value to be encoded.", // JSON_ERROR_INF_OR_NAN in PHP5.5
8 => "A value of a type that cannot be encoded was given." // JSON_ERROR_UNSUPPORTED_TYPE in PHP5.5
];
/**
* @var array
*/
private $lastSchemaErrors = [];
/**
* Codifica el parámetro a JSON.
* @param mixed $value
* @return string
*/
public function encode($value)
{
$json = json_encode($value);
if ($code = json_last_error()) $this->throwError($code);
return $json;
}
/**
* Codifica el parámetro a JSON.
* @param string $json
* @param boolean $toObject
* @return array
*/
public function decode($json, $toObject = FALSE)
{
if (is_file($json)) {
if (is_readable($json)) {
$json = file_get_contents($json);
} else {
throw new \ErrorException(self::ERROR_CANNOT_READ_FILE);
}
}
$value = json_decode($json, !$toObject);
if ($code = json_last_error()) $this->throwError($code);
return $value;
}
/**
* @param integer $code
* @throws \ErrorException
*/
private function throwError($code)
{
$message = isset(self::$errorMessages[$code])
? self::$errorMessages[$code]
: "Unknown error.";
$message = sprintf(self::ERROR_PARSE, $message);
throw new \ErrorException($message);
}
/**
* Matches a JSON string or structure to a schema.
*
* It would be lovely to be able to return an object containing both
* the result and the errors wich would itself be castable to boolean,
* but alas, this is not yet possible on PHP.
* @param string $json
* @param string $schema
* @return boolean
* @see http://json-schema.org/
*/
public function matchSchema($json, $schema)
{
$validator = new Validator();
if (is_string($json)) {
$json = $this->decode($json, TRUE);
} elseif (is_array($json)) {
$json = (object) $json;
}
if (is_string($schema)) {
$schema = $this->decode($schema, TRUE);
} elseif (is_array($schema)) {
$schema = (object) $schema;
}
$validator->check($json, $schema);
$this->lastSchemaErrors = $validator->getErrors();
return $validator->isValid();
}
/**
* Returns the latest schema matching errors.
* @return array
* @see http://php.net/manual/en/function.json-last-error.php
*/
public function getSchemaErrors()
{
return $this->lastSchemaErrors;
}
/**
* Returns the latest schema matching errors as a text message.
* @return string
* @see http://php.net/manual/en/function.json-last-error-msg.php
*/
public function getSchemaErrorMessage()
{
$message = NULL;
foreach ($this->lastSchemaErrors as $error) {
$message .= sprintf(
"[%s] %s\n", $error['property'], $error['message']
);
}
if (!empty($message)) {
$message = self::FAIL_JSON_SCHEMA_MESSAGE . $message;
}
return $message;
}
}