Passed
Push — master ( c4e846...448054 )
by Jakub
01:35
created

Filter::matches()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 6
nc 5
nop 2
dl 0
loc 10
ccs 6
cts 6
cp 1
crap 4
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Nexendrie\Utils;
5
6
use Nette\Utils\Strings;
7
8
/**
9
 * Filter
10
 *
11
 * @author Jakub Konečný
12
 * @internal
13
 */
14 1
final class Filter {
15 1
  use \Nette\StaticClass;
16
  
17
  public const OPERATORS = ["==", ">=", ">", "<=", "<", "!=",];
18
  
19
  public static function getOperator(string $input): string {
20 1
    foreach(static::OPERATORS as $operator) {
21 1
      if(Strings::endsWith($input, $operator)) {
22 1
        return $operator;
23
      }
24
    }
25 1
    return static::OPERATORS[0];
26
  }
27
28
  public static function matches(object $item, array $filter): bool {
29
    /** @var string $key */
30 1
    foreach($filter as $key => $value) {
31 1
      $operator = static::getOperator($key);
32 1
      $key = Strings::endsWith($key, $operator) ? Strings::before($key, $operator) : $key;
33 1
      if(!eval("return \"{$item->$key}\" $operator \"$value\";")) {
0 ignored issues
show
introduced by
The use of eval() is discouraged.
Loading history...
introduced by
Use of eval() is discouraged
Loading history...
34 1
        return false;
35
      }
36
    }
37 1
    return true;
38
  }
39
40
  public static function applyFilter(array $input, array $filter = []): array {
41 1
    if(count($filter) === 0) {
42 1
      return $input;
43
    }
44 1
    return array_values(array_filter($input, function(object $item) use($filter) {
45 1
      return static::matches($item, $filter);
46 1
    }));
47
  }
48
}
49
?>