From: Fabien Potencier Date: Sun, 18 Dec 2011 10:24:52 +0000 (+0100) Subject: added a random function X-Git-Url: http://git.silmor.de/gitweb/?a=commitdiff_plain;h=89a1519e0931318a0182cd9b7f0920cfcac44274;p=web%2Fkonrad%2Ftwig.git added a random function --- diff --git a/CHANGELOG b/CHANGELOG index ee559ee..00be5eb 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -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 diff --git a/lib/Twig/Extension/Core.php b/lib/Twig/Extension/Core.php index 42846e4..d6bd7b8 100644 --- a/lib/Twig/Extension/Core.php +++ b/lib/Twig/Extension/Core.php @@ -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'), ); } @@ -244,6 +245,26 @@ function twig_cycle($values, $i) } /** + * 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. * *
diff --git a/test/Twig/Tests/Extension/CoreTest.php b/test/Twig/Tests/Extension/CoreTest.php
new file mode 100644
index 0000000..3883382
--- /dev/null
+++ b/test/Twig/Tests/Extension/CoreTest.php
@@ -0,0 +1,29 @@
+assertTrue(in_array(twig_random($value), $items));
+            }
+        }
+    }
+}