Skip to content

Commit

Permalink
Clean up Collection::transpose().
Browse files Browse the repository at this point in the history
Refs #8957
  • Loading branch information
markstory committed Jun 17, 2016
1 parent 9114949 commit 2f4f433
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 65 deletions.
4 changes: 1 addition & 3 deletions src/Collection/CollectionInterface.php
Expand Up @@ -946,7 +946,6 @@ public function isEmpty();
*/
public function unwrap();


/**
* Transpose rows and columns into columns and rows
*
Expand All @@ -969,10 +968,9 @@ public function unwrap();
* // ['2013', '100', '200', '300'],
* // ['2014', '50', '100', '200'],
* // ]
*
* ```
*
* @return Collection
* @return \Cake\Collection\CollectionInterface
*/
public function transpose();
}
5 changes: 3 additions & 2 deletions src/Collection/CollectionTrait.php
Expand Up @@ -30,6 +30,7 @@
use Cake\Collection\Iterator\ZipIterator;
use Countable;
use LimitIterator;
use LogicException;
use RecursiveIteratorIterator;
use Traversable;

Expand Down Expand Up @@ -662,7 +663,7 @@ public function _unwrap()
/**
* {@inheritDoc}
*
* @return \Cake\Collection
* @return \Cake\Collection\CollectionInterface
*/
public function transpose()
{
Expand All @@ -671,7 +672,7 @@ public function transpose()
$result = [];
foreach ($arrayValue as $column => $row) {
if (count($row) != $length) {
throw new \LogicException('Child arrays do not have even length');
throw new LogicException('Child arrays do not have even length');
}
$result[] = array_column($arrayValue, $column);
}
Expand Down
37 changes: 37 additions & 0 deletions tests/TestCase/Collection/CollectionTest.php
Expand Up @@ -1602,4 +1602,41 @@ public function testChunkNested()
$expected = [[1, 2], [3, [4, 5]], [6, [7, [8, 9], 10]], [11]];
$this->assertEquals($expected, $chunked);
}

public function testTranspose()
{
$collection = new Collection([
['Products', '2012', '2013', '2014'],
['Product A', '200', '100', '50'],
['Product B', '300', '200', '100'],
['Product C', '400', '300', '200'],
]);
$transposed = $collection->transpose();
$expected = [
['Products', 'Product A', 'Product B', 'Product C'],
['2012', '200', '300', '400'],
['2013', '100', '200', '300'],
['2014', '50', '100', '200'],
];

$this->assertEquals($expected, $transposed->toList());
}

/**
* Tests that provided arrays do not have even length
*
* @expectedException \LogicException
* @return void
*/
public function testTransposeUnEvenLengthShouldThrowException()
{
$collection = new Collection([
['Products', '2012', '2013', '2014'],
['Product A', '200', '100', '50'],
['Product B', '300'],
['Product C', '400', '300'],
]);

$collection->transpose();
}
}
60 changes: 0 additions & 60 deletions tests/TestCase/Collection/Iterator/TransposeIteratorTest.php

This file was deleted.

0 comments on commit 2f4f433

Please sign in to comment.