Skip to content

Commit

Permalink
added Helpers::compare()
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Jan 28, 2022
1 parent a823f8e commit 70b3543
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/Utils/Helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -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'"),
};
}
}
47 changes: 47 additions & 0 deletions tests/Utils/Helpers.compare().phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

declare(strict_types=1);

use Nette\Utils\Helpers;
use Tester\Assert;

require __DIR__ . '/../bootstrap.php';


Assert::false(Helpers::compare(1, '>', 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'");

0 comments on commit 70b3543

Please sign in to comment.