HigherOrderCollectionProxy.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Collection;
  12. /**
  13. * @template TKey of array-key
  14. * @template TValue
  15. *
  16. * @mixin Enumerable
  17. * @mixin TValue
  18. */
  19. class HigherOrderCollectionProxy
  20. {
  21. /**
  22. * Create a new proxy instance.
  23. * @param Enumerable<TKey, TValue> $collection the collection being operated on
  24. * @param string $method the method being proxied
  25. */
  26. public function __construct(protected Enumerable $collection, protected string $method)
  27. {
  28. }
  29. /**
  30. * Proxy accessing an attribute onto the collection items.
  31. */
  32. public function __get(string $key)
  33. {
  34. return $this->collection->{$this->method}(function ($value) use ($key) {
  35. return is_array($value) ? $value[$key] : $value->{$key};
  36. });
  37. }
  38. /**
  39. * Proxy a method call onto the collection items.
  40. */
  41. public function __call(string $method, array $parameters)
  42. {
  43. return $this->collection->{$this->method}(function ($value) use ($method, $parameters) {
  44. return $value->{$method}(...$parameters);
  45. });
  46. }
  47. }