1: <?php
2:
3: declare(strict_types=1);
4:
5: namespace OpenSearch\Exception;
6:
7: use OpenSearch\Common\Exceptions\OpenSearchException;
8:
9: /**
10: * Provides an exception for JSON errors.
11: *
12: * @phpstan-ignore class.implementsDeprecatedInterface
13: */
14: class JsonException extends \JsonException implements OpenSearchException
15: {
16: public function __construct(int $code, private readonly ?string $data, ?\Throwable $previous = null)
17: {
18: parent::__construct($this->getErrorMessage($code), $code, $previous);
19: }
20:
21: public function getData(): ?string
22: {
23: return $this->data;
24: }
25:
26: /**
27: * Gets the JSON error message for the given error code.
28: */
29: private function getErrorMessage(int $code): string
30: {
31: return match ($code) {
32: JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
33: JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON',
34: JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
35: JSON_ERROR_SYNTAX => 'Syntax error',
36: JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded',
37: JSON_ERROR_RECURSION => 'One or more recursive references in the value to be encoded',
38: JSON_ERROR_INF_OR_NAN => 'One or more NAN or INF values in the value to be encoded',
39: JSON_ERROR_UNSUPPORTED_TYPE => 'A value of a type that cannot be encoded was given',
40:
41: // JSON_ERROR_* constant values that are available on PHP >= 7.0
42: 9 => 'Decoding of value would result in invalid PHP property name', //JSON_ERROR_INVALID_PROPERTY_NAME
43: 10 => 'Attempted to decode nonexistent UTF-16 code-point',//JSON_ERROR_UTF16
44: default => throw new \InvalidArgumentException("Encountered unknown JSON error code: [{$code}]"),
45: };
46: }
47: }
48: