* 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
'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'),
);
}
}
/**
+ * 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.
*
* <pre>
--- /dev/null
+<?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));
+ }
+ }
+ }
+}