From 479f87e1e008cbf8fcd23cef2eacab2754561ced Mon Sep 17 00:00:00 2001 From: Jose Lorenzo Rodriguez Date: Tue, 4 Sep 2018 10:53:47 +0200 Subject: [PATCH] Fixed code for lastN when passing a countable --- src/Collection/CollectionTrait.php | 4 +++- tests/TestCase/Collection/CollectionTest.php | 25 +++++++++++++++++--- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/src/Collection/CollectionTrait.php b/src/Collection/CollectionTrait.php index e33ddf4ec94..76e10189f42 100644 --- a/src/Collection/CollectionTrait.php +++ b/src/Collection/CollectionTrait.php @@ -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); diff --git a/tests/TestCase/Collection/CollectionTest.php b/tests/TestCase/Collection/CollectionTest.php index ff58eab4c9b..27b2ef20bfe 100644 --- a/tests/TestCase/Collection/CollectionTest.php +++ b/tests/TestCase/Collection/CollectionTest.php @@ -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 */ @@ -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); }