HigherOrderWhenProxy.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. <?php
  2. namespace Illuminate\Support;
  3. class HigherOrderWhenProxy
  4. {
  5. /**
  6. * The target being conditionally operated on.
  7. *
  8. * @var mixed
  9. */
  10. protected $target;
  11. /**
  12. * The condition for proxying.
  13. *
  14. * @var bool
  15. */
  16. protected $condition;
  17. /**
  18. * Indicates whether the proxy has a condition.
  19. *
  20. * @var bool
  21. */
  22. protected $hasCondition = false;
  23. /**
  24. * Determine whether the condition should be negated.
  25. *
  26. * @var bool
  27. */
  28. protected $negateConditionOnCapture;
  29. /**
  30. * Create a new proxy instance.
  31. *
  32. * @param mixed $target
  33. * @return void
  34. */
  35. public function __construct($target)
  36. {
  37. $this->target = $target;
  38. }
  39. /**
  40. * Set the condition on the proxy.
  41. *
  42. * @param bool $condition
  43. * @return $this
  44. */
  45. public function condition($condition)
  46. {
  47. [$this->condition, $this->hasCondition] = [$condition, true];
  48. return $this;
  49. }
  50. /**
  51. * Indicate that the condition should be negated.
  52. *
  53. * @return $this
  54. */
  55. public function negateConditionOnCapture()
  56. {
  57. $this->negateConditionOnCapture = true;
  58. return $this;
  59. }
  60. /**
  61. * Proxy accessing an attribute onto the target.
  62. *
  63. * @param string $key
  64. * @return mixed
  65. */
  66. public function __get($key)
  67. {
  68. if (! $this->hasCondition) {
  69. $condition = $this->target->{$key};
  70. return $this->condition($this->negateConditionOnCapture ? ! $condition : $condition);
  71. }
  72. return $this->condition
  73. ? $this->target->{$key}
  74. : $this->target;
  75. }
  76. /**
  77. * Proxy a method call on the target.
  78. *
  79. * @param string $method
  80. * @param array $parameters
  81. * @return mixed
  82. */
  83. public function __call($method, $parameters)
  84. {
  85. if (! $this->hasCondition) {
  86. $condition = $this->target->{$method}(...$parameters);
  87. return $this->condition($this->negateConditionOnCapture ? ! $condition : $condition);
  88. }
  89. return $this->condition
  90. ? $this->target->{$method}(...$parameters)
  91. : $this->target;
  92. }
  93. }