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 e26a4e8
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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
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 static function arrayShuffle(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 e26a4e8

Please sign in to comment.