From b4142304ab3f223df71c12df74b5e33c4c7141e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9F=D0=B0=D0=B2=D0=B5=D0=BB?= Date: Tue, 25 May 2021 10:49:29 +0300 Subject: [PATCH] `matchOrigin` matcher --- src/PockBuilder.php | 28 ++++++++++++++++++++++++ tests/src/PockBuilderTest.php | 40 +++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) diff --git a/src/PockBuilder.php b/src/PockBuilder.php index 1f47250..2751e0d 100644 --- a/src/PockBuilder.php +++ b/src/PockBuilder.php @@ -43,6 +43,7 @@ use Pock\Traits\JsonDecoderTrait; use Pock\Traits\JsonSerializerAwareTrait; use Pock\Traits\XmlSerializerAwareTrait; use Psr\Http\Client\ClientInterface; +use RuntimeException; use Throwable; /** @@ -129,6 +130,33 @@ class PockBuilder return $this->addMatcher(new HostMatcher($host)); } + /** + * Matches request by origin. + * + * @param string $origin + * + * @return self + * @throws \RuntimeException + */ + public function matchOrigin(string $origin): self + { + $parsed = parse_url($origin); + + if (!is_array($parsed)) { + throw new RuntimeException('Malformed origin: ' . $origin); + } + + if (array_key_exists('scheme', $parsed) && !empty($parsed['scheme'])) { + $this->matchScheme($parsed['scheme']); + } + + if (array_key_exists('host', $parsed) && !empty($parsed['host'])) { + $this->matchHost($parsed['host']); + } + + return $this; + } + /** * Matches request by the whole URI. * diff --git a/tests/src/PockBuilderTest.php b/tests/src/PockBuilderTest.php index ac1462c..507367e 100644 --- a/tests/src/PockBuilderTest.php +++ b/tests/src/PockBuilderTest.php @@ -151,6 +151,46 @@ class PockBuilderTest extends PockTestCase self::assertEquals('Successful', $response->getBody()->getContents()); } + public function testMatchOriginFailure(): void + { + $incorrectOrigin = RequestScheme::HTTPS . ':///' . self::TEST_HOST; + + $this->expectExceptionMessage($incorrectOrigin); + + $builder = new PockBuilder(); + $builder->matchMethod(RequestMethod::GET) + ->matchOrigin($incorrectOrigin) + ->reply(200) + ->withHeader('Content-Type', 'text/plain') + ->withBody('Successful'); + + $builder->getClient()->sendRequest( + self::getPsr17Factory() + ->createRequest(RequestMethod::GET, 'https://another-example.com') + ); + } + + public function testMatchOrigin(): void + { + $origin = RequestScheme::HTTPS . '://' . self::TEST_HOST; + $builder = new PockBuilder(); + + $builder->matchMethod(RequestMethod::GET) + ->matchOrigin($origin) + ->reply(200) + ->withHeader('Content-Type', 'text/plain') + ->withBody('Successful'); + + $response = $builder->getClient()->sendRequest( + self::getPsr17Factory() + ->createRequest(RequestMethod::GET, $origin) + ); + + self::assertEquals(200, $response->getStatusCode()); + self::assertEquals(['Content-Type' => ['text/plain']], $response->getHeaders()); + self::assertEquals('Successful', $response->getBody()->getContents()); + } + public function testMatchExactHeader(): void { $builder = new PockBuilder();