nexendrie /
utils
| 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
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 | ?> |