Conditionable.php
61 lines
| 1 | <?php |
| 2 | |
| 3 | /** |
| 4 | * Trait adding when and unless conditional execution to any class. |
| 5 | * Runs a callback when a truthy condition is met and supports default fallbacks. |
| 6 | * Enables fluent conditional chains on builders and models. |
| 7 | * |
| 8 | * @package Framework |
| 9 | * @subpackage Supports\Traits |
| 10 | * @since 1.0.0 |
| 11 | */ |
| 12 | namespace Kirki\Framework\Supports\Traits; |
| 13 | |
| 14 | \defined('ABSPATH') || exit; |
| 15 | use Closure; |
| 16 | trait Conditionable |
| 17 | { |
| 18 | /** |
| 19 | * Execute the callback when the value is true |
| 20 | * |
| 21 | * @param mixed $value The value to check |
| 22 | * @param callable $callback The callback to execute if the value is true |
| 23 | * @param mixed $default The default value to return if the value is true |
| 24 | * |
| 25 | * @return mixed The result of the callback or the default value |
| 26 | * |
| 27 | * @since 1.0.0 |
| 28 | */ |
| 29 | public function when($value, callable $callback, $default = null) |
| 30 | { |
| 31 | $value = $value instanceof Closure ? $value($this) : $value; |
| 32 | if ($value) { |
| 33 | return $callback($this, $value); |
| 34 | } elseif ($default) { |
| 35 | return $default instanceof Closure ? $default($this, $value) : $default; |
| 36 | } |
| 37 | return $this; |
| 38 | } |
| 39 | /** |
| 40 | * Execute the callback unless the value is true |
| 41 | * |
| 42 | * @param mixed $value The value to check |
| 43 | * @param callable $callback The callback to execute if the value is false |
| 44 | * @param mixed $default The default value to return if the value is false |
| 45 | * |
| 46 | * @return mixed The result of the callback or the default value |
| 47 | * |
| 48 | * @since 1.0.0 |
| 49 | */ |
| 50 | public function unless($value, callable $callback, $default = null) |
| 51 | { |
| 52 | $value = $value instanceof Closure ? $value($this) : $value; |
| 53 | if (!$value) { |
| 54 | return $callback($this, $value); |
| 55 | } elseif ($default) { |
| 56 | return $default instanceof Closure ? $default($this, $value) : $default; |
| 57 | } |
| 58 | return $this; |
| 59 | } |
| 60 | } |
| 61 |