Skip to content

Commit

Permalink
Allow collection macros to be proxied
Browse files Browse the repository at this point in the history
  • Loading branch information
JosephSilber committed Dec 11, 2016
1 parent 3f93af4 commit 1e83d65
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 6 deletions.
28 changes: 22 additions & 6 deletions src/Illuminate/Support/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,16 @@ class Collection implements ArrayAccess, Arrayable, Countable, IteratorAggregate
*/
protected $items = [];

/**
* The methods that can be proxied.
*
* @var array
*/
protected static $proxies = [
'each', 'map', 'first', 'partition', 'sortBy',
'sortByDesc', 'sum', 'reject', 'filter',
];

/**
* Create a new collection.
*
Expand All @@ -48,6 +58,17 @@ public static function make($items = [])
return new static($items);
}

/**
* Add a method to the list of proxied methods.
*
* @param string $method
* @return void
*/
public static function proxy($method)
{
static::$proxies[] = $method;
}

/**
* Get all of the items in the collection.
*
Expand Down Expand Up @@ -1388,12 +1409,7 @@ protected function getArrayableItems($items)
*/
public function __get($key)
{
$proxies = [
'each', 'map', 'first', 'partition', 'sortBy',
'sortByDesc', 'sum', 'reject', 'filter',
];

if (! in_array($key, $proxies)) {
if (! in_array($key, static::$proxies)) {
throw new Exception("Property [{$key}] does not exist on this collection instance.");
}

Expand Down
15 changes: 15 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -834,6 +834,21 @@ public function testMacroable()
$this->assertSame(['a', 'aa', 'aaa'], $c->foo()->all());
}

public function testCanAddMethodsToProxy()
{
Collection::macro('adults', function ($callback) {
return $this->filter(function ($item) use ($callback) {
return $callback($item) >= 18;
});
});

Collection::proxy('adults');

$c = new Collection([['age' => 3], ['age' => 12], ['age' => 18], ['age' => 56]]);

$this->assertSame([['age' => 18], ['age' => 56]], $c->adults->age->values()->all());
}

public function testMakeMethod()
{
$collection = Collection::make('foo');
Expand Down

0 comments on commit 1e83d65

Please sign in to comment.