added support for an "arrow" function on the "sort" filter

This commit is contained in:
Fabien Potencier
2019-08-20 10:13:31 +02:00
parent 163f6a0979
commit 330024b67e
4 changed files with 45 additions and 2 deletions
+1
View File
@@ -1,5 +1,6 @@
* 2.12.0 (2019-XX-XX)
* added support for an "arrow" function on the "sort" filter
* added the CssInliner extension in the "extra" repositories: "inline_css"
filter
* added the Inky extension in the "extra" repositories: "inky" filter
+24
View File
@@ -1,6 +1,9 @@
``sort``
========
.. versionadded:: 2.12
The ``arrow`` argument was added in Twig 2.12.
The ``sort`` filter sorts an array:
.. code-block:: twig
@@ -15,4 +18,25 @@ The ``sort`` filter sorts an array:
association. It supports Traversable objects by transforming
those to arrays.
You can pass an arrow function to sort the array:
.. code-block:: twig
{% set list = [
{ name: 'Apples', quantity: 5 },
{ name: 'Oranges', quantity: 2 },
{ name: 'Grapes', quantity: 4 },
] %}
{% for fruit in fruits|sort((a, b) => a.quantity == b.quantity ? 0 : (a.quantity > b.quantity ? 1 : -1))|column('name') %}
{{ fruit }}
{% endfor %}
{# output in this order: Oranges, Grapes, Apples #}
Arguments
---------
* ``arrow``: An arrow function
.. _`asort`: https://secure.php.net/asort
+6 -2
View File
@@ -904,7 +904,7 @@ function twig_reverse_filter(Environment $env, $item, $preserveKeys = false)
*
* @return array
*/
function twig_sort_filter($array)
function twig_sort_filter($array, $arrow = null)
{
if ($array instanceof \Traversable) {
$array = iterator_to_array($array);
@@ -912,7 +912,11 @@ function twig_sort_filter($array)
throw new RuntimeError(sprintf('The sort filter only works with arrays or "Traversable", got "%s".', \gettype($array)));
}
asort($array);
if (null !== $arrow) {
uasort($array, $arrow);
} else {
asort($array);
}
return $array;
}
@@ -0,0 +1,14 @@
--TEST--
"sort" filter
--TEMPLATE--
{{ fruits|sort((a, b) => a.quantity == b.quantity ? 0 : (a.quantity > b.quantity ? 1 : -1))|column('name')|join(', ') }}
--DATA--
return [
'fruits' => [
[ 'name' => 'Apples', 'quantity' => 5 ],
[ 'name' => 'Oranges', 'quantity' => 2 ],
[ 'name' => 'Grapes', 'quantity' => 4 ],
],
]
--EXPECT--
Oranges, Grapes, Apples