added a random function

This commit is contained in:
Fabien Potencier
2011-12-18 11:24:52 +01:00
parent f8b7441e42
commit 89a1519e09
3 changed files with 51 additions and 0 deletions
+1
View File
@@ -1,5 +1,6 @@
* 1.5.0
* added a random function
* added a way to change the default format for the date filter
* fixed the lexer when an operator ending with a letter ends a line
* added string interpolation support
+21
View File
@@ -121,6 +121,7 @@ class Twig_Extension_Core extends Twig_Extension
'range' => new Twig_Function_Function('range'),
'constant' => new Twig_Function_Function('constant'),
'cycle' => new Twig_Function_Function('twig_cycle'),
'random' => new Twig_Function_Function('twig_random'),
);
}
@@ -243,6 +244,26 @@ function twig_cycle($values, $i)
return $values[$i % count($values)];
}
/**
* Returns a random item from sequence.
*
* @param Iterator|array $values An array or an ArrayAccess instance
*
* @return mixed A random value from the given sequence
*/
function twig_random($values)
{
if (!is_array($values) && !$values instanceof Traversable) {
return $values;
}
if (is_object($values) && !$values instanceof Countable) {
$values = iterator_to_array($values);
}
return $values[mt_rand(0, count($values) - 1)];
}
/**
* Converts a date to the given format.
*
+29
View File
@@ -0,0 +1,29 @@
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class Twig_Tests_Extension_CoreTest extends PHPUnit_Framework_TestCase
{
public function testRandomFunction()
{
$core = new Twig_Extension_Core();
$items = array('apple', 'orange', 'citrus');
$values = array(
$items,
new ArrayObject($items),
);
foreach ($values as $value) {
for ($i = 0; $i < 100; $i++) {
$this->assertTrue(in_array(twig_random($value), $items));
}
}
}
}