HigherOrderCollectionProxy.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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\Utils;
  12. /**
  13. * @mixin Collection
  14. * Most of the methods in this file come from illuminate/support,
  15. * thanks Laravel Team provide such a useful class.
  16. */
  17. class HigherOrderCollectionProxy
  18. {
  19. /**
  20. * The collection being operated on.
  21. *
  22. * @var Collection
  23. */
  24. protected $collection;
  25. /**
  26. * The method being proxied.
  27. *
  28. * @var string
  29. */
  30. protected $method;
  31. /**
  32. * Create a new proxy instance.
  33. */
  34. public function __construct(Collection $collection, string $method)
  35. {
  36. $this->method = $method;
  37. $this->collection = $collection;
  38. }
  39. /**
  40. * Proxy accessing an attribute onto the collection items.
  41. */
  42. public function __get(string $key)
  43. {
  44. return $this->collection->{$this->method}(function ($value) use ($key) {
  45. return is_array($value) ? $value[$key] : $value->{$key};
  46. });
  47. }
  48. /**
  49. * Proxy a method call onto the collection items.
  50. */
  51. public function __call(string $method, array $parameters)
  52. {
  53. return $this->collection->{$this->method}(function ($value) use ($method, $parameters) {
  54. return $value->{$method}(...$parameters);
  55. });
  56. }
  57. }