HigherOrderCollectionProxy.php
80 lines
| 1 | <?php |
| 2 | |
| 3 | /** |
| 4 | * Provides property-style access on collection items by delegating to a named collection method such as pluck or map. |
| 5 | * Lets callers write concise syntax like $collection->pluck->name instead of wrapping closures manually. |
| 6 | * Returns the transformed collection result for each accessed key. |
| 7 | * |
| 8 | * @package Framework |
| 9 | * @subpackage Collections |
| 10 | * @since 1.0.0 |
| 11 | */ |
| 12 | namespace Kirki\Framework\Collections; |
| 13 | |
| 14 | \defined('ABSPATH') || exit; |
| 15 | class HigherOrderCollectionProxy |
| 16 | { |
| 17 | /** |
| 18 | * The collection instance. |
| 19 | * |
| 20 | * @var Collection |
| 21 | * |
| 22 | * @since 1.0.0 |
| 23 | */ |
| 24 | protected $collection; |
| 25 | /** |
| 26 | * The method to call on the collection. |
| 27 | * |
| 28 | * @var string |
| 29 | * |
| 30 | * @since 1.0.0 |
| 31 | */ |
| 32 | protected $method; |
| 33 | /** |
| 34 | * Create a new higher order collection proxy instance. |
| 35 | * |
| 36 | * @param Collection $collection The collection instance. |
| 37 | * @param string $method The method to call on the collection. |
| 38 | * |
| 39 | * @return void |
| 40 | * |
| 41 | * @since 1.0.0 |
| 42 | */ |
| 43 | public function __construct(Collection $collection, string $method) |
| 44 | { |
| 45 | $this->collection = $collection; |
| 46 | $this->method = $method; |
| 47 | } |
| 48 | /** |
| 49 | * Get the value of the property. |
| 50 | * |
| 51 | * @param string $key The key of the property. |
| 52 | * |
| 53 | * @return mixed |
| 54 | * |
| 55 | * @since 1.0.0 |
| 56 | */ |
| 57 | public function __get($key) |
| 58 | { |
| 59 | return $this->collection->{$this->method}(function ($value) use($key) { |
| 60 | return \is_array($value) ? $value[$key] : $value->{$key}; |
| 61 | }); |
| 62 | } |
| 63 | /** |
| 64 | * Call the method on the collection. |
| 65 | * |
| 66 | * @param string $method The method to call on the collection. |
| 67 | * @param array $parameters The parameters to pass to the method. |
| 68 | * |
| 69 | * @return mixed |
| 70 | * |
| 71 | * @since 1.0.0 |
| 72 | */ |
| 73 | public function __call($method, $parameters) |
| 74 | { |
| 75 | return $this->collection->{$this->method}(function ($value) use($method, $parameters) { |
| 76 | return \is_string($value) ? $value::$method(...$parameters) : $value->{$method}(...$parameters); |
| 77 | }); |
| 78 | } |
| 79 | } |
| 80 |