From 8dd57f96ebfd75889b9fe809e060b24709159204 Mon Sep 17 00:00:00 2001 From: Franz Liedke Date: Fri, 4 Nov 2016 11:00:53 +0100 Subject: [PATCH] Basic implementation of higher-order messages --- src/Illuminate/Support/Collection.php | 52 +++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/src/Illuminate/Support/Collection.php b/src/Illuminate/Support/Collection.php index 990729220663..5b325f944461 100644 --- a/src/Illuminate/Support/Collection.php +++ b/src/Illuminate/Support/Collection.php @@ -1266,6 +1266,25 @@ public function toBase() return new self($this); } + public function __get($name) + { + $nameToMethod = [ + 'where' => 'filter', + 'unless' => 'reject', + 'do' => 'each', + 'extract' => 'map', + 'sum' => 'sum', + 'inOrderOf' => 'sortBy', + 'inReverseOrderOf' => 'sortByDesc', + ]; + + if (isset($nameToMethod[$name])) { + throw new \Exception('Not accessible.'); + } + + return new HigherOrderProxy($this, $nameToMethod[$name]); + } + /** * Determine if an item exists at an offset. * @@ -1350,3 +1369,36 @@ protected function getArrayableItems($items) return (array) $items; } } + +class HigherOrderProxy +{ + /** + * @var Collection + */ + protected $collection; + + /** + * @var string + */ + protected $method; + + public function __construct(Collection $collection, $method) + { + $this->collection = $collection; + $this->method = $method; + } + + public function __call($name, $arguments) + { + return $this->collection->{$this->method}(function($value) use ($name, $arguments) { + return call_user_func_array([$value, $name], $arguments); + }); + } + + public function __get($name) + { + return $this->collection->{$this->method}(function($value) use ($name) { + return $value->$name; + }); + } +}