Browse Source

Fixed code for lastN when passing a countable

Jose Lorenzo Rodriguez 7 years ago
parent
commit
479f87e1e0
2 changed files with 25 additions and 4 deletions
  1. 3 1
      src/Collection/CollectionTrait.php
  2. 22 3
      tests/TestCase/Collection/CollectionTest.php

+ 3 - 1
src/Collection/CollectionTrait.php

@@ -415,9 +415,11 @@ trait CollectionTrait
 
         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);

+ 22 - 3
tests/TestCase/Collection/CollectionTest.php

@@ -63,6 +63,24 @@ class TestIterator extends ArrayIterator
     }
 }
 
+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 @@ class CollectionTest extends TestCase
      */
     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);
     }