Skip to content

Commit

Permalink
Merge pull request FluidTYPO3#641 from Cash2m/add-preserve-keys
Browse files Browse the repository at this point in the history
[TASK] Add argument to preserve array keys on ChunkViewHelper
  • Loading branch information
NamelessCoder committed Jul 23, 2014
2 parents f769135 + 922e859 commit 689d3c2
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
7 changes: 4 additions & 3 deletions Classes/ViewHelpers/Iterator/ChunkViewHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,11 @@ class ChunkViewHelper extends AbstractViewHelper {
* @param boolean $fixed Whether to allocate items to a fixed number of chunks or not
* @param mixed $subject The subject Traversable/Array instance to shift
* @param string $as If specified, inserts a template variable with this name, then renders the child content, then removes the variable
* @param boolean $preserveKeys If set to true, the original array keys will be preserved in the chunks
* @throws \Exception
* @return array
*/
public function render($count, $fixed = FALSE, $subject = NULL, $as = NULL) {
public function render($count, $fixed = FALSE, $subject = NULL, $as = NULL, $preserveKeys = FALSE) {
if (NULL === $subject) {
$subject = $this->renderChildren();
}
Expand All @@ -63,15 +64,15 @@ public function render($count, $fixed = FALSE, $subject = NULL, $as = NULL) {
$subjectSize = count($subject);
if (0 < $subjectSize) {
$chunkSize = ceil($subjectSize / $count);
$output = array_chunk($subject, $chunkSize);
$output = array_chunk($subject, $chunkSize, $preserveKeys);
}
// Fill the resulting array with empty items to get the desired element count
$elementCount = count($output);
if ($elementCount < $count) {
$output += array_fill($elementCount, $count - $elementCount, NULL);
}
} else {
$output = array_chunk($subject, $count);
$output = array_chunk($subject, $count, $preserveKeys);
}
if (NULL !== $as) {
$variables = array($as => $output);
Expand Down
15 changes: 15 additions & 0 deletions Tests/Unit/ViewHelpers/Iterator/ChunkViewHelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -95,4 +95,19 @@ public function returnsEmptyResultForZeroCount() {
$this->assertCount(0, $result);
}

/**
* @test
*/
public function preservesArrayKeysIfRequested() {
$arguments = array(
'count' => 2,
'subject' => array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5),
'preserveKeys' => TRUE,
);
$result = $this->executeViewHelper($arguments);

$expected = array(array('a' => 1, 'b' => 2), array('c' => 3, 'd' => 4), array('e' => 5));
$this->assertEquals($expected, $result);
}

}

0 comments on commit 689d3c2

Please sign in to comment.