diff --git a/src/Util/JSON.php b/src/Util/JSON.php index 9c568c52f..9824cbd74 100644 --- a/src/Util/JSON.php +++ b/src/Util/JSON.php @@ -35,6 +35,9 @@ public static function encode($data, int $options = 0, int $maxDepth = 512): str $encodedData = json_encode($data, $options, $maxDepth); $allowedErrors = [\JSON_ERROR_NONE, \JSON_ERROR_RECURSION, \JSON_ERROR_INF_OR_NAN, \JSON_ERROR_UNSUPPORTED_TYPE]; + if (\defined('JSON_ERROR_NON_BACKED_ENUM')) { + $allowedErrors[] = \JSON_ERROR_NON_BACKED_ENUM; + } $encounteredAnyError = json_last_error() !== \JSON_ERROR_NONE; diff --git a/tests/Util/Fixtures/NonBackedEnum.php b/tests/Util/Fixtures/NonBackedEnum.php new file mode 100644 index 000000000..8cef91f05 --- /dev/null +++ b/tests/Util/Fixtures/NonBackedEnum.php @@ -0,0 +1,11 @@ +assertSame('{}', JSON::encode([], \JSON_FORCE_OBJECT)); } + /** + * The `JSON_ERROR_NON_BACKED_ENUM` constant is only exposed from 8.1.5 and up. + * + * @requires PHP >= 8.1.5 + */ + public function testEncodeGracefullyHandlesUnitEnums(): void + { + $result = JSON::encode([NonBackedEnum::None, NonBackedEnum::Some]); + $this->assertSame('[0,0]', $result); + } + /** * @dataProvider decodeDataProvider */