Jose Lorenzo Rodriguez 10 years ago
parent
commit
8540633534

+ 5 - 0
src/Collection/CollectionTrait.php

@@ -330,6 +330,11 @@ trait CollectionTrait
         $count = $iterator instanceof Countable ?
             count($iterator) :
             iterator_count($iterator);
+
+        if ($count === 0) {
+            return null;
+        }
+
         foreach ($this->take(1, $count - 1) as $last) {
             return $last;
         }

+ 11 - 0
tests/TestCase/Collection/CollectionTest.php

@@ -1356,4 +1356,15 @@ class CollectionTest extends TestCase
         });
         $this->assertEquals(6, $collection->last());
     }
+
+    /**
+     * Tests the last() method when on an empty collection
+     *
+     * @return void
+     */
+    public function testLAstWithEmptyCollection()
+    {
+        $collection = new Collection([]);
+        $this->assertNull($collection->last());
+    }
 }

+ 14 - 0
tests/TestCase/ORM/QueryRegressionTest.php

@@ -864,4 +864,18 @@ class QueryRegressionTest extends TestCase
             ->ratio;
         $this->assertEquals(0.5, $ratio);
     }
+
+    /**
+     * Tests calling last on an empty table
+     *
+     * @see https://github.com/cakephp/cakephp/issues/6683
+     * @return void
+     */
+    public function testFindLastOnEmptyTable()
+    {
+        $table = TableRegistry::get('Comments');
+        $table->deleteAll(['1 = 1']);
+        $this->assertEquals(0, $table->find()->count());
+        $this->assertNull($table->find()->last());
+    }
 }