Skip to content

Commit

Permalink
Improve Statement::when conditionable
Browse files Browse the repository at this point in the history
  • Loading branch information
nyamsprod committed Nov 25, 2024
1 parent bf70531 commit cc7656d
Showing 1 changed file with 12 additions and 11 deletions.
23 changes: 12 additions & 11 deletions src/Statement.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/**
Expand Down

0 comments on commit cc7656d

Please sign in to comment.