From 543b9542ae56e4e2a0661561cc02e3f651519a83 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mert=20A=C5=9Fan?= Date: Thu, 23 Sep 2021 06:55:28 +0300 Subject: [PATCH] add new `match()` method --- src/Expectation.php | 50 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/src/Expectation.php b/src/Expectation.php index 253b1e1e..1d8403ac 100644 --- a/src/Expectation.php +++ b/src/Expectation.php @@ -177,6 +177,56 @@ final class Expectation return $this; } + /** + * If the subject matches one of the expressions, the callback in the expression is run. + * + * @template TMatchValue + * + * @param Closure|bool|string $subject + * @param array $expressions + * + * @return \Pest\Expectation + */ + public function match($subject, array $expressions): Expectation + { + $subject = is_callable($subject) + ? $subject + : function () use ($subject) { + return $subject; + }; + + $subject = $subject(); + $keys = array_keys($expressions); + $matched = false; + + if (in_array($subject, ['0', '1', false, true], true)) { + $subject = (int) $subject; + } + + foreach ($expressions as $key => $callback) { + if ($subject !== $key) { + continue; + } + + $matched = true; + + if (is_callable($callback)) { + $callback(new self($this->value)); + continue; + } + + (new self($this->value))->toEqual($callback); + + break; + } + + if (!$matched) { + test()->addWarning('No item found matching "' . $subject . '".'); + } + + return $this; + } + /** * Asserts that two variables have the same type and * value. Used on objects, it asserts that two