1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* Copyright 2017 SURFnet B.V. |
5
|
|
|
* |
6
|
|
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
7
|
|
|
* you may not use this file except in compliance with the License. |
8
|
|
|
* You may obtain a copy of the License at |
9
|
|
|
* |
10
|
|
|
* http://www.apache.org/licenses/LICENSE-2.0 |
11
|
|
|
* |
12
|
|
|
* Unless required by applicable law or agreed to in writing, software |
13
|
|
|
* distributed under the License is distributed on an "AS IS" BASIS, |
14
|
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
15
|
|
|
* See the License for the specific language governing permissions and |
16
|
|
|
* limitations under the License. |
17
|
|
|
*/ |
18
|
|
|
|
19
|
|
|
namespace Surfnet\StepupBundle\Http; |
20
|
|
|
|
21
|
|
|
use Surfnet\StepupBundle\Exception\InvalidArgumentException; |
22
|
|
|
use Surfnet\StepupBundle\Exception\JsonException; |
23
|
|
|
|
24
|
|
|
final class JsonHelper |
25
|
|
|
{ |
26
|
|
|
private static $jsonErrors = [ |
27
|
|
|
JSON_ERROR_DEPTH => 'JSON_ERROR_DEPTH - Maximum stack depth exceeded', |
28
|
|
|
JSON_ERROR_STATE_MISMATCH => 'JSON_ERROR_STATE_MISMATCH - Underflow or the modes mismatch', |
29
|
|
|
JSON_ERROR_CTRL_CHAR => 'JSON_ERROR_CTRL_CHAR - Unexpected control character found', |
30
|
|
|
JSON_ERROR_SYNTAX => 'JSON_ERROR_SYNTAX - Syntax error, malformed JSON', |
31
|
|
|
JSON_ERROR_UTF8 => 'JSON_ERROR_UTF8 - Malformed UTF-8 characters, possibly incorrectly encoded', |
32
|
|
|
]; |
33
|
|
|
|
34
|
|
|
public static function decode($json) |
|
|
|
|
35
|
|
|
{ |
36
|
|
|
if (!is_string($json)) { |
37
|
|
|
throw InvalidArgumentException::invalidType('string', 'json', $json); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
$data = json_decode($json, true); |
41
|
|
|
|
42
|
|
|
if (JSON_ERROR_NONE !== json_last_error()) { |
43
|
|
|
$last = json_last_error(); |
44
|
|
|
|
45
|
|
|
$errorMessage = 'Unknown error'; |
46
|
|
|
if (array_key_exists($last, self::$jsonErrors)) { |
47
|
|
|
$errorMessage = self::$jsonErrors[$last]; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
throw JsonException::withMessage($errorMessage); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
return $data; |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|
Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a
@return
annotation as described here.