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