mirror of
https://github.com/twigphp/Twig.git
synced 2026-09-16 04:16:28 +00:00
added a random function
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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.
|
||||
*
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user