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

Filter   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 32
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 17
dl 0
loc 32
ccs 16
cts 16
cp 1
rs 10
c 0
b 0
f 0
wmc 9

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getOperator() 0 7 3
A applyFilter() 0 6 2
A matches() 0 10 4
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
?>