Skip to content
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions src/JSON.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php

declare(strict_types=1);

namespace Artemeon\Support;

use JetBrains\PhpStorm\Language;
use JsonException;

class JSON
{
/**
* @param positive-int $depth
*
* @throws JsonException
*/
public static function encode(mixed $value, int $flags = 0, int $depth = 512): string
{
return json_encode($value, JSON_THROW_ON_ERROR | $flags, $depth);
}

/**
* @param int<1, 2147483647> $depth
*
* @throws JsonException
*/
public static function decode(#[Language('JSON')] string $json, ?bool $associative = null, int $depth = 512, int $flags = 0): mixed
Comment thread
marcreichel marked this conversation as resolved.
{
return json_decode($json, $associative, $depth, JSON_THROW_ON_ERROR | $flags);
}

/**
* @param int<1, 2147483647> $depth
*/
public static function decodeSilently(#[Language('JSON')] string $json, ?bool $associative = null, int $depth = 512, int $flags = 0): mixed
{
try {
return self::decode($json, $associative, $depth, $flags);
} catch (JsonException) {
return null;
}
}

/**
* @param int<1, 2147483647> $depth
* @param int-mask-of<0|1048576> $flags
*/
public static function validate(#[Language('JSON')] string $json, int $depth = 512, int $flags = 0): bool
{
return json_validate($json, $depth, $flags);
}
}
3 changes: 3 additions & 0 deletions src/JsonDecoder.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
use Artemeon\Support\Exception\InvalidJsonFormatException;
use JsonException;

/**
* @deprecated Use {@see JSON} instead.
*/
final class JsonDecoder
{
public static function decode(string $json, bool $assoc = true, int $flags = 0): mixed
Expand Down
31 changes: 31 additions & 0 deletions tests/Unit/JSONTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

declare(strict_types=1);

use Artemeon\Support\JSON;

it('should encode data', function (): void {
expect(JSON::encode(['foo' => 'bar']))
->toBe('{"foo":"bar"}');
});

it('should decode data', function (): void {
expect(JSON::decode('{"foo": "bar"}', true))
->toBe(['foo' => 'bar']);
});

it('should throw with invalid data', function (): void {
JSON::decode('lol');
})->throws(JsonException::class);

it('should return null and not throw with invalid data', function (): void {
expect(JSON::decodeSilently('lol'))
->toBeNull();
});

it('should validate data', function (): void {
expect(JSON::validate('{"foo": "bar"}'))
->toBeTrue()
->and(JSON::validate('lol'))
->toBeFalse();
});
Loading