-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Json.php
56 lines (48 loc) · 1.61 KB
/
Json.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?php
declare(strict_types=1);
namespace Vection\Component\Common;
use JsonException;
use JsonSerializable;
use Vection\Component\Common\Exception\RuntimeException;
/**
* @author BloodhunterD <[email protected]>
*/
class Json
{
public static function parse(string $json, bool $immutable = false): VArray
{
try {
return new VArray(json_decode($json, true, 512, JSON_THROW_ON_ERROR), $immutable);
}
catch (JsonException $e) {
throw new RuntimeException('Malformed JSON: '.$e->getMessage());
}
}
public static function read(string $filePath): VArray
{
return VArray::parseFile($filePath);
}
/**
* @param VArray|array<mixed>|JsonSerializable $array
*/
public static function encode(VArray|array|JsonSerializable $array, bool $pretty = true, int $flags = 0, int $depth = 512): string
{
if ($pretty) {
$flags += JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_LINE_TERMINATORS;
}
try {
return json_encode($array, $flags | JSON_THROW_ON_ERROR, $depth);
}
catch (JsonException $e) {
throw new RuntimeException('Failed to encode Array to JSON: '.$e->getMessage());
}
}
public static function toFile(
string $filePath, VArray $array, bool $pretty = true, int $flags = 0, int $depth = 512
): void
{
if (!file_put_contents($filePath, self::encode($array, $pretty, $flags, $depth))) {
throw new RuntimeException('Failed to save JSON data in file.');
}
}
}