Skip to content

Commit

Permalink
adds JSON_ERROR_NON_BACKED_ENUM to allowed JSON::encode() errors. (
Browse files Browse the repository at this point in the history
  • Loading branch information
ju1ius authored Feb 27, 2024
1 parent 1cd7ff0 commit 6f8cce5
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/Util/JSON.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
11 changes: 11 additions & 0 deletions tests/Util/Fixtures/NonBackedEnum.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

declare(strict_types=1);

namespace Sentry\Tests\Util\Fixtures;

enum NonBackedEnum
{
case None;
case Some;
}
12 changes: 12 additions & 0 deletions tests/Util/JSONTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use PHPUnit\Framework\TestCase;
use Sentry\Exception\JsonException;
use Sentry\Tests\Util\Fixtures\JsonSerializableClass;
use Sentry\Tests\Util\Fixtures\NonBackedEnum;
use Sentry\Tests\Util\Fixtures\SimpleClass;
use Sentry\Util\JSON;

Expand Down Expand Up @@ -143,6 +144,17 @@ public function testEncodeRespectsOptionsArgument(): void
$this->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
*/
Expand Down

0 comments on commit 6f8cce5

Please # to comment.