4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Translation
;
14 use Symfony\Component\Translation\Exception\InvalidArgumentException
;
17 * Tests if a given number belongs to a given math interval.
19 * An interval can represent a finite set of numbers:
23 * An interval can represent numbers between two numbers:
28 * The left delimiter can be [ (inclusive) or ] (exclusive).
29 * The right delimiter can be [ (exclusive) or ] (inclusive).
30 * Beside numbers, you can use -Inf and +Inf for the infinite.
32 * @author Fabien Potencier <fabien@symfony.com>
34 * @see http://en.wikipedia.org/wiki/Interval_%28mathematics%29#The_ISO_notation
39 * Tests if the given number is in the math interval.
41 * @param int $number A number
42 * @param string $interval An interval
46 * @throws InvalidArgumentException
48 public static function test($number, $interval)
50 $interval = trim($interval);
52 if (!preg_match('/^'.self
::getIntervalRegexp().'$/x', $interval, $matches)) {
53 throw new InvalidArgumentException(sprintf('"%s" is not a valid interval.', $interval));
57 foreach (explode(',', $matches[2]) as $n) {
63 $leftNumber = self
::convertNumber($matches['left']);
64 $rightNumber = self
::convertNumber($matches['right']);
67 ('[' === $matches['left_delimiter'] ?
$number >= $leftNumber : $number > $leftNumber)
68 && (']' === $matches['right_delimiter'] ?
$number <= $rightNumber : $number < $rightNumber)
76 * Returns a Regexp that matches valid intervals.
78 * @return string A Regexp (without the delimiters)
80 public static function getIntervalRegexp()
84 (\-?\d+(\.\d+)?[\s*,\s*\-?\d+(\.\d+)?]*)
89 (?P<left_delimiter>[\[\]])
91 (?P<left>-Inf|\-?\d+(\.\d+)?)
93 (?P<right>\+?Inf|\-?\d+(\.\d+)?)
95 (?P<right_delimiter>[\[\]])
99 private static function convertNumber($number)
101 if ('-Inf' === $number) {
103 } elseif ('+Inf' === $number ||
'Inf' === $number) {
107 return (float) $number;