Chris@0: Chris@0: * Chris@0: * For the full copyright and license information, please view the LICENSE Chris@0: * file that was distributed with this source code. Chris@0: */ Chris@0: Chris@0: namespace Symfony\Component\Translation; Chris@0: Chris@0: use Symfony\Component\Translation\Exception\InvalidArgumentException; Chris@0: Chris@0: /** Chris@0: * Tests if a given number belongs to a given math interval. Chris@0: * Chris@0: * An interval can represent a finite set of numbers: Chris@0: * Chris@0: * {1,2,3,4} Chris@0: * Chris@0: * An interval can represent numbers between two numbers: Chris@0: * Chris@0: * [1, +Inf] Chris@0: * ]-1,2[ Chris@0: * Chris@0: * The left delimiter can be [ (inclusive) or ] (exclusive). Chris@0: * The right delimiter can be [ (exclusive) or ] (inclusive). Chris@0: * Beside numbers, you can use -Inf and +Inf for the infinite. Chris@0: * Chris@0: * @author Fabien Potencier Chris@0: * Chris@0: * @see http://en.wikipedia.org/wiki/Interval_%28mathematics%29#The_ISO_notation Chris@0: */ Chris@0: class Interval Chris@0: { Chris@0: /** Chris@0: * Tests if the given number is in the math interval. Chris@0: * Chris@0: * @param int $number A number Chris@0: * @param string $interval An interval Chris@0: * Chris@0: * @return bool Chris@0: * Chris@0: * @throws InvalidArgumentException Chris@0: */ Chris@0: public static function test($number, $interval) Chris@0: { Chris@0: $interval = trim($interval); Chris@0: Chris@0: if (!preg_match('/^'.self::getIntervalRegexp().'$/x', $interval, $matches)) { Chris@0: throw new InvalidArgumentException(sprintf('"%s" is not a valid interval.', $interval)); Chris@0: } Chris@0: Chris@0: if ($matches[1]) { Chris@0: foreach (explode(',', $matches[2]) as $n) { Chris@0: if ($number == $n) { Chris@0: return true; Chris@0: } Chris@0: } Chris@0: } else { Chris@0: $leftNumber = self::convertNumber($matches['left']); Chris@0: $rightNumber = self::convertNumber($matches['right']); Chris@0: Chris@0: return Chris@0: ('[' === $matches['left_delimiter'] ? $number >= $leftNumber : $number > $leftNumber) Chris@0: && (']' === $matches['right_delimiter'] ? $number <= $rightNumber : $number < $rightNumber) Chris@0: ; Chris@0: } Chris@0: Chris@0: return false; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns a Regexp that matches valid intervals. Chris@0: * Chris@0: * @return string A Regexp (without the delimiters) Chris@0: */ Chris@0: public static function getIntervalRegexp() Chris@0: { Chris@0: return <<[\[\]]) Chris@0: \s* Chris@0: (?P-Inf|\-?\d+(\.\d+)?) Chris@0: \s*,\s* Chris@0: (?P\+?Inf|\-?\d+(\.\d+)?) Chris@0: \s* Chris@0: (?P[\[\]]) Chris@0: EOF; Chris@0: } Chris@0: Chris@0: private static function convertNumber($number) Chris@0: { Chris@0: if ('-Inf' === $number) { Chris@0: return log(0); Chris@0: } elseif ('+Inf' === $number || 'Inf' === $number) { Chris@0: return -log(0); Chris@0: } Chris@0: Chris@0: return (float) $number; Chris@0: } Chris@0: }