Skip to content

Commit

Permalink
Fixed code for lastN when passing a countable
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Sep 4, 2018
1 parent f2525fc commit 479f87e
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
4 changes: 3 additions & 1 deletion src/Collection/CollectionTrait.php
Expand Up @@ -415,9 +415,11 @@ public function lastN($howMany)

if ($iterator instanceof Countable) {
$count = count($iterator);

if ($count === 0) {
return null;
return new Collection([]);
}

$iterator = new LimitIterator($iterator, max(0, $count - $howMany), $howMany);

return new Collection($iterator);
Expand Down
25 changes: 22 additions & 3 deletions tests/TestCase/Collection/CollectionTest.php
Expand Up @@ -63,6 +63,24 @@ public function checkValues()
}
}

class CountableIterator extends \IteratorIterator implements \Countable
{
public function __construct($items)
{
$f = function () use ($items) {
foreach ($items as $e) {
yield $e;
}
};
parent::__construct($f());
}

public function count()
{
return 6;
}
}

/**
* CollectionTest
*/
Expand Down Expand Up @@ -2199,11 +2217,12 @@ public function testLasNtWithOddData($data)
*/
public function testLasNtWithCountable()
{
$collection = new Collection(new ArrayObject([1, 2, 3, 4, 5]));
$result = $collection->lastN(2)->toArray();
$collection = new Collection(new CountableIterator(range(0, 5)));
$result = $collection->lastN(2)->toList();
$this->assertEquals([4, 5], $result);

$result = $collection->lastN(1)->toArray();
$collection = new Collection(new CountableIterator(range(0, 5)));
$result = $collection->lastN(1)->toList();
$this->assertEquals([5], $result);
}

Expand Down

0 comments on commit 479f87e

Please sign in to comment.