Skip to content

Commit

Permalink
refactor: expectation match method
Browse files Browse the repository at this point in the history
  • Loading branch information
nunomaduro committed Sep 24, 2021
1 parent ae02966 commit 4579727
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 17 deletions.
23 changes: 12 additions & 11 deletions src/Expectation.php
Original file line number Diff line number Diff line change
Expand Up @@ -178,14 +178,12 @@ public function sequence(...$callbacks): Expectation
}

/**
* If the subject matches one of the expressions, the callback in the expression is run.
* If the subject matches one of the given "expressions", the expression callback will run.
*
* @template TMatchValue
* @template TMatchSubject of array-key
*
* @param Closure|bool|string $subject
* @param array<mixed, callable(self): void|TMatchValue> $expressions
*
* @return \Pest\Expectation
* @param callable(): TMatchSubject|TMatchSubject $subject
* @param array<TMatchSubject, (callable(Expectation<TValue>): mixed)|TValue> $expressions
*/
public function match($subject, array $expressions): Expectation
{
Expand All @@ -196,17 +194,16 @@ public function match($subject, array $expressions): Expectation
};

$subject = $subject();
$keys = array_keys($expressions);

if (in_array($subject, ['0', '1', false, true], true)) {
$subject = (int) $subject;
}
$matched = false;

foreach ($expressions as $key => $callback) {
if ($subject !== $key) {
if ($subject != $key) {
continue;
}

$matched = true;

if (is_callable($callback)) {
$callback(new self($this->value));
continue;
Expand All @@ -217,6 +214,10 @@ public function match($subject, array $expressions): Expectation
break;
}

if ($matched === false) {
throw new ExpectationFailedException('Unhandled match value.');
}

return $this;
}

Expand Down
2 changes: 1 addition & 1 deletion tests/.snapshots/success.txt
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@
✓ it runs with truthy closure condition
✓ it runs with falsy closure condition
✓ it can be passed non-callable values
✓ it passes with empty data
✓ it fails with unhandled match
✓ it can be used in higher order tests

PASS Tests\Features\Expect\not
Expand Down
8 changes: 3 additions & 5 deletions tests/Features/Expect/matchExpectation.php
Original file line number Diff line number Diff line change
Expand Up @@ -130,11 +130,9 @@ function () { return '0'; }, [
);
})->throws(ExpectationFailedException::class, 'two strings are equal');

it('passes with empty data', function () {
expect('foo')
->match('bar', [])
->toEqual('foo');
});
it('fails with unhandled match', function () {
expect('foo')->match('bar', []);
})->throws(ExpectationFailedException::class, 'Unhandled match value.');

it('can be used in higher order tests')
->expect(true)
Expand Down

0 comments on commit 4579727

Please sign in to comment.