1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Sarala\Query; |
6
|
|
|
|
7
|
|
|
use Illuminate\Http\Request; |
8
|
|
|
use Illuminate\Support\Collection; |
9
|
|
|
|
10
|
|
|
class QueryParamBag |
11
|
|
|
{ |
12
|
|
|
/** @var Collection $params */ |
13
|
|
|
private $params; |
14
|
|
|
|
15
|
|
|
public function __construct(Request $request, string $field) |
16
|
|
|
{ |
17
|
|
|
$this->params = collect(); |
18
|
|
|
|
19
|
|
|
if ($request->filled($field)) { |
20
|
|
|
$this->prepareParams($request->get($field)); |
21
|
|
|
} |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
public function has($field): bool |
25
|
|
|
{ |
26
|
|
|
return $this->params->has($field); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
public function keys(): array |
30
|
|
|
{ |
31
|
|
|
return $this->params->keys()->all(); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
public function get($field): ?QueryParam |
35
|
|
|
{ |
36
|
|
|
return $this->params->get($field); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
public function each($callback) |
40
|
|
|
{ |
41
|
|
|
$this->params->each($callback); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
protected function prepareParams($value): void |
45
|
|
|
{ |
46
|
|
|
if (is_string($value)) { |
47
|
|
|
$this->prepareStringBasedParams($value); |
48
|
|
|
} elseif (is_array($value)) { |
49
|
|
|
$this->prepareArrayBasedParams($value); |
50
|
|
|
} |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
protected function prepareStringBasedParams($value): void |
54
|
|
|
{ |
55
|
|
|
collect(explode(',', $value))->each(function ($param) { |
56
|
|
|
$sections = explode(':', $param); |
57
|
|
|
$params = $this->prepareStringBasedNestedParams(array_slice($sections, 1)); |
58
|
|
|
|
59
|
|
|
return $this->params->put($sections[0], new QueryParam($sections[0], $params)); |
60
|
|
|
}); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
private function prepareStringBasedNestedParams(array $params): array |
64
|
|
|
{ |
65
|
|
|
return collect($params)->mapWithKeys(function ($param) { |
66
|
|
|
$paramSections = explode('(', $param); |
67
|
|
|
|
68
|
|
|
return [$paramSections[0] => explode('|', str_replace(')', '', $paramSections[1]))]; |
69
|
|
|
})->all(); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
protected function prepareArrayBasedParams($value): void |
73
|
|
|
{ |
74
|
|
|
collect($value)->each(function ($params, $field) { |
75
|
|
|
if ($params === "") { |
76
|
|
|
$params = []; |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
$params = $this->prepareArrayBasedNestedParams($params); |
80
|
|
|
|
81
|
|
|
return $this->params->put($field, new QueryParam($field, $params)); |
82
|
|
|
}); |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
private function prepareArrayBasedNestedParams(array $params): array |
86
|
|
|
{ |
87
|
|
|
return collect($params)->mapWithKeys(function ($param, $name) { |
88
|
|
|
return [$name => explode('|', $param)]; |
89
|
|
|
})->all(); |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
|