-
-
Notifications
You must be signed in to change notification settings - Fork 80
/
FilterHelper.php
83 lines (71 loc) · 2.45 KB
/
FilterHelper.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?php
declare(strict_types=1);
/**
* Flextype (https://flextype.org)
* Founded by Sergey Romanenko and maintained by Flextype Community.
*/
if (! function_exists('filter')) {
/**
* Create a collection from the given value and filter it.
*
* @param mixed $items Items.
* @param array $options Options array.
*
* @return array
*/
function filter($items = [], array $options = []): array
{
$collection = arrays($items);
! isset($options['return']) and $options['return'] = 'all';
if (isset($options['where'])) {
if (is_array($options['where'])) {
foreach ($options['where'] as $key => $value) {
if (
! isset($value['key']) ||
! isset($value['operator']) ||
! isset($value['value'])
) {
continue;
}
$collection->where($value['key'], $value['operator'], $value['value']);
}
}
}
if (isset($options['group_by'])) {
$collection->groupBy($options['group_by']);
}
if (isset($options['sort_by'])) {
if (isset($options['sort_by']['key']) && isset($options['sort_by']['direction'])) {
$collection->sortBy($options['sort_by']['key'], $options['sort_by']['direction']);
}
}
if (isset($options['offset'])) {
$collection->offset(isset($options['offset']) ? (int) $options['offset'] : 0);
}
if (isset($options['limit'])) {
$collection->limit(isset($options['limit']) ? (int) $options['limit'] : 0);
}
switch ($options['return']) {
case 'first':
$result = $collection->first();
break;
case 'last':
$result = $collection->last();
break;
case 'next':
$result = $collection->next();
break;
case 'random':
$result = $collection->random(isset($options['random']) ? (int) $options['random'] : null);
break;
case 'shuffle':
$result = $collection->shuffle()->toArray();
break;
case 'all':
default:
$result = $collection->all();
break;
}
return $result;
}
}