diff --git a/composer.json b/composer.json
index 1e00fb475..3299e7b90 100644
--- a/composer.json
+++ b/composer.json
@@ -78,6 +78,7 @@
"composer run-example:generators",
"composer run-example:json",
"composer run-example:matchers",
+ "composer run-example:or-matcher",
"composer run-example:message",
"composer run-example:multipart",
"composer run-example:protobuf-async-message",
@@ -94,6 +95,7 @@
"composer run-example:generators:windows",
"composer run-example:json:windows",
"composer run-example:matchers:windows",
+ "composer run-example:or-matcher:windows",
"composer run-example:message:windows",
"composer run-example:multipart:windows",
"composer run-example:protobuf-async-message:windows",
@@ -129,6 +131,11 @@
"cd example/matchers/consumer && phpunit --process-isolation",
"cd example/matchers/provider && phpunit --process-isolation"
],
+ "run-example:or-matcher:windows": [
+ "powershell -Command \"if (Test-Path 'example/or-matcher/pacts/orMatcherConsumer-orMatcherProvider.json') { Remove-Item 'example/or-matcher/pacts/orMatcherConsumer-orMatcherProvider.json' }\"",
+ "cd example/or-matcher/consumer && phpunit --process-isolation",
+ "cd example/or-matcher/provider && phpunit --process-isolation"
+ ],
"run-example:message:windows": [
"powershell -Command \"if (Test-Path 'example/message/pacts/messageConsumer-messageProvider.json') { Remove-Item 'example/message/pacts/messageConsumer-messageProvider.json' }\"",
"cd example/message/consumer && phpunit --process-isolation",
@@ -192,6 +199,11 @@
"cd example/matchers/consumer && phpunit",
"cd example/matchers/provider && phpunit"
],
+ "run-example:or-matcher": [
+ "rm -f example/or-matcher/pacts/orMatcherConsumer-orMatcherProvider.json",
+ "cd example/or-matcher/consumer && phpunit",
+ "cd example/or-matcher/provider && phpunit"
+ ],
"run-example:message": [
"rm -f example/message/pacts/messageConsumer-messageProvider.json",
"cd example/message/consumer && phpunit",
@@ -244,12 +256,12 @@
"extra": {
"downloads": {
"pact-ffi-headers": {
- "version": "0.5.10",
- "url": "https://github.com/pact-foundation/pact-reference/releases/download/libpact_ffi-v{$version}/pact.h",
+ "version": "0.5.13-or.1",
+ "url": "https://github.com/YOU54F/pact-reference/releases/download/libpact_ffi-v{$version}/pact.h",
"path": "bin/pact-ffi-headers/pact.h"
},
"pact-ffi-lib": {
- "version": "0.5.10",
+ "version": "0.5.13-or.1",
"variables": {
"{$prefix}": "PHP_OS_FAMILY === 'Windows' ? 'pact_ffi' : 'libpact_ffi'",
"{$os}": "PHP_OS === 'Darwin' ? 'macos' : strtolower(PHP_OS_FAMILY)",
@@ -257,7 +269,7 @@
"{$musl}": "PHP_OS === 'Linux' && musl() === true ? '-musl' : ''",
"{$extension}": "PHP_OS_FAMILY === 'Windows' ? 'dll' : (PHP_OS === 'Darwin' ? 'dylib' : 'so')"
},
- "url": "https://github.com/pact-foundation/pact-reference/releases/download/libpact_ffi-v{$version}/{$prefix}-{$os}-{$architecture}{$musl}.{$extension}.gz",
+ "url": "https://github.com/YOU54F/pact-reference/releases/download/libpact_ffi-v{$version}/{$prefix}-{$os}-{$architecture}{$musl}.{$extension}.gz",
"path": "bin/pact-ffi-lib/pact.{$extension}"
},
"pact-stub-server": {
diff --git a/docs/consumer.md b/docs/consumer.md
index 164ca0ad4..7f0e291dd 100644
--- a/docs/consumer.md
+++ b/docs/consumer.md
@@ -76,6 +76,78 @@ uuid | Regex to match a uuid. | Value (Defaults to ce118b6e-d8e1-11e7-9296-cec27
ipv4Address | Regex to match a ipv4 address. | Value (Defaults to 127.0.0.13) | $matcher->ipv4Address('127.0.0.1')
ipv6Address | Regex to match a ipv6 address. | Value (Defaults to ::ffff:192.0.2.128) | $matcher->ipv6Address('::ffff:192.0.2.1')
email | Regex to match an address. | Value (hello@pact.io) | $matcher->email('hello@pact.io')
+nullValue | Match a null value. | none | $matcher->nullValue()
+matchAll | Match if all the matchers match (combined with AND). | Value, Matchers | $matcher->matchAll(['key' => 'value'], [$matcher->atLeast(1), $matcher->atMost(2)])
+matchAny | Match if at least one of the matchers matches (combined with OR). See [Combining matchers with OR](#combining-matchers-with-or). | Value, Matchers | $matcher->matchAny('Fred', [$matcher->like(null), $matcher->nullValue()])
+likeOrNull | Match a value of the same type as the example, or null. Shortcut for `matchAny` with `like` and `nullValue`. | Value | $matcher->likeOrNull('Fred')
+
+### Combining matchers with OR
+
+> [!NOTE]
+> This requires pact_ffi TODO(version with pact-foundation/pact-reference#601) or later. Older versions combine the
+> matchers with AND, so a value can never match both `like` and `nullValue`.
+
+`matchAny` applies several matchers to the same value, and the value matches if at least one of them matches. The
+first argument is the example value, the second is the list of alternatives.
+
+```php
+$matcher = new Matcher();
+
+$response = new ProviderResponse();
+$response
+ ->setStatus(200)
+ ->addHeader('Content-Type', 'application/json')
+ ->setBody([
+ // A string, or null
+ 'nickname' => $matcher->likeOrNull('Fred'),
+ // A string of digits, or 'unknown'
+ 'age' => $matcher->matchAny('42', [
+ $matcher->regex(null, '^\d+$'),
+ $matcher->regex(null, '^unknown$'),
+ ]),
+ // An object, or null. The matchers inside the object still apply when it is not null.
+ 'address' => $matcher->matchAny(
+ [
+ 'street' => 'Main St',
+ 'number' => $matcher->integerV3(42),
+ ],
+ [
+ $matcher->like(null),
+ $matcher->nullValue(),
+ ]
+ ),
+ ]);
+```
+
+`'address'` is written to the pact file as:
+
+```json
+"$.address": {
+ "combine": "OR",
+ "matchers": [{ "match": "type" }, { "match": "null" }]
+},
+"$.address.number": {
+ "combine": "AND",
+ "matchers": [{ "match": "integer" }]
+}
+```
+
+`matchAny` works for bodies, headers and query parameters.
+
+Things to keep in mind:
+
+* Only the example value is used in the consumer test: the mock server always returns it, so your consumer code is
+ never tested with the other alternatives (e.g. with `null`). Write a separate test (or interaction) if your code has to
+ handle them.
+* Every alternative is checked against the actual value, using the example value as the expected value. So matchers
+ that compare with the expected value (like `like` or `equal`) can only describe the example value. For example,
+ `$matcher->matchAny('10', [$matcher->regex(null, '^\d+$'), $matcher->equal('all')])` does not accept `'all'`, use
+ `$matcher->regex(null, '^all$')` instead.
+* Put all the alternatives in the list of matchers. The example value can not be a matcher, and `matchAll`/`matchAny`
+ can not be nested.
+* `matchAny` is not supported by plugins (matching expressions can not combine matchers with OR).
+
+See [example/or-matcher](../example/or-matcher) for a full example.
## Build the Interaction
diff --git a/example/or-matcher/consumer/autoload.php b/example/or-matcher/consumer/autoload.php
new file mode 100644
index 000000000..4dfd88b69
--- /dev/null
+++ b/example/or-matcher/consumer/autoload.php
@@ -0,0 +1,6 @@
+addPsr4('OrMatcherConsumer\\', __DIR__ . '/src');
+$loader->addPsr4('OrMatcherConsumer\\Tests\\', __DIR__ . '/tests');
diff --git a/example/or-matcher/consumer/phpunit.xml b/example/or-matcher/consumer/phpunit.xml
new file mode 100644
index 000000000..7768334ba
--- /dev/null
+++ b/example/or-matcher/consumer/phpunit.xml
@@ -0,0 +1,11 @@
+
+
+
+
+ ./tests
+
+
+
+
+
+
diff --git a/example/or-matcher/consumer/src/Service/HttpClientService.php b/example/or-matcher/consumer/src/Service/HttpClientService.php
new file mode 100644
index 000000000..01b1052ba
--- /dev/null
+++ b/example/or-matcher/consumer/src/Service/HttpClientService.php
@@ -0,0 +1,29 @@
+httpClient = new Client();
+ }
+
+ /**
+ * @param array $user
+ */
+ public function updateUser(array $user, string $limit, string $apiVersion): ResponseInterface
+ {
+ return $this->httpClient->put("{$this->baseUri}/users/1", [
+ 'headers' => ['Accept' => 'application/json', 'X-Api-Version' => $apiVersion],
+ 'query' => ['limit' => $limit],
+ 'json' => $user,
+ 'http_errors' => false,
+ ]);
+ }
+}
diff --git a/example/or-matcher/consumer/tests/Service/OrMatcherTest.php b/example/or-matcher/consumer/tests/Service/OrMatcherTest.php
new file mode 100644
index 000000000..f2eeff84f
--- /dev/null
+++ b/example/or-matcher/consumer/tests/Service/OrMatcherTest.php
@@ -0,0 +1,187 @@
+matcher = new Matcher();
+
+ $request = new ConsumerRequest();
+ $request
+ ->setMethod('PUT')
+ ->setPath('/users/1')
+ // A query value that is either a number, or 'all'.
+ // Every alternative is checked against the example value ('10'), so `equal('all')` would not work here.
+ ->addQueryParameter('limit', $this->matcher->matchAny('10', [
+ $this->matcher->regex(null, '^\d+$'),
+ $this->matcher->regex(null, '^all$'),
+ ]))
+ // A header value that is either a number, or 'latest'
+ ->addHeader('X-Api-Version', $this->matcher->matchAny('2', [
+ $this->matcher->regex(null, '^\d+$'),
+ $this->matcher->regex(null, '^latest$'),
+ ]))
+ ->addHeader('Content-Type', 'application/json')
+ ->setBody([
+ // A string, or null
+ 'nickname' => $this->matcher->likeOrNull('Fred'),
+ // An object, or null. The rules inside the object still apply when it is not null.
+ 'address' => $this->matcher->likeOrNull([
+ 'street' => 'Main St',
+ 'number' => $this->matcher->integerV3(42),
+ ]),
+ ]);
+
+ $response = new ProviderResponse();
+ $response
+ ->setStatus(200)
+ ->addHeader('Content-Type', 'application/json')
+ ->setBody([
+ 'id' => $this->matcher->integerV3(1),
+ 'nickname' => $this->matcher->likeOrNull('Fred'),
+ // Same as `likeOrNull`, using `matchAny` and `nullValue` directly
+ 'address' => $this->matcher->matchAny(
+ [
+ 'street' => 'Main St',
+ 'number' => $this->matcher->integerV3(42),
+ ],
+ [
+ $this->matcher->like(null),
+ $this->matcher->nullValue(),
+ ]
+ ),
+ ]);
+
+ $this->config = new MockServerConfig();
+ $this->config
+ ->setConsumer('orMatcherConsumer')
+ ->setProvider('orMatcherProvider')
+ ->setPactDir(__DIR__.'/../../../pacts')
+ ->setPactSpecificationVersion('4.0.0');
+ if ($logLevel = \getenv('PACT_LOGLEVEL')) {
+ $this->config->setLogLevel($logLevel);
+ }
+ $this->builder = new InteractionBuilder($this->config);
+ $this->builder
+ ->uponReceiving('A put request to /users/{id}')
+ ->with($request)
+ ->willRespondWith($response);
+ }
+
+ /**
+ * @return iterable, string, string}>
+ */
+ public static function matchingRequests(): iterable
+ {
+ yield 'example values' => [['nickname' => 'Fred', 'address' => ['street' => 'Main St', 'number' => 42]], '10', '2'];
+ yield 'first alternatives' => [['nickname' => 'Bob', 'address' => ['street' => 'High St', 'number' => 7]], '25', '3'];
+ yield 'second alternatives' => [['nickname' => null, 'address' => null], 'all', 'latest'];
+ }
+
+ /**
+ * @param array $user
+ */
+ #[DataProvider('matchingRequests')]
+ public function testMatchingRequest(array $user, string $limit, string $apiVersion): void
+ {
+ $service = new HttpClientService($this->config->getBaseUri());
+ $response = $service->updateUser($user, $limit, $apiVersion);
+ $verifyResult = $this->builder->verify();
+
+ $this->assertTrue($verifyResult);
+ $this->assertSame(200, $response->getStatusCode());
+ // Only the example value is returned by the mock server, so the consumer code is only tested with it.
+ $this->assertEquals([
+ 'id' => 1,
+ 'nickname' => 'Fred',
+ 'address' => ['street' => 'Main St', 'number' => 42],
+ ], \json_decode($response->getBody(), true, 512, JSON_THROW_ON_ERROR));
+
+ $this->assertPactFileHasOrRules();
+ }
+
+ /**
+ * @return iterable, string, string}>
+ */
+ public static function nonMatchingRequests(): iterable
+ {
+ $user = ['nickname' => 'Fred', 'address' => ['street' => 'Main St', 'number' => 42]];
+ yield 'nickname is neither a string nor null' => [['nickname' => 123] + $user, '10', '2'];
+ yield 'address is neither an object nor null' => [['address' => 'nowhere'] + $user, '10', '2'];
+ yield 'address number is not an integer' => [['address' => ['street' => 'Main St', 'number' => '42']] + $user, '10', '2'];
+ yield 'limit is neither a number nor all' => [$user, 'many', '2'];
+ yield 'api version is neither a number nor latest' => [$user, '10', 'beta'];
+ }
+
+ /**
+ * @param array $user
+ */
+ #[DataProvider('nonMatchingRequests')]
+ public function testNonMatchingRequest(array $user, string $limit, string $apiVersion): void
+ {
+ $service = new HttpClientService($this->config->getBaseUri());
+ $response = $service->updateUser($user, $limit, $apiVersion);
+ $verifyResult = $this->builder->verify();
+
+ $this->assertFalse($verifyResult);
+ $this->assertSame(500, $response->getStatusCode());
+ }
+
+ private function assertPactFileHasOrRules(): void
+ {
+ $pactFile = $this->config->getPactDir() . '/orMatcherConsumer-orMatcherProvider.json';
+ $this->assertFileExists($pactFile);
+ $pact = \json_decode((string) \file_get_contents($pactFile), true, 512, JSON_THROW_ON_ERROR);
+ $this->assertIsArray($pact);
+ $this->assertIsArray($pact['interactions']);
+ $this->assertCount(1, $pact['interactions']);
+ $interaction = $pact['interactions'][0];
+ $this->assertIsArray($interaction);
+ $this->assertIsArray($interaction['request']);
+ $this->assertIsArray($interaction['response']);
+
+ $typeOrNull = ['combine' => 'OR', 'matchers' => [['match' => 'type'], ['match' => 'null']]];
+ $numberOr = static fn (string $regex): array => [
+ 'combine' => 'OR',
+ 'matchers' => [['match' => 'regex', 'regex' => '^\d+$'], ['match' => 'regex', 'regex' => $regex]],
+ ];
+
+ $this->assertEquals([
+ 'body' => [
+ '$.nickname' => $typeOrNull,
+ '$.address' => $typeOrNull,
+ '$.address.number' => ['combine' => 'AND', 'matchers' => [['match' => 'integer']]],
+ ],
+ 'header' => [
+ 'X-Api-Version' => $numberOr('^latest$'),
+ ],
+ 'query' => [
+ 'limit' => $numberOr('^all$'),
+ ],
+ ], $interaction['request']['matchingRules'] ?? null);
+
+ $this->assertEquals([
+ 'body' => [
+ '$.id' => ['combine' => 'AND', 'matchers' => [['match' => 'integer']]],
+ '$.nickname' => $typeOrNull,
+ '$.address' => $typeOrNull,
+ '$.address.number' => ['combine' => 'AND', 'matchers' => [['match' => 'integer']]],
+ ],
+ ], $interaction['response']['matchingRules'] ?? null);
+ }
+}
diff --git a/example/or-matcher/pacts/orMatcherConsumer-orMatcherProvider.json b/example/or-matcher/pacts/orMatcherConsumer-orMatcherProvider.json
new file mode 100644
index 000000000..90af57ea5
--- /dev/null
+++ b/example/or-matcher/pacts/orMatcherConsumer-orMatcherProvider.json
@@ -0,0 +1,180 @@
+{
+ "consumer": {
+ "name": "orMatcherConsumer"
+ },
+ "interactions": [
+ {
+ "description": "A put request to /users/{id}",
+ "pending": false,
+ "request": {
+ "body": {
+ "content": {
+ "address": {
+ "number": 42,
+ "street": "Main St"
+ },
+ "nickname": "Fred"
+ },
+ "contentType": "application/json",
+ "encoded": false
+ },
+ "headers": {
+ "Content-Type": [
+ "application/json"
+ ],
+ "X-Api-Version": [
+ "2"
+ ]
+ },
+ "matchingRules": {
+ "body": {
+ "$.address": {
+ "combine": "OR",
+ "matchers": [
+ {
+ "match": "type"
+ },
+ {
+ "match": "null"
+ }
+ ]
+ },
+ "$.address.number": {
+ "combine": "AND",
+ "matchers": [
+ {
+ "match": "integer"
+ }
+ ]
+ },
+ "$.nickname": {
+ "combine": "OR",
+ "matchers": [
+ {
+ "match": "type"
+ },
+ {
+ "match": "null"
+ }
+ ]
+ }
+ },
+ "header": {
+ "X-Api-Version": {
+ "combine": "OR",
+ "matchers": [
+ {
+ "match": "regex",
+ "regex": "^\\d+$"
+ },
+ {
+ "match": "regex",
+ "regex": "^latest$"
+ }
+ ]
+ }
+ },
+ "query": {
+ "limit": {
+ "combine": "OR",
+ "matchers": [
+ {
+ "match": "regex",
+ "regex": "^\\d+$"
+ },
+ {
+ "match": "regex",
+ "regex": "^all$"
+ }
+ ]
+ }
+ }
+ },
+ "method": "PUT",
+ "path": "/users/1",
+ "query": {
+ "limit": [
+ "10"
+ ]
+ }
+ },
+ "response": {
+ "body": {
+ "content": {
+ "address": {
+ "number": 42,
+ "street": "Main St"
+ },
+ "id": 1,
+ "nickname": "Fred"
+ },
+ "contentType": "application/json",
+ "encoded": false
+ },
+ "headers": {
+ "Content-Type": [
+ "application/json"
+ ]
+ },
+ "matchingRules": {
+ "body": {
+ "$.address": {
+ "combine": "OR",
+ "matchers": [
+ {
+ "match": "type"
+ },
+ {
+ "match": "null"
+ }
+ ]
+ },
+ "$.address.number": {
+ "combine": "AND",
+ "matchers": [
+ {
+ "match": "integer"
+ }
+ ]
+ },
+ "$.id": {
+ "combine": "AND",
+ "matchers": [
+ {
+ "match": "integer"
+ }
+ ]
+ },
+ "$.nickname": {
+ "combine": "OR",
+ "matchers": [
+ {
+ "match": "type"
+ },
+ {
+ "match": "null"
+ }
+ ]
+ }
+ }
+ },
+ "status": 200
+ },
+ "transport": "http",
+ "type": "Synchronous/HTTP"
+ }
+ ],
+ "metadata": {
+ "pactRust": {
+ "ffi": "0.5.12",
+ "mockserver": "2.2.6",
+ "models": "1.3.17"
+ },
+ "pactSpecification": {
+ "version": "4.0"
+ }
+ },
+ "provider": {
+ "name": "orMatcherProvider"
+ }
+}
\ No newline at end of file
diff --git a/example/or-matcher/provider/autoload.php b/example/or-matcher/provider/autoload.php
new file mode 100644
index 000000000..9bf80a413
--- /dev/null
+++ b/example/or-matcher/provider/autoload.php
@@ -0,0 +1,5 @@
+addPsr4('OrMatcherProvider\\Tests\\', __DIR__ . '/tests');
diff --git a/example/or-matcher/provider/phpunit.xml b/example/or-matcher/provider/phpunit.xml
new file mode 100644
index 000000000..7768334ba
--- /dev/null
+++ b/example/or-matcher/provider/phpunit.xml
@@ -0,0 +1,11 @@
+
+
+
+
+ ./tests
+
+
+
+
+
+
diff --git a/example/or-matcher/provider/public/index.php b/example/or-matcher/provider/public/index.php
new file mode 100644
index 000000000..ab2ecc673
--- /dev/null
+++ b/example/or-matcher/provider/public/index.php
@@ -0,0 +1,27 @@
+put('/users/{id}', function () {
+ return Response::json([
+ 'id' => 1,
+ 'nickname' => null,
+ 'address' => null,
+ ]);
+});
+
+$app->post('/pact-change-state', function (ServerRequestInterface $request) {
+ /** @var array{action: string, state: string, params: array} $body */
+ $body = json_decode((string) $request->getBody(), true);
+
+ return Response::plaintext(sprintf('%s provider state %s with params: %s', $body['action'], $body['state'], (string) json_encode($body['params'])));
+});
+
+$app->run();
diff --git a/example/or-matcher/provider/tests/PactVerifyTest.php b/example/or-matcher/provider/tests/PactVerifyTest.php
new file mode 100644
index 000000000..55232ac8a
--- /dev/null
+++ b/example/or-matcher/provider/tests/PactVerifyTest.php
@@ -0,0 +1,47 @@
+process = new PhpProcess(__DIR__ . '/../public/');
+ $this->process->start();
+ }
+
+ protected function tearDown(): void
+ {
+ $this->process->stop();
+ }
+
+ public function testPactVerifyConsumer(): void
+ {
+ $config = new VerifierConfig();
+ $config->getProviderInfo()
+ ->setName('orMatcherProvider')
+ ->setHost('localhost')
+ ->setPort($this->process->getPort());
+ $config->getProviderState()
+ ->setStateChangeUrl(new Uri(sprintf('http://localhost:%d/pact-change-state', $this->process->getPort())))
+ ;
+ if ($level = \getenv('PACT_LOGLEVEL')) {
+ $config->setLogLevel($level);
+ }
+
+ $verifier = new Verifier($config);
+ $verifier->addFile(__DIR__ . '/../../pacts/orMatcherConsumer-orMatcherProvider.json');
+
+ $verifyResult = $verifier->verify();
+
+ $this->assertTrue($verifyResult);
+ }
+}
diff --git a/phpstan.neon b/phpstan.neon
index 575705a16..96250c74f 100644
--- a/phpstan.neon
+++ b/phpstan.neon
@@ -26,6 +26,8 @@ parameters:
- example/json/provider/autoload.php
- example/matchers/consumer/autoload.php
- example/matchers/provider/autoload.php
+ - example/or-matcher/consumer/autoload.php
+ - example/or-matcher/provider/autoload.php
- example/message/consumer/autoload.php
- example/message/provider/autoload.php
- example/multipart/consumer/autoload.php
diff --git a/src/PhpPact/Consumer/Matcher/Matcher.php b/src/PhpPact/Consumer/Matcher/Matcher.php
index 86bd3ce1e..8f3210d87 100644
--- a/src/PhpPact/Consumer/Matcher/Matcher.php
+++ b/src/PhpPact/Consumer/Matcher/Matcher.php
@@ -31,6 +31,7 @@
use PhpPact\Consumer\Matcher\Matchers\Includes;
use PhpPact\Consumer\Matcher\Matchers\Integer;
use PhpPact\Consumer\Matcher\Matchers\MatchAll;
+use PhpPact\Consumer\Matcher\Matchers\MatchAny;
use PhpPact\Consumer\Matcher\Matchers\MatchingField;
use PhpPact\Consumer\Matcher\Matchers\Max;
use PhpPact\Consumer\Matcher\Matchers\MaxType;
@@ -569,6 +570,36 @@ public function matchAll(object|array $value, array $matchers): MatchAll
return $matcher->withFormatter($this->createFormatter());
}
+ /**
+ * Match if at least one of the matchers matches (matching rules combined with OR).
+ *
+ * Only the example value is used in the consumer test, the other alternatives are never exercised against
+ * the consumer code. Put all the alternatives in the list of matchers, don't use a matcher as the value.
+ *
+ * NOTE: Requires a pact_ffi version supporting `pact:matcher:combine` (TODO: pact_ffi version)
+ *
+ * @param MatcherInterface[] $matchers
+ */
+ public function matchAny(mixed $value, array $matchers): MatchAny
+ {
+ $matcher = new MatchAny($value, $matchers);
+
+ return $matcher->withFormatter($this->createFormatter());
+ }
+
+ /**
+ * Value that is either null, or has the same type as the example value.
+ *
+ * Shortcut for `matchAny($value, [like(...), nullValue()])`. Matchers inside an array or object value
+ * are still applied to its children, when the value is not null.
+ *
+ * NOTE: Requires a pact_ffi version supporting `pact:matcher:combine` (TODO: pact_ffi version)
+ */
+ public function likeOrNull(mixed $value): MatchAny
+ {
+ return $this->matchAny($value, [$this->like(null), $this->nullValue()]);
+ }
+
/**
* An array that has to have at least the required number of elements
*/
diff --git a/src/PhpPact/Consumer/Matcher/Matchers/MatchAny.php b/src/PhpPact/Consumer/Matcher/Matchers/MatchAny.php
new file mode 100644
index 000000000..ccdbb382d
--- /dev/null
+++ b/src/PhpPact/Consumer/Matcher/Matchers/MatchAny.php
@@ -0,0 +1,70 @@
+setMatchers($matchers);
+ parent::__construct();
+ }
+
+ public function formatJson(): Attributes
+ {
+ return new Attributes([
+ 'pact:matcher:type' => array_map(
+ $this->getFormatter()->format(...),
+ $this->matchers
+ ),
+ 'pact:matcher:combine' => 'OR',
+ 'value' => $this->value,
+ ]);
+ }
+
+ /**
+ * @param MatcherInterface[] $matchers
+ */
+ private function setMatchers(array $matchers): void
+ {
+ if (empty($matchers)) {
+ throw new InvalidValueException('Matchers should not be empty');
+ }
+ $this->matchers = [];
+ foreach ($matchers as $matcher) {
+ if ($matcher instanceof self || $matcher instanceof MatchAll) {
+ throw new MatcherNotSupportedException("Nested 'matchAny' or 'matchAll' matcher is not supported");
+ }
+ $this->addMatcher($matcher);
+ }
+ }
+
+ private function addMatcher(MatcherInterface $matcher): void
+ {
+ $this->matchers[] = $matcher;
+ }
+}
diff --git a/tests/PhpPact/Consumer/Matcher/MatcherTest.php b/tests/PhpPact/Consumer/Matcher/MatcherTest.php
index 6f2212003..6e02812db 100644
--- a/tests/PhpPact/Consumer/Matcher/MatcherTest.php
+++ b/tests/PhpPact/Consumer/Matcher/MatcherTest.php
@@ -31,6 +31,7 @@
use PhpPact\Consumer\Matcher\Matchers\Includes;
use PhpPact\Consumer\Matcher\Matchers\Integer;
use PhpPact\Consumer\Matcher\Matchers\MatchAll;
+use PhpPact\Consumer\Matcher\Matchers\MatchAny;
use PhpPact\Consumer\Matcher\Matchers\MatchingField;
use PhpPact\Consumer\Matcher\Matchers\Max;
use PhpPact\Consumer\Matcher\Matchers\MaxType;
@@ -552,6 +553,22 @@ public function testMatchAll(): void
$this->assertInstanceOf(JsonFormatter::class, $result->getFormatter());
}
+ public function testMatchAny(): void
+ {
+ $this->assertInstanceOf(MatchAny::class, $result = $this->matcher->matchAny('value', [$this->matcher->like('text'), $this->matcher->nullValue()]));
+ $this->assertInstanceOf(JsonFormatter::class, $result->getFormatter());
+ }
+
+ public function testLikeOrNull(): void
+ {
+ $this->assertInstanceOf(MatchAny::class, $result = $this->matcher->likeOrNull(['key' => 'value']));
+ $this->assertInstanceOf(JsonFormatter::class, $result->getFormatter());
+ $this->assertJsonStringEqualsJsonString(
+ '{"pact:matcher:type":[{"pact:matcher:type":"type","value":null},{"pact:matcher:type":"null"}],"pact:matcher:combine":"OR","value":{"key":"value"}}',
+ (string) json_encode($result)
+ );
+ }
+
public function testAtLeast(): void
{
$this->assertInstanceOf(Min::class, $result = $this->matcher->atLeast(123));
diff --git a/tests/PhpPact/Consumer/Matcher/Matchers/MatchAnyTest.php b/tests/PhpPact/Consumer/Matcher/Matchers/MatchAnyTest.php
new file mode 100644
index 000000000..61ba9b477
--- /dev/null
+++ b/tests/PhpPact/Consumer/Matcher/Matchers/MatchAnyTest.php
@@ -0,0 +1,120 @@
+expectException(MatcherNotSupportedException::class);
+ $this->expectExceptionMessage("Nested 'matchAny' or 'matchAll' matcher is not supported");
+ new MatchAny('abc', [new MatchAny('abc', [new Type('abc')])]);
+ }
+
+ public function testNestedMatchAllMatchers(): void
+ {
+ $this->expectException(MatcherNotSupportedException::class);
+ $this->expectExceptionMessage("Nested 'matchAny' or 'matchAll' matcher is not supported");
+ new MatchAny([], [new MatchAll([], [new Type(123)])]);
+ }
+
+ public function testMatcherAsValue(): void
+ {
+ $this->expectException(MatcherNotSupportedException::class);
+ $this->expectExceptionMessage("Value of 'matchAny' matcher can not be a matcher, add it to the list of matchers instead");
+ new MatchAny(new Regex('^\d+$', '100'), [new NullValue()]);
+ }
+
+ public function testMissingMatchers(): void
+ {
+ $this->expectException(InvalidValueException::class);
+ $this->expectExceptionMessage('Matchers should not be empty');
+ new MatchAny('value', []);
+ }
+
+ #[TestWith([new MatchAny('Fred', [new Type(null), new NullValue()]), << 'Main St', 'number' => new Integer(42)], [new Type(null), new NullValue()]), <<assertIsString($jsonEncoded);
+ $this->assertJsonStringEqualsJsonString(
+ $json,
+ $jsonEncoded
+ );
+ }
+
+ public function testFormatExpressionIsNotSupported(): void
+ {
+ $matcher = (new MatchAny('Fred', [new Type(null), new NullValue()]))->withFormatter(new ExpressionFormatter());
+ $this->expectException(MatcherNotSupportedException::class);
+ $this->expectExceptionMessage('Matcher does not support expression format');
+ json_encode($matcher);
+ }
+}