Passed
Branch master (4aba6c)
by compolom
03:10 queued 01:29
created

Linq::condition()   B

Complexity

Conditions 7
Paths 7

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 17.5839

Importance

Changes 0
Metric Value
dl 0
loc 19
ccs 6
cts 15
cp 0.4
rs 8.8333
c 0
b 0
f 0
cc 7
nc 7
nop 3
crap 17.5839
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 4
    public function __construct(Collection $collection)
21
    {
22 4
        $this->collection = $collection;
23 4
    }
24
25 2
    public function where(string $query): self
26
    {
27 2
        $pattern = '#(?P<field>.*)?(?P<condition>' . implode('|', self::CONDITIONS_TYPES) . ')(?P<value>.*)#is';
28
29 2
        preg_match($pattern, $query, $matches);
30
31 2
        $count = count($matches);
32
33 2
        if (!$count || $count < 4) {
34 2
            throw new InvalidArgumentException('Not matches ' . '<pre>' . print_r($matches, true) . '</pre>');
35
        }
36 2
        $args = array_map('trim', $matches);
37
38
        $array = [
39 2
            '=' => '===',
40
            '!=' => '!==',
41
        ];
42
43 2
        return $this->prepare($args['field'],
44 2
            (in_array($args['condition'], $array, true) ? $array[$args['condition']] : $args['condition']),
45 2
            $args['value']);
46
    }
47
    
48 2
    private function condition($valFirst, string $condition, $valSecond): bool
49
    {
50 2
        switch ($condition) {
51 2
            case '=':
52
                return $valFirst === $valSecond;
53 2
            case '!=':
54
                return $valFirst !== $valSecond;
55 2
            case '>':
56 2
                return $valFirst > $valSecond;
57
            case '<':
58
                return $valFirst < $valSecond;
59
            case '>=':
60
                return $valFirst >= $valSecond;
61
            case '<=':
62
                return $valFirst <= $valSecond;
63
            default:
64
                throw new InvalidArgumentException('Condition not set');
65
        }
66
    }
67
68 2
    private function prepare(string $field, string $condition, $value): self
69
    {
70 2
        $new = new Collection($this->collection->getGeneric());
71
72 2
        foreach ($this->collection->get() as $val) {
73 2
            !$this->condition($val->$field, $condition, $value) ?: $new->addOne($val);
74
        }
75
76 2
        $this->collection = $new;
77
78 2
        return $this;
79
    }
80
81
82 3
    public function get(): array
83
    {
84 3
        return $this->collection->get();
85
    }
86
}
87