Skip to content

Commit

Permalink
added preserveKeys support for the batch filter
Browse files Browse the repository at this point in the history
  • Loading branch information
fabpot committed Mar 12, 2019
1 parent e797635 commit 37c398f
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 10 deletions.
1 change: 1 addition & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
* 1.38.0 (2019-XX-XX)

* added preserveKeys support for the batch filter
* added the possibility to pass a TemplateWrapper to Twig\Environment::load()
* improved the performance of the sandbox
* added a spaceless filter
Expand Down
13 changes: 5 additions & 8 deletions src/Extension/CoreExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -1638,23 +1638,20 @@ function twig_constant_is_defined($constant, $object = null)
*
* @return array
*/
function twig_array_batch($items, $size, $fill = null)
function twig_array_batch($items, $size, $fill = null, $preserveKeys = true)
{
if ($items instanceof \Traversable) {
$items = iterator_to_array($items, false);
$items = iterator_to_array($items, $preserveKeys);
}

$size = ceil($size);

$result = array_chunk($items, $size, true);
$result = array_chunk($items, $size, $preserveKeys);

if (null !== $fill && !empty($result)) {
if (null !== $fill && $result) {
$last = \count($result) - 1;
if ($fillCount = $size - \count($result[$last])) {
$result[$last] = array_merge(
$result[$last],
array_fill(0, $fillCount, $fill)
);
$result[$last] = array_merge($result[$last], array_fill(0, $fillCount, $fill));
}
}

Expand Down
4 changes: 2 additions & 2 deletions test/Twig/Tests/Fixtures/filters/batch_with_keys.test
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
--TEST--
"batch" filter preserves array keys
--TEMPLATE--
{{ {'foo': 'bar', 'key': 'value'}|batch(4)|first|keys|join(',') }}
{{ {'foo': 'bar', 'key': 'value'}|batch(4, 'fill')|first|keys|join(',') }}
{{ {'foo': 'bar', 'key': 'value'}|batch(4)|first|keys|join(',') }}
{{ {'foo': 'bar', 'key': 'value'}|batch(4, 'fill')|first|keys|join(',') }}
--DATA--
return []
--EXPECT--
Expand Down

0 comments on commit 37c398f

Please sign in to comment.