HigherOrderWhenProxy.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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. */
  34. public function __construct($target)
  35. {
  36. $this->target = $target;
  37. }
  38. /**
  39. * Set the condition on the proxy.
  40. *
  41. * @param bool $condition
  42. * @return $this
  43. */
  44. public function condition($condition)
  45. {
  46. [$this->condition, $this->hasCondition] = [$condition, true];
  47. return $this;
  48. }
  49. /**
  50. * Indicate that the condition should be negated.
  51. *
  52. * @return $this
  53. */
  54. public function negateConditionOnCapture()
  55. {
  56. $this->negateConditionOnCapture = true;
  57. return $this;
  58. }
  59. /**
  60. * Proxy accessing an attribute onto the target.
  61. *
  62. * @param string $key
  63. * @return mixed
  64. */
  65. public function __get($key)
  66. {
  67. if (! $this->hasCondition) {
  68. $condition = $this->target->{$key};
  69. return $this->condition($this->negateConditionOnCapture ? ! $condition : $condition);
  70. }
  71. return $this->condition
  72. ? $this->target->{$key}
  73. : $this->target;
  74. }
  75. /**
  76. * Proxy a method call on the target.
  77. *
  78. * @param string $method
  79. * @param array $parameters
  80. * @return mixed
  81. */
  82. public function __call($method, $parameters)
  83. {
  84. if (! $this->hasCondition) {
  85. $condition = $this->target->{$method}(...$parameters);
  86. return $this->condition($this->negateConditionOnCapture ? ! $condition : $condition);
  87. }
  88. return $this->condition
  89. ? $this->target->{$method}(...$parameters)
  90. : $this->target;
  91. }
  92. }