Skip to content

Commit

Permalink
[templates] add shuffle filter
Browse files Browse the repository at this point in the history
  • Loading branch information
Sarah-eit committed Jan 23, 2024
1 parent 3e94978 commit e7a0e6a
Show file tree
Hide file tree
Showing 6 changed files with 5 additions and 49 deletions.
10 changes: 4 additions & 6 deletions doc/filters/shuffle.rst
@@ -1,5 +1,5 @@
``shuffle``
========
===========

The ``shuffle`` filter shuffles an array:

Expand All @@ -11,9 +11,9 @@ The ``shuffle`` filter shuffles an array:
.. caution::

Internally, Twig uses the PHP `shuffle`_ function.
This function assigns new keys to the elements in array. It will remove
any existing keys that may have been assigned, rather than just reordering the keys.
The shuffled array does not preserve keys. So if the input had not sequential keys
but indexed keys (using the user id for instance),
it is not the case anymore after shuffling it.

Example 1:

Expand Down Expand Up @@ -72,5 +72,3 @@ The above example will be rendered as:

Note, results can also be :
"d, e, f" or "e, d, f" or "e, f, d" or "f, d, e" or "f, e, d".

.. _`shuffle`: https://www.php.net/shuffle
10 changes: 1 addition & 9 deletions src/Extension/CoreExtension.php
Expand Up @@ -953,18 +953,10 @@ public static function sortFilter(Environment $env, $array, $arrow = null)
* Shuffle an array.
* The function does not preserve keys.
*
* @param array|\Traversable $array
*
* @return array
*
* @internal
*/
public function shuffle($array)
public function shuffle(iterable $array): array
{
if (!is_iterable($array)) {
throw new RuntimeError(sprintf('The shuffle filter only works with array or "Traversable", got "%s" as argument.', \gettype($array)));
}

$array = self::toArray($array, false);
shuffle($array);

Expand Down
10 changes: 0 additions & 10 deletions tests/Fixtures/filters/shuffle_with_alphanumerics_characters.test

This file was deleted.

8 changes: 0 additions & 8 deletions tests/Fixtures/filters/shuffle_with_boolean.test

This file was deleted.

8 changes: 0 additions & 8 deletions tests/Fixtures/filters/shuffle_with_empty_string.test

This file was deleted.

8 changes: 0 additions & 8 deletions tests/Fixtures/filters/shuffle_with_null_value.test

This file was deleted.

0 comments on commit e7a0e6a

Please sign in to comment.