Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.4] Allow collection macros to be proxied #16749

Merged
merged 1 commit into from
Dec 11, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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