forked from brainbits/functional-test-helpers
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueryParamMatcher.php
More file actions
74 lines (59 loc) · 1.91 KB
/
QueryParamMatcher.php
File metadata and controls
74 lines (59 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php
declare(strict_types=1);
namespace Brainbits\FunctionalTestHelpers\HttpClientMock\Matcher;
use Brainbits\FunctionalTestHelpers\HttpClientMock\RealRequest;
use function in_array;
use function is_array;
use function Safe\json_encode;
use function sprintf;
use function str_ends_with;
use function substr;
use function vsprintf;
final readonly class QueryParamMatcher implements Matcher
{
private string $key;
/** @var string|mixed[] */
private string|array $value;
private bool $isArray;
/**
* @param string|mixed[] $value
* @param array<string> $placeholders
*/
public function __construct(string $key, string|array $value, array $placeholders)
{
$isArray = false;
if (str_ends_with($key, '[]')) {
$key = substr($key, 0, -2);
$isArray = true;
}
if (!is_array($value)) {
$value = vsprintf($value, $placeholders);
}
$this->key = $key;
$this->value = $value;
$this->isArray = $isArray;
}
public function __invoke(RealRequest $realRequest): Hit|Mismatch|Missing
{
if (!$realRequest->hasQueryParam($this->key)) {
return Missing::missingQueryParam($this->key, $this->value);
}
$expectedValue = $this->value;
$realValue = $realRequest->getQueryParam($this->key);
if (
(!$this->isArray && $expectedValue !== $realValue) ||
($this->isArray && !in_array($expectedValue, $realValue, true))
) {
return Mismatch::mismatchingQueryParam($this->key, $expectedValue, $realValue);
}
return Hit::matchesQueryParam($this->key, $realValue);
}
public function __toString(): string
{
return sprintf(
'request.queryParams["%s"] === "%s"',
$this->key,
is_array($this->value) ? json_encode($this->value) : $this->value,
);
}
}