diff --git a/src/Illuminate/Support/Collection.php b/src/Illuminate/Support/Collection.php index 09367c754463..646753bbbfb4 100644 --- a/src/Illuminate/Support/Collection.php +++ b/src/Illuminate/Support/Collection.php @@ -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. * @@ -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. * @@ -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."); } diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index 654f1c0e1dd4..0b81195171aa 100755 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -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');