From cc7656d288d44a46b063b0e963767aa74cf01b79 Mon Sep 17 00:00:00 2001 From: ignace nyamagana butera Date: Mon, 25 Nov 2024 07:43:32 +0100 Subject: [PATCH] Improve Statement::when conditionable --- src/Statement.php | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/src/Statement.php b/src/Statement.php index 0171d1bc..b9823995 100644 --- a/src/Statement.php +++ b/src/Statement.php @@ -293,22 +293,23 @@ public function limit(int $limit): self } /** - * @template TWhenParameter + * Apply the callback if the given "condition" is (or resolves to) true. * - * @param (Closure($this): TWhenParameter)|TWhenParameter $value - * @param callable($this, TWhenParameter): ($this|null) $callback + * @param (callable($this): bool)|bool $condition + * @param callable($this): ($this|null) $callback + * @param ?callable($this): ($this|null) $default */ - public function when($value, callable $callback): self + public function when(callable|bool $condition, callable $callback, ?callable $default = null): self { - if ($value instanceof Closure) { - $value = $value($this); + if (!is_bool($condition)) { + $condition = $condition($this); } - if (!$value) { - return $this; - } - - return $callback($this, $value) ?? $this; + return match (true) { + $condition => $callback($this), + null !== $default => $default($this), + default => $this, + } ?? $this; } /**