Skip to content

Commit

Permalink
add Json::maybeDecode()
Browse files Browse the repository at this point in the history
  • Loading branch information
Baptouuuu committed Mar 23, 2024
1 parent 9844210 commit 6bb0e0a
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
### Added

- `Innmind\Json\Json::encode()` and `::decode()` are now declared pure
- `Innmind\Json\Json::maybeDecode()`

### Removed

Expand Down
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
},
"require": {
"php": "~8.2",
"ext-json": "*"
"ext-json": "*",
"innmind/immutable": "~5.3"
},
"autoload": {
"psr-4": {
Expand Down
16 changes: 16 additions & 0 deletions src/Json.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
MaximumDepthExceeded,
StateMismatch,
CharacterControlError,
Exception,
SyntaxError,
MalformedUTF8,
RecursiveReference,
Expand All @@ -15,6 +16,7 @@
PropertyCannotBeEncoded,
MalformedUTF16,
};
use Innmind\Immutable\Maybe;

final class Json
{
Expand Down Expand Up @@ -43,6 +45,20 @@ public static function decode(string $string)
}
}

/**
* @psalm-pure
*
* @return Maybe<mixed>
*/
public static function maybeDecode(string $string): Maybe
{
try {
return Maybe::just(self::decode($string));
} catch (Exception $e) {
return Maybe::nothing();
}
}

/**
* @psalm-pure
*
Expand Down
18 changes: 18 additions & 0 deletions tests/JsonTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,13 +59,31 @@ public function testDecode()
$this->assertSame(['foo' => 'bar'], $content);
}

public function testMaybeDecode()
{
$content = Json::maybeDecode('{"foo":"bar"}');

$this->assertSame(['foo' => 'bar'], $content->match(
static fn($content) => $content,
static fn() => null,
));
}

public function testThrowOnSyntaxError()
{
$this->expectException(SyntaxError::class);

Json::decode('{"foo"');
}

public function testReturnNothingOnDecodingError()
{
$this->assertFalse(Json::maybeDecode('{"foo"')->match(
static fn() => true,
static fn() => false,
));
}

public function testThrowOnMaximumDepthExceeded()
{
$this->expectException(MaximumDepthExceeded::class);
Expand Down

0 comments on commit 6bb0e0a

Please sign in to comment.