HigherOrderCollectionProxy.php 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. * @mixin Collection
  14. * @mixin Enumerable
  15. */
  16. class HigherOrderCollectionProxy
  17. {
  18. /**
  19. * Create a new proxy instance.
  20. * @param Collection $collection the collection being operated on
  21. * @param string $method the method being proxied
  22. */
  23. public function __construct(protected Collection $collection, protected string $method)
  24. {
  25. }
  26. /**
  27. * Proxy accessing an attribute onto the collection items.
  28. */
  29. public function __get(string $key)
  30. {
  31. return $this->collection->{$this->method}(function ($value) use ($key) {
  32. return is_array($value) ? $value[$key] : $value->{$key};
  33. });
  34. }
  35. /**
  36. * Proxy a method call onto the collection items.
  37. */
  38. public function __call(string $method, array $parameters)
  39. {
  40. return $this->collection->{$this->method}(function ($value) use ($method, $parameters) {
  41. return $value->{$method}(...$parameters);
  42. });
  43. }
  44. }