Skip to content

Commit 26b3972

Browse files
author
Greg Bowler
authored
Merge pull request #14 from PhpGt/13-flags
feature: pass flags to json_decode
2 parents e8059f3 + e79e884 commit 26b3972

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

src/JsonObjectBuilder.php

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
class JsonObjectBuilder extends DataObjectBuilder {
1616
public function __construct(
1717
private readonly int $depth = 512,
18+
private readonly int $flags = 0,
1819
) {
1920
}
2021

@@ -23,7 +24,7 @@ public function fromJsonString(string $jsonString):JsonObject {
2324
$json = json_decode(
2425
$jsonString,
2526
depth: $this->depth,
26-
flags: JSON_THROW_ON_ERROR
27+
flags: JSON_THROW_ON_ERROR | $this->flags,
2728
);
2829
}
2930
catch(NativeJsonException $exception) {
@@ -39,9 +40,10 @@ public function fromJsonString(string $jsonString):JsonObject {
3940
public function fromJsonDecoded(
4041
object|array|string|int|float|bool|null $jsonDecoded
4142
):JsonObject {
43+
/** @noinspection PhpDeprecatedStdLibCallInspection */
4244
if(is_array($jsonDecoded)
4345
&& !is_int(key($jsonDecoded))) {
44-
// The JSON could represent an primitive indexed array, but the json could have
46+
// The JSON could represent a primitive indexed array, but the json could have
4547
// been decoded as an associative array too. Deal with associative arrays first.
4648
$jsonData = $this->fromJsonDecoded(
4749
(object)$jsonDecoded

test/phpunit/JsonObjectBuilderTest.php

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
use Gt\Json\JsonPrimitive\JsonNullPrimitive;
1212
use Gt\Json\JsonPrimitive\JsonStringPrimitive;
1313
use PHPUnit\Framework\TestCase;
14-
use stdClass;
1514

1615
class JsonObjectBuilderTest extends TestCase {
1716
private string $jsonStringSimpleKVP = <<<JSON
@@ -215,4 +214,18 @@ public function testFromJson_depth() {
215214
self::expectExceptionMessage("Error decoding JSON: Maximum stack depth exceeded");
216215
$sut->fromJsonString($jsonString);
217216
}
217+
218+
public function testFromJson_customFlag_bigInt() {
219+
$jsonString = '{"num": 9876543210987654321 }';
220+
221+
$sut = new JsonObjectBuilder();
222+
$json = $sut->fromJsonString($jsonString);
223+
$num = $json->getString("num");
224+
self::assertStringContainsString("E", $num);
225+
226+
$sut = new JsonObjectBuilder(flags: JSON_BIGINT_AS_STRING);
227+
$json = $sut->fromJsonString($jsonString);
228+
$num = $json->getString("num");
229+
self::assertSame("9876543210987654321", $num);
230+
}
218231
}

0 commit comments

Comments
 (0)