-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathInteractsWithJson.php
More file actions
71 lines (55 loc) · 1.84 KB
/
Copy pathInteractsWithJson.php
File metadata and controls
71 lines (55 loc) · 1.84 KB
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
66
67
68
69
70
71
<?php
declare(strict_types=1);
namespace Zero\Lib\Http\Concerns;
trait InteractsWithJson
{
protected ?array $jsonPayload = null;
public function all(): array
{
return array_replace_recursive($this->query ?? [], $this->request ?? [], $this->json() ?? []);
}
public function input(string $key, mixed $default = null): mixed
{
return $this->dataGet($this->all(), $key, $default);
}
public function has(string $key): bool
{
return $this->dataGet($this->all(), $key, null) !== null;
}
public function json(?string $key = null, mixed $default = null): ?array
{
if ($this->jsonPayload === null) {
$this->jsonPayload = [];
if ($this->isJsonRequest()) {
$decoded = json_decode($this->rawBody ?? '', true);
if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
$this->jsonPayload = $decoded;
}
}
}
if ($key === null) {
return $this->jsonPayload ?: null;
}
return $this->dataGet($this->jsonPayload ?? [], $key, $default);
}
protected function isJsonRequest(): bool
{
$contentType = strtolower((string) $this->header('content-type', ''));
return str_contains($contentType, 'application/json') || str_contains($contentType, '+json');
}
protected function dataGet(array $target, string $key, mixed $default = null): mixed
{
if ($key === '') {
return $target;
}
$segments = explode('.', $key);
foreach ($segments as $segment) {
if (is_array($target) && array_key_exists($segment, $target)) {
$target = $target[$segment];
} else {
return $default;
}
}
return $target;
}
}