Skip to content

Commit e0d5f8f

Browse files
committed
feat(support): support base64 in json encode and decode
1 parent c8b5b7f commit e0d5f8f

File tree

2 files changed

+38
-2
lines changed

2 files changed

+38
-2
lines changed

packages/support/src/Json/functions.php

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,16 @@
2121
*
2222
* @throws Exception\JsonCouldNotBeDecoded If an error occurred.
2323
*/
24-
function decode(string $json, bool $associative = true): mixed
24+
function decode(string $json, bool $associative = true, bool $base64 = false): mixed
2525
{
26+
if ($base64) {
27+
$json = base64_decode($json, strict: true);
28+
29+
if ($json === false) {
30+
throw new Exception\JsonCouldNotBeDecoded('The provided base64 string is not valid.');
31+
}
32+
}
33+
2634
try {
2735
/** @var mixed $value */
2836
$value = json_decode($json, $associative, 512, JSON_BIGINT_AS_STRING | JSON_THROW_ON_ERROR);
@@ -40,7 +48,7 @@ function decode(string $json, bool $associative = true): mixed
4048
*
4149
* @return non-empty-string
4250
*/
43-
function encode(mixed $value, bool $pretty = false, int $flags = 0): string
51+
function encode(mixed $value, bool $pretty = false, int $flags = 0, bool $base64 = false): string
4452
{
4553
$flags |= JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRESERVE_ZERO_FRACTION | JSON_THROW_ON_ERROR;
4654

@@ -55,6 +63,10 @@ function encode(mixed $value, bool $pretty = false, int $flags = 0): string
5563
throw new Exception\JsonCouldNotBeEncoded(sprintf('%s.', $jsonException->getMessage()), $jsonException->getCode(), $jsonException);
5664
}
5765

66+
if ($base64) {
67+
return base64_encode($json);
68+
}
69+
5870
return $json;
5971
}
6072

packages/support/tests/Json/JsonTest.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,4 +121,28 @@ public function test_is_valid(): void
121121
$this->assertFalse(Json\is_valid(['foo' => 'bar']));
122122
$this->assertFalse(Json\is_valid(1));
123123
}
124+
125+
public function test_base64_encode_and_decode(): void
126+
{
127+
$data = [
128+
'name' => 'azjezz/psl',
129+
'type' => 'library',
130+
'description' => 'PHP Standard Library.',
131+
'keywords' => ['php', 'std', 'stdlib', 'utility', 'psl'],
132+
'license' => 'MIT',
133+
];
134+
135+
$encoded = Json\encode($data, base64: true);
136+
$decoded = Json\decode($encoded, base64: true);
137+
138+
$this->assertSame($data, $decoded);
139+
}
140+
141+
public function test_base64_decode_failure(): void
142+
{
143+
$this->expectException(Json\Exception\JsonCouldNotBeDecoded::class);
144+
$this->expectExceptionMessage('The provided base64 string is not valid.');
145+
146+
Json\decode('invalid_base64', base64: true);
147+
}
124148
}

0 commit comments

Comments
 (0)