Completed
Push — master ( 448054...510bd1 )
by Jakub
02:05
created

Filter::getCondition()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 4
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 2
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
  /**
29
   * @param mixed $value
30
   */
31
  protected static function getCondition(object $item, string $key, string $operator, $value): string {
32 1
    if($key === "%class%") {
33 1
      return "return \"" . get_class($item) . "\" $operator \"$value\";";
34
    }
35 1
    return "return \"{$item->$key}\" $operator \"$value\";";
36
  }
37
38
  public static function matches(object $item, array $filter): bool {
39
    /** @var string $key */
40 1
    foreach($filter as $key => $value) {
41 1
      $operator = static::getOperator($key);
42
      /** @var string $key */
43 1
      $key = Strings::endsWith($key, $operator) ? Strings::before($key, $operator) : $key;
44 1
      if(!eval(static::getCondition($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...
45 1
        return false;
46
      }
47
    }
48 1
    return true;
49
  }
50
51
  public static function applyFilter(array $input, array $filter = []): array {
52 1
    if(count($filter) === 0) {
53 1
      return $input;
54
    }
55 1
    return array_values(array_filter($input, function(object $item) use($filter) {
56 1
      return static::matches($item, $filter);
57 1
    }));
58
  }
59
}
60
?>