diff --git a/src/Utils/Helpers.php b/src/Utils/Helpers.php index f27b9e7be..1471e5351 100644 --- a/src/Utils/Helpers.php +++ b/src/Utils/Helpers.php @@ -82,4 +82,23 @@ public static function getSuggestion(array $possibilities, string $value): ?stri return $best; } + + + /** + * Compares two values. Recognizes operators: >, >=, <, <=, =, ==, ===, !=, !==, <> + */ + public static function compare(mixed $l, string $operator, mixed $r): bool + { + return match ($operator) { + '>' => $l > $r, + '>=' => $l >= $r, + '<' => $l < $r, + '<=' => $l <= $r, + '=', '==' => $l == $r, + '===' => $l === $r, + '!=', '<>' => $l != $r, + '!==' => $l !== $r, + default => throw new Nette\InvalidArgumentException("Unknown operator '$operator'"), + }; + } } diff --git a/tests/Utils/Helpers.compare().phpt b/tests/Utils/Helpers.compare().phpt new file mode 100644 index 000000000..2790cbe42 --- /dev/null +++ b/tests/Utils/Helpers.compare().phpt @@ -0,0 +1,47 @@ +', 1)); +Assert::false(Helpers::compare(1, '>', 2)); +Assert::false(Helpers::compare(1, '<', 1)); +Assert::true(Helpers::compare(1, '<', 2)); + +Assert::true(Helpers::compare(1, '>=', 1)); +Assert::false(Helpers::compare(1, '>=', 2)); +Assert::true(Helpers::compare(1, '<=', 1)); +Assert::true(Helpers::compare(1, '<=', 2)); + +Assert::true(Helpers::compare(1, '=', 1)); +Assert::true(Helpers::compare(1.0, '=', 1)); +Assert::false(Helpers::compare(1, '=', 2)); + +Assert::true(Helpers::compare(1, '==', 1)); +Assert::true(Helpers::compare(1.0, '==', 1)); +Assert::false(Helpers::compare(1, '==', 2)); + +Assert::true(Helpers::compare(1, '===', 1)); +Assert::false(Helpers::compare(1.0, '===', 1)); +Assert::false(Helpers::compare(1, '===', 2)); + +Assert::false(Helpers::compare(1, '<>', 1)); +Assert::false(Helpers::compare(1.0, '<>', 1)); +Assert::true(Helpers::compare(1, '<>', 2)); + +Assert::false(Helpers::compare(1, '!=', 1)); +Assert::false(Helpers::compare(1.0, '!=', 1)); +Assert::true(Helpers::compare(1, '!=', 2)); + +Assert::false(Helpers::compare(1, '!==', 1)); +Assert::true(Helpers::compare(1.0, '!==', 1)); +Assert::true(Helpers::compare(1, '!==', 2)); + +Assert::exception(function () { + Helpers::compare(1, 'x', 1); +}, Nette\InvalidArgumentException::class, "Unknown operator 'x'");