1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Linio\Component\Util; |
6
|
|
|
|
7
|
|
|
use InvalidArgumentException; |
8
|
|
|
use LogicException; |
9
|
|
|
|
10
|
|
|
class Json |
|
|
|
|
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* @param mixed $data |
14
|
|
|
* |
15
|
|
|
* @throws LogicException If encoding fails |
16
|
|
|
*/ |
17
|
|
|
public static function encode($data): string |
18
|
|
|
{ |
19
|
|
|
if (is_resource($data)) { |
20
|
|
|
throw new InvalidArgumentException('Resource types cannot be encoded'); |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
$result = json_encode($data); |
24
|
|
|
|
25
|
|
|
if ($result === false || json_last_error() !== JSON_ERROR_NONE) { |
26
|
|
|
throw new LogicException(self::getLastJsonError()); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
return $result; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @param mixed $data |
34
|
|
|
* |
35
|
|
|
* @throws LogicException If decoding fails |
36
|
|
|
* |
37
|
|
|
* @return mixed |
38
|
|
|
*/ |
39
|
|
|
public static function decode($data) |
40
|
|
|
{ |
41
|
|
|
if (empty($data)) { |
42
|
|
|
return; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
$result = json_decode($data, true); |
46
|
|
|
|
47
|
|
|
if (json_last_error() !== JSON_ERROR_NONE) { |
48
|
|
|
$lastError = self::getLastJsonError(); |
49
|
|
|
$payload = substr($data, 0, 255); |
50
|
|
|
|
51
|
|
|
if (strlen($data) > 255) { |
52
|
|
|
$payload .= '... (truncated)'; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
throw new LogicException(sprintf('%s on \'%s\'', $lastError, $payload)); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
return $result; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
public static function getLastJsonError(): string |
62
|
|
|
{ |
63
|
|
|
switch (json_last_error()) { |
64
|
|
|
case JSON_ERROR_DEPTH: |
65
|
|
|
return 'Invalid JSON: Maximum stack depth exceeded'; |
66
|
|
|
|
67
|
|
|
case JSON_ERROR_STATE_MISMATCH: |
68
|
|
|
return 'Invalid JSON: Underflow or modes mismatch'; |
69
|
|
|
|
70
|
|
|
case JSON_ERROR_CTRL_CHAR: |
71
|
|
|
return 'Invalid JSON: Unexpected control character found'; |
72
|
|
|
|
73
|
|
|
case JSON_ERROR_SYNTAX: |
74
|
|
|
return 'Invalid JSON: Syntax error'; |
75
|
|
|
|
76
|
|
|
case JSON_ERROR_UTF8: |
77
|
|
|
return 'Invalid JSON: Malformed UTF-8 characters, possibly incorrectly encoded'; |
78
|
|
|
|
79
|
|
|
default: |
80
|
|
|
return 'Invalid JSON: Unknown error'; |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|
This check examines a number of code elements and verifies that they conform to the given naming conventions.
You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.