-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathJson.php
65 lines (48 loc) · 1.36 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
57
58
59
60
61
62
63
64
65
<?php
namespace ZhenMu\Support\Utils;
use Illuminate\Support\Arr;
class Json
{
protected $filepath;
protected $data = [];
public function __construct(?string $filepath = null)
{
$this->filepath = $filepath;
$this->decode();
}
public static function make(?string $filepath = null)
{
return new static($filepath);
}
public function decode(?string $content = null)
{
if ($this->filepath && file_exists($this->filepath)) {
$content = @file_get_contents($this->filepath);
}
if (!$content) {
$content = '';
}
$this->data = json_decode($content, true) ?? [];
return $this;
}
public function encode(?array $data = null, $options = null)
{
$defaultOptions = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_NUMERIC_CHECK| JSON_PRETTY_PRINT;
if ($options) {
$options = $defaultOptions | $options;
} else {
$options = $defaultOptions;
}
if ($data) {
$this->data = $data;
}
return json_encode($this->data, $options);
}
public function get(mixed $key = null, mixed $default = null)
{
if (!Arr::has($this->data, $key)) {
return $this->data;
}
return Arr::get($this->data, $key, $default);
}
}