Filter::matches()   A
last analyzed

Complexity

Conditions 4
Paths 5

Size

Total Lines 11
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 11
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
  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
    if(preg_match("#([a-zA-Z0-9_]+)\(\)\$#", $key, $matches) === 1) {
36 1
      return "return  \"{$item->{$matches[1]}()}\" $operator  \"$value\";";
37
    }
38 1
    return "return \"{$item->$key}\" $operator \"$value\";";
39
  }
40
41
  public static function matches(object $item, array $filter): bool {
42
    /** @var string $key */
43 1
    foreach($filter as $key => $value) {
44 1
      $operator = static::getOperator($key);
45
      /** @var string $key */
46 1
      $key = Strings::endsWith($key, $operator) ? Strings::before($key, $operator) : $key;
47 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...
48 1
        return false;
49
      }
50
    }
51 1
    return true;
52
  }
53
54
  public static function applyFilter(array $input, array $filter = []): array {
55 1
    if(count($filter) === 0) {
56 1
      return $input;
57
    }
58 1
    return array_values(array_filter($input, function(object $item) use($filter): bool {
59 1
      return static::matches($item, $filter);
60 1
    }));
61
  }
62
}
63
?>