|
| 1 | +<?php |
| 2 | +namespace ScriptFUSION\Mapper\Strategy; |
| 3 | + |
| 4 | +use ScriptFUSION\Mapper\InvalidConditionException; |
| 5 | +use ScriptFUSION\Mapper\Mapping; |
| 6 | + |
| 7 | +/** |
| 8 | + * Delegates to one expression or another depending on whether the specified condition strictly evaluates to true. |
| 9 | + */ |
| 10 | +class IfElse extends Delegate |
| 11 | +{ |
| 12 | + /** @var callable */ |
| 13 | + private $condition; |
| 14 | + |
| 15 | + /** @var Strategy|Mapping|array|mixed */ |
| 16 | + private $else; |
| 17 | + |
| 18 | + /** |
| 19 | + * Initializes this instance with the specified condition, the specified |
| 20 | + * expression to be resolved when condition is true and, optionally, the |
| 21 | + * specified expression to be resolved when condition is false. |
| 22 | + * |
| 23 | + * @param callable $condition Condition. |
| 24 | + * @param Strategy|Mapping|array|mixed $if Primary expression. |
| 25 | + * @param Strategy|Mapping|array|mixed|null $else Optional. Fallback expression. |
| 26 | + */ |
| 27 | + public function __construct(callable $condition, $if, $else = null) |
| 28 | + { |
| 29 | + parent::__construct($if); |
| 30 | + |
| 31 | + $this->condition = $condition; |
| 32 | + $this->else = $else; |
| 33 | + } |
| 34 | + |
| 35 | + /** |
| 36 | + * Resolves the stored expression when the stored condition strictly |
| 37 | + * evaluates to true, otherwise resolve the stored fallback expression. |
| 38 | + * |
| 39 | + * @param mixed $data |
| 40 | + * @param mixed $context |
| 41 | + * |
| 42 | + * @throws InvalidConditionException |
| 43 | + * |
| 44 | + * @return mixed |
| 45 | + */ |
| 46 | + public function __invoke($data, $context = null) |
| 47 | + { |
| 48 | + $result = call_user_func($this->condition, $data, $context); |
| 49 | + |
| 50 | + if (!is_bool($result)) { |
| 51 | + throw new InvalidConditionException('Invalid return from condition: must be of type boolean.'); |
| 52 | + } |
| 53 | + |
| 54 | + if ($result === true) { |
| 55 | + return parent::__invoke($data, $context); |
| 56 | + } |
| 57 | + |
| 58 | + return $this->delegate($this->else, $data, $context); |
| 59 | + } |
| 60 | +} |
0 commit comments