Skip to content

Commit

Permalink
chain() supports both static and OO-style calls
Browse files Browse the repository at this point in the history
  • Loading branch information
brianhaveri committed Jan 7, 2012
1 parent baae976 commit 49e0161
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 11 deletions.
22 changes: 14 additions & 8 deletions test/ChainingTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,21 @@ public function testMapFlattenReduce() {
}

public function testSelectRejectSortBy() {
// from js
$numbers = array(1,2,3,4,5,6,7,8,9,10);
$numbers = __($numbers)->chain()
->select(function($n) { return $n % 2 === 0; })
->reject(function($n) { return $n % 4 === 0; })
->sortBy(function($n) { return -$n; })
->value();
$this->assertEquals(array(10, 6, 2), $numbers, 'filtered and reversed the numbers in OO-style call');

$numbers = array(1,2,3,4,5,6,7,8,9,10);
$numbers = __($numbers)->chain()->select(function($n) {
return $n % 2 === 0;
})->reject(function($n) {
return $n % 4 === 0;
})->sortBy(function($n) {
return -$n;
})->value();
$this->assertEquals(array(10, 6, 2), $numbers, 'filtered and reversed the numbers');
$numbers = __::chain($numbers)->select(function($n) { return $n % 2 === 0; })
->reject(function($n) { return $n % 4 === 0; })
->sortBy(function($n) { return -$n; })
->value();
$this->assertEquals(array(10, 6, 2), $numbers, 'filtered and reversed the numbers in static call');
}

public function testChain() {
Expand Down
9 changes: 6 additions & 3 deletions underscore.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,12 @@ class __ {

// Start the chain
private $_chained = false; // Are we in a chain?
public function chain() {
$this->_chained = true;
return $this;
public function chain($item=null) {
list($item) = self::_wrapArgs(func_get_args(), 1);

$__ = (isset($this) && isset($this->_chained) && $this->_chained) ? $this : __($item);
$__->_chained = true;
return $__;
}


Expand Down

0 comments on commit 49e0161

Please sign in to comment.