Skip to content

Commit

Permalink
Implemented Collection::isEmpty()
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed May 4, 2015
1 parent 029501d commit bac36e0
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/Collection/CollectionInterface.php
Expand Up @@ -830,4 +830,21 @@ public function unfold(callable $transformer = null);
* @return \Cake\Collection\CollectionInterface
*/
public function through(callable $handler);

/**
* Returns whether or not there are elements in this collection
*
* ### Example:
*
* ```
* $items [1, 2, 3];
* (new Collection($items))->isEmpty(); // false
* ```
* ```
* (new Collection([]))->isEmpty(); // true
* ```
*
* @return bool
*/
public function isEmpty();
}
9 changes: 9 additions & 0 deletions src/Collection/CollectionTrait.php
Expand Up @@ -531,6 +531,15 @@ public function through(callable $handler)
return $result instanceof CollectionInterface ? $result: new Collection($result);
}

/**
* {@inheritDoc}
*
*/
public function isEmpty()
{
return iterator_count($this->take(1)) === 0;
}

/**
* Returns the closest nested iterator that can be safely traversed without
* losing any possible transformations.
Expand Down
19 changes: 19 additions & 0 deletions tests/TestCase/Collection/CollectionTest.php
Expand Up @@ -1226,4 +1226,23 @@ public function testDebug()
];
$this->assertSame($expected, $result);
}

/**
* Tests the isEmpty() method
*
* @return void
*/
public function testIsEmpty()
{
$collection = new Collection([1, 2, 3]);
$this->assertFalse($collection->isEmpty());

$collection = $collection->map(function () {
return null;
});
$this->assertFalse($collection->isEmpty());

$collection = $collection->filter();
$this->assertTrue($collection->isEmpty());
}
}

0 comments on commit bac36e0

Please sign in to comment.