Completed
Push — master ( 6a2690...9f8cee )
by Milroy
01:22
created

QueryParamBag::isEmpty()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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