1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace Compolomus\Collection; |
4
|
|
|
|
5
|
|
|
use InvalidArgumentException; |
6
|
|
|
|
7
|
|
|
class Linq |
8
|
|
|
{ |
9
|
|
|
private $collection; |
10
|
|
|
|
11
|
|
|
private const CONDITIONS_TYPES = [ |
12
|
|
|
'=', |
13
|
|
|
'!=', |
14
|
|
|
'>', |
15
|
|
|
'<', |
16
|
|
|
'<=', |
17
|
|
|
'>=', |
18
|
|
|
]; |
19
|
|
|
|
20
|
|
|
public function __construct(Collection $collection) |
21
|
|
|
{ |
22
|
|
|
$this->collection = $collection; |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
public function where(string $query): self |
26
|
|
|
{ |
27
|
|
|
$pattern = '#(?P<field>.*)?(?P<condition>' . implode('|', self::CONDITIONS_TYPES) . ')(?P<value>.*)#is'; |
28
|
|
|
|
29
|
|
|
preg_match($pattern, $query, $matches); |
30
|
|
|
|
31
|
|
|
$count = count($matches); |
32
|
|
|
|
33
|
|
|
if (!$count || $count < 4) { |
34
|
|
|
throw new InvalidArgumentException('Not matches ' . '<pre>' . print_r($matches, true) . '</pre>'); |
35
|
|
|
} |
36
|
|
|
$args = array_map('trim', $matches); |
37
|
|
|
|
38
|
|
|
$array = [ |
39
|
|
|
'=' => '===', |
40
|
|
|
'!=' => '!==', |
41
|
|
|
]; |
42
|
|
|
|
43
|
|
|
return $this->prepare($args['field'], |
44
|
|
|
(in_array($args['condition'], $array, true) ? $array[$args['condition']] : $args['condition']), |
45
|
|
|
$args['value']); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
private function condition($valFirst, string $condition, $valSecond): bool |
49
|
|
|
{ |
50
|
|
|
switch ($condition) { |
51
|
|
|
case '=': |
52
|
|
|
return $valFirst === $valSecond; |
53
|
|
|
break; |
|
|
|
|
54
|
|
|
case '!=': |
55
|
|
|
return $valFirst !== $valSecond; |
56
|
|
|
break; |
|
|
|
|
57
|
|
|
case '>': |
58
|
|
|
return $valFirst > $valSecond; |
59
|
|
|
break; |
|
|
|
|
60
|
|
|
case '<': |
61
|
|
|
return $valFirst < $valSecond; |
62
|
|
|
break; |
|
|
|
|
63
|
|
|
case '>=': |
64
|
|
|
return $valFirst >= $valSecond; |
65
|
|
|
break; |
|
|
|
|
66
|
|
|
case '<=': |
67
|
|
|
return $valFirst <= $valSecond; |
68
|
|
|
break; |
|
|
|
|
69
|
|
|
default: |
70
|
|
|
throw new InvalidArgumentException('Condition not set'); |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
public function prepare(string $field, string $condition, $value): self |
75
|
|
|
{ |
76
|
|
|
$new = new Collection($this->collection->getGeneric()); |
77
|
|
|
|
78
|
|
|
foreach ($this->collection->get() as $val) { |
79
|
|
|
!$this->condition($val->$field, $condition, $value) ?: $new->addOne($val); |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
$this->collection = $new; |
83
|
|
|
|
84
|
|
|
return $this; |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
|
88
|
|
|
public function get(): array |
89
|
|
|
{ |
90
|
|
|
return $this->collection->get(); |
91
|
|
|
} |
92
|
|
|
} |
93
|
|
|
|
The break statement is not necessary if it is preceded for example by a return statement:
If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.