Skip to content

Commit

Permalink
Implemented Collection::every()
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Dec 25, 2013
1 parent 4a2d24f commit ca35f15
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 2 deletions.
46 changes: 46 additions & 0 deletions Cake/Test/TestCase/Utility/CollectionTest.php
Expand Up @@ -97,4 +97,50 @@ public function testReject() {
$this->assertEquals(['a' => 1, 'b' => 2], iterator_to_array($result));
$this->assertInstanceOf('\Cake\Utility\Collection', $result);
}

/**
* Tests every when the callback returns true for all elements
*
* @return void
*/
public function testEveryReturnTrue() {
$items = ['a' => 1, 'b' => 2, 'c' => 3];
$collection = new Collection($items);
$callable = $this->getMock('stdClass', ['__invoke']);
$callable->expects($this->at(0))
->method('__invoke')
->with(1, 'a')
->will($this->returnValue(true));
$callable->expects($this->at(1))
->method('__invoke')
->with(2, 'b')
->will($this->returnValue(true));
$callable->expects($this->at(2))
->method('__invoke')
->with(3, 'c')
->will($this->returnValue(true));
$this->assertTrue($collection->every($callable));
}

/**
* Tests every when the callback returns false for one of the elements
*
* @return void
*/
public function testEveryReturnFalse() {
$items = ['a' => 1, 'b' => 2, 'c' => 3];
$collection = new Collection($items);
$callable = $this->getMock('stdClass', ['__invoke']);
$callable->expects($this->at(0))
->method('__invoke')
->with(1, 'a')
->will($this->returnValue(true));
$callable->expects($this->at(1))
->method('__invoke')
->with(2, 'b')
->will($this->returnValue(false));
$callable->expects($this->exactly(2))->method('__invoke');
$this->assertFalse($collection->every($callable));
}

}
30 changes: 28 additions & 2 deletions Cake/Utility/Collection.php
Expand Up @@ -117,10 +117,36 @@ public function reject(callable $c) {
});
}

public function some(callable $c) {
/**
* Returns true if all values in this collection pass the truth test provided
* in the callback.
*
* Each time the callback is executed it will receive the value of the element
* in the current iteration and the key of the element as arguments, in that
* order.
*
* ###Example:
*
* {{{
* $legalAge = (new Collection([24, 45, 60, 15]))->every(function($value, $key) {
* return $value > 21;
* });
* }}}
*
* @param callable $c a callback function
* @return boolean true if for all elements in this collection the provided
* callback returns true, false otherwise
*/
public function every(callable $c) {
foreach ($this as $key => $value) {
if (!$c($value, $key)) {
return false;
}
}
return true;
}

public function every(callable $c) {
public function some(callable $c) {
}

public function contains(callable $c) {
Expand Down

0 comments on commit ca35f15

Please sign in to comment.