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
;
15 * Tests if a given number belongs to a given math interval.
17 * An interval can represent a finite set of numbers:
21 * An interval can represent numbers between two numbers:
26 * The left delimiter can be [ (inclusive) or ] (exclusive).
27 * The right delimiter can be [ (exclusive) or ] (inclusive).
28 * Beside numbers, you can use -Inf and +Inf for the infinite.
30 * @author Fabien Potencier <fabien@symfony.com>
32 * @see http://en.wikipedia.org/wiki/Interval_%28mathematics%29#The_ISO_notation
37 * Tests if the given number is in the math interval.
39 * @param integer $number A number
40 * @param string $interval An interval
44 * @throws \InvalidArgumentException
46 public static function test($number, $interval)
48 $interval = trim($interval);
50 if (!preg_match('/^'.self
::getIntervalRegexp().'$/x', $interval, $matches)) {
51 throw new \
InvalidArgumentException(sprintf('"%s" is not a valid interval.', $interval));
55 foreach (explode(',', $matches[2]) as $n) {
61 $leftNumber = self
::convertNumber($matches['left']);
62 $rightNumber = self
::convertNumber($matches['right']);
65 ('[' === $matches['left_delimiter'] ? $number >= $leftNumber : $number > $leftNumber)
66 && (']' === $matches['right_delimiter'] ? $number <= $rightNumber : $number < $rightNumber)
74 * Returns a Regexp that matches valid intervals.
76 * @return string A Regexp (without the delimiters)
78 public static function getIntervalRegexp()
82 (\-?\d+(\.\d+)?[\s*,\s*\-?\d+(\.\d+)?]*)
87 (?P<left_delimiter>[\[\]])
89 (?P<left>-Inf|\-?\d+(\.\d+)?)
91 (?P<right>\+?Inf|\-?\d+(\.\d+)?)
93 (?P<right_delimiter>[\[\]])
97 private static function convertNumber($number)
99 if ('-Inf' === $number) {
101 } elseif ('+Inf' === $number || 'Inf' === $number) {
105 return (float) $number;