HigherOrderCollectionProxy.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace Illuminate\Support;
  3. /**
  4. * @template TKey of array-key
  5. *
  6. * @template-covariant TValue
  7. *
  8. * @mixin \Illuminate\Support\Enumerable<TKey, TValue>
  9. * @mixin TValue
  10. */
  11. class HigherOrderCollectionProxy
  12. {
  13. /**
  14. * The collection being operated on.
  15. *
  16. * @var \Illuminate\Support\Enumerable<TKey, TValue>
  17. */
  18. protected $collection;
  19. /**
  20. * The method being proxied.
  21. *
  22. * @var string
  23. */
  24. protected $method;
  25. /**
  26. * Create a new proxy instance.
  27. *
  28. * @param \Illuminate\Support\Enumerable<TKey, TValue> $collection
  29. * @param string $method
  30. */
  31. public function __construct(Enumerable $collection, $method)
  32. {
  33. $this->method = $method;
  34. $this->collection = $collection;
  35. }
  36. /**
  37. * Proxy accessing an attribute onto the collection items.
  38. *
  39. * @param string $key
  40. * @return mixed
  41. */
  42. public function __get($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. * @param string $method
  52. * @param array $parameters
  53. * @return mixed
  54. */
  55. public function __call($method, $parameters)
  56. {
  57. return $this->collection->{$this->method}(function ($value) use ($method, $parameters) {
  58. return is_string($value)
  59. ? $value::{$method}(...$parameters)
  60. : $value->{$method}(...$parameters);
  61. });
  62. }
  63. }