diff --git a/lib/Doctrine/ORM/LazyCriteriaCollection.php b/lib/Doctrine/ORM/LazyCriteriaCollection.php index 28e2709ac..0751bee41 100644 --- a/lib/Doctrine/ORM/LazyCriteriaCollection.php +++ b/lib/Doctrine/ORM/LazyCriteriaCollection.php @@ -82,6 +82,20 @@ class LazyCriteriaCollection extends AbstractLazyCollection implements Selectabl return $this->count = $this->entityPersister->count($this->criteria); } + /** + * check if collection is empty without loading it + * + * @return boolean TRUE if the collection is empty, FALSE otherwise. + */ + public function isEmpty() + { + if ($this->isInitialized()) { + return $this->collection->isEmpty(); + } + + return !$this->count(); + } + /** * Do an optimized search of an element * diff --git a/tests/Doctrine/Tests/ORM/LazyCriteriaCollectionTest.php b/tests/Doctrine/Tests/ORM/LazyCriteriaCollectionTest.php index 2f228f98b..92da34cda 100644 --- a/tests/Doctrine/Tests/ORM/LazyCriteriaCollectionTest.php +++ b/tests/Doctrine/Tests/ORM/LazyCriteriaCollectionTest.php @@ -103,4 +103,35 @@ class LazyCriteriaCollectionTest extends PHPUnit_Framework_TestCase $this->assertEquals(array($foo), $this->lazyCriteriaCollection->matching($criteria)->toArray()); } + + public function testIsEmptyUsesCountWhenNotInitialized() + { + $this->persister->expects($this->once())->method('count')->with($this->criteria)->will($this->returnValue(0)); + + $this->assertTrue($this->lazyCriteriaCollection->isEmpty()); + } + + public function testIsEmptyIsFalseIfCountIsNotZero() + { + $this->persister->expects($this->once())->method('count')->with($this->criteria)->will($this->returnValue(1)); + + $this->assertFalse($this->lazyCriteriaCollection->isEmpty()); + } + + public function testIsEmptyUsesWrappedCollectionWhenInitialized() + { + $this + ->persister + ->expects($this->once()) + ->method('loadCriteria') + ->with($this->criteria) + ->will($this->returnValue(array('foo', 'bar', 'baz'))); + + // should never call the persister's count + $this->persister->expects($this->never())->method('count'); + + $this->assertSame(array('foo', 'bar', 'baz'), $this->lazyCriteriaCollection->toArray()); + + $this->assertFalse($this->lazyCriteriaCollection->isEmpty()); + } }