From 5ab4dc298327d3a8d51387959d6905c6bb24fd99 Mon Sep 17 00:00:00 2001 From: Andreas Fischer Date: Sat, 5 Mar 2011 22:16:50 +0100 Subject: [PATCH] [ticket/10042] Add mt_rand() wrapper which allows swapping $min and $max. PHPBB3-10042 --- phpBB/includes/functions.php | 16 +++++++++++++ tests/random/mt_rand.php | 46 ++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 tests/random/mt_rand.php diff --git a/phpBB/includes/functions.php b/phpBB/includes/functions.php index 398a02380b..259b3b0481 100644 --- a/phpBB/includes/functions.php +++ b/phpBB/includes/functions.php @@ -244,6 +244,22 @@ function unique_id($extra = 'c') return substr($val, 4, 16); } +/** +* Wrapper for mt_rand() which allows swapping $min and $max parameters. +* +* PHP does not allow us to swap the order of the arguments for mt_rand() anymore. +* (since PHP 5.3.4, see http://bugs.php.net/46587) +* +* @param int $min Lowest value to be returned +* @param int $max Highest value to be returned +* +* @return int Random integer between $min and $max (or $max and $min) +*/ +function phpbb_mt_rand($min, $max) +{ + return ($min > $max) ? mt_rand($max, $min) : mt_rand($min, $max); +} + /** * Return formatted string for filesizes * diff --git a/tests/random/mt_rand.php b/tests/random/mt_rand.php new file mode 100644 index 0000000000..d6502c4e80 --- /dev/null +++ b/tests/random/mt_rand.php @@ -0,0 +1,46 @@ +assertEquals(42, $result); + } + + public function test_max_equals_min_negative() + { + $result = phpbb_mt_rand(-42, -42); + $this->assertEquals(-42, $result); + } + + public function test_max_greater_min() + { + $result = phpbb_mt_rand(3, 4); + $this->assertGreaterThanOrEqual(3, $result); + $this->assertLessThanOrEqual(4, $result); + } + + public function test_min_greater_max() + { + $result = phpbb_mt_rand(4, 3); + $this->assertGreaterThanOrEqual(3, $result); + $this->assertLessThanOrEqual(4, $result); + } + + public function test_min_greater_max_negative() + { + $result = phpbb_mt_rand(-3, -4); + $this->assertGreaterThanOrEqual(-4, $result); + $this->assertLessThanOrEqual(-3, $result); + } +}