Skip to content

Commit

Permalink
Fix isEmpty() consuming data.
Browse files Browse the repository at this point in the history
When isEmpty() is used on a buffered iterator, that has not be iterated,
the take(1) call combined with the new Collection's rewind() call would
cause a row to be lost by creating the inner Collection. By not making
a temporary Collection we don't consume data and saving some time as
well.

Refs #7649
  • Loading branch information
markstory committed Nov 9, 2015
1 parent 51c1f2d commit 74452a0
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Collection/CollectionTrait.php
Expand Up @@ -607,7 +607,7 @@ public function zipWith($items, $callable)
*/
public function isEmpty()
{
return iterator_count($this->take(1)) === 0;
return iterator_count($this->unwrap()) === 0;
}

/**
Expand Down
15 changes: 15 additions & 0 deletions tests/TestCase/Collection/CollectionTest.php
Expand Up @@ -1299,6 +1299,21 @@ public function testIsEmpty()
$this->assertTrue($collection->isEmpty());
}

/**
* Tests the isEmpty() method does not consume data
* from buffered iterators.
*
* @return void
*/
public function testIsEmptyDoesNotConsume()
{
$array = new \ArrayIterator([1, 2, 3]);
$inner = new \Cake\Collection\Iterator\BufferedIterator($array);
$collection = new Collection($inner);
$this->assertFalse($collection->isEmpty());
$this->assertCount(3, $collection->toArray());
}

/**
* Tests the zip() method
*
Expand Down
18 changes: 18 additions & 0 deletions tests/TestCase/ORM/ResultSetTest.php
Expand Up @@ -368,4 +368,22 @@ public function testSourceOnContainAssociations()
$this->assertEquals('TestPlugin.Comments', $result->source());
$this->assertEquals('TestPlugin.Authors', $result->_matchingData['Authors']->source());
}

/**
* Ensure that isEmpty() on a ResultSet doesn't result in loss
* of records. This behavior is provided by CollectionTrait.
*
* @return void
*/
public function testIsEmptyDoesNotConsumeData()
{
$table = TableRegistry::get('Comments');
$query = $table->find()
->formatResults(function ($results) {
return $results;
});
$res = $query->all();
$res->isEmpty();
$this->assertCount(6, $res->toArray());
}
}

0 comments on commit 74452a0

Please sign in to comment.