Matthias Andreas Benkard | 7b2a3a1 | 2021-08-16 10:57:25 +0200 | [diff] [blame^] | 1 | <?php |
| 2 | |
| 3 | namespace Tightenco\Collect\Support; |
| 4 | |
| 5 | /** |
| 6 | * @mixin \Tightenco\Collect\Support\Enumerable |
| 7 | */ |
| 8 | class HigherOrderCollectionProxy |
| 9 | { |
| 10 | /** |
| 11 | * The collection being operated on. |
| 12 | * |
| 13 | * @var \Tightenco\Collect\Support\Enumerable |
| 14 | */ |
| 15 | protected $collection; |
| 16 | |
| 17 | /** |
| 18 | * The method being proxied. |
| 19 | * |
| 20 | * @var string |
| 21 | */ |
| 22 | protected $method; |
| 23 | |
| 24 | /** |
| 25 | * Create a new proxy instance. |
| 26 | * |
| 27 | * @param \Tightenco\Collect\Support\Enumerable $collection |
| 28 | * @param string $method |
| 29 | * @return void |
| 30 | */ |
| 31 | public function __construct(Enumerable $collection, $method) |
| 32 | { |
| 33 | $this->method = $method; |
| 34 | $this->collection = $collection; |
| 35 | } |
| 36 | |
| 37 | /** |
| 38 | * Proxy accessing an attribute onto the collection items. |
| 39 | * |
| 40 | * @param string $key |
| 41 | * @return mixed |
| 42 | */ |
| 43 | public function __get($key) |
| 44 | { |
| 45 | return $this->collection->{$this->method}(function ($value) use ($key) { |
| 46 | return is_array($value) ? $value[$key] : $value->{$key}; |
| 47 | }); |
| 48 | } |
| 49 | |
| 50 | /** |
| 51 | * Proxy a method call onto the collection items. |
| 52 | * |
| 53 | * @param string $method |
| 54 | * @param array $parameters |
| 55 | * @return mixed |
| 56 | */ |
| 57 | public function __call($method, $parameters) |
| 58 | { |
| 59 | return $this->collection->{$this->method}(function ($value) use ($method, $parameters) { |
| 60 | return $value->{$method}(...$parameters); |
| 61 | }); |
| 62 | } |
| 63 | } |