HigherOrderWhenProxy.php 2.4 KB

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