You are here

function twig_random in Zircon Profile 8.0

Same name and namespace in other branches
  1. 8 vendor/twig/twig/lib/Twig/Extension/Core.php \twig_random()

Returns a random value depending on the supplied parameter type:

  • a random item from a Traversable or array
  • a random character from a string
  • a random integer between 0 and the integer parameter.

Parameters

Twig_Environment $env A Twig_Environment instance:

Traversable|array|int|string $values The values to pick a random item from:

Return value

mixed A random value from the given sequence

Throws

Twig_Error_Runtime When $values is an empty array (does not apply to an empty string which is returned as is).

5 calls to twig_random()
Twig_Tests_Extension_CoreTest::testRandomFunction in vendor/twig/twig/test/Twig/Tests/Extension/CoreTest.php
@dataProvider getRandomFunctionTestData
Twig_Tests_Extension_CoreTest::testRandomFunctionOfEmptyArrayThrowsException in vendor/twig/twig/test/Twig/Tests/Extension/CoreTest.php
@expectedException Twig_Error_Runtime
Twig_Tests_Extension_CoreTest::testRandomFunctionOnNonUTF8String in vendor/twig/twig/test/Twig/Tests/Extension/CoreTest.php
Twig_Tests_Extension_CoreTest::testRandomFunctionReturnsAsIs in vendor/twig/twig/test/Twig/Tests/Extension/CoreTest.php
Twig_Tests_Extension_CoreTest::testRandomFunctionWithoutParameter in vendor/twig/twig/test/Twig/Tests/Extension/CoreTest.php
1 string reference to 'twig_random'
Twig_Extension_Core::getFunctions in vendor/twig/twig/lib/Twig/Extension/Core.php

File

vendor/twig/twig/lib/Twig/Extension/Core.php, line 369

Code

function twig_random(Twig_Environment $env, $values = null) {
  if (null === $values) {
    return mt_rand();
  }
  if (is_int($values) || is_float($values)) {
    return $values < 0 ? mt_rand($values, 0) : mt_rand(0, $values);
  }
  if ($values instanceof Traversable) {
    $values = iterator_to_array($values);
  }
  elseif (is_string($values)) {
    if ('' === $values) {
      return '';
    }
    if (null !== ($charset = $env
      ->getCharset())) {
      if ('UTF-8' != $charset) {
        $values = twig_convert_encoding($values, 'UTF-8', $charset);
      }

      // unicode version of str_split()
      // split at all positions, but not after the start and not before the end
      $values = preg_split('/(?<!^)(?!$)/u', $values);
      if ('UTF-8' != $charset) {
        foreach ($values as $i => $value) {
          $values[$i] = twig_convert_encoding($value, $charset, 'UTF-8');
        }
      }
    }
    else {
      return $values[mt_rand(0, strlen($values) - 1)];
    }
  }
  if (!is_array($values)) {
    return $values;
  }
  if (0 === count($values)) {
    throw new Twig_Error_Runtime('The random function cannot pick from an empty array.');
  }
  return $values[array_rand($values, 1)];
}