diff --git a/src/macros/transpose.php b/src/macros/transpose.php index d9121a4..c330dd5 100644 --- a/src/macros/transpose.php +++ b/src/macros/transpose.php @@ -14,10 +14,12 @@ return new static(); } - $expectedLength = count($this->first()); + $firstItem = $this->first(); + + $expectedLength = is_array($firstItem) || $firstItem instanceof Countable ? count($firstItem) : 0; array_walk($this->items, function ($row) use ($expectedLength) { - if (count($row) !== $expectedLength) { + if ((is_array($row) || $row instanceof Countable) && count($row) !== $expectedLength) { throw new \LengthException("Element's length must be equal."); } }); diff --git a/tests/TransposeTest.php b/tests/TransposeTest.php index a6a8bec..46c63b0 100644 --- a/tests/TransposeTest.php +++ b/tests/TransposeTest.php @@ -149,4 +149,32 @@ public function it_can_transpose_a_single_row_array() $this->assertEquals($expected, $collection->transpose()); } + + /** @test */ + public function it_can_handle_null_values() + { + $collection = new Collection([ + null, + ]); + + $expected = new Collection(); + + $this->assertEquals($expected, $collection->transpose()); + } + + /** @test */ + public function it_can_handle_collections_values() + { + $collection = new Collection([ + new Collection([1, 2, 3]), + ]); + + $expected = new Collection([ + new Collection([1]), + new Collection([2]), + new Collection([3]), + ]); + + $this->assertEquals($expected, $collection->transpose()); + } }