diff --git a/src/Client.php b/src/Client.php index e05fa1b..a14967e 100644 --- a/src/Client.php +++ b/src/Client.php @@ -19,6 +19,7 @@ use Pock\Promise\HttpRejectedPromise; use Psr\Http\Client\ClientInterface; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; +use Throwable; /** * Class Client @@ -31,14 +32,18 @@ class Client implements ClientInterface, HttpClient, HttpAsyncClient /** @var \Pock\MockInterface[] */ private $mocks; + /** @var \Psr\Http\Client\ClientInterface|null */ + private $fallbackClient; + /** * Client constructor. * * @param \Pock\MockInterface[] $mocks */ - public function __construct(array $mocks) + public function __construct(array $mocks, ?ClientInterface $fallbackClient = null) { $this->mocks = $mocks; + $this->fallbackClient = $fallbackClient; } /** @@ -86,6 +91,14 @@ class Client implements ClientInterface, HttpClient, HttpAsyncClient } } + if (null !== $this->fallbackClient) { + try { + return new HttpFulfilledPromise($this->fallbackClient->sendRequest($request)); + } catch (Throwable $throwable) { + return new HttpRejectedPromise($throwable); + } + } + throw new UnsupportedRequestException(); } } diff --git a/src/PockBuilder.php b/src/PockBuilder.php index cc40889..a28ee4a 100644 --- a/src/PockBuilder.php +++ b/src/PockBuilder.php @@ -12,6 +12,7 @@ namespace Pock; use Pock\Matchers\AnyRequestMatcher; use Pock\Matchers\HostMatcher; use Pock\Matchers\MultipleMatcher; +use Psr\Http\Client\ClientInterface; /** * Class PockBuilder @@ -33,6 +34,9 @@ class PockBuilder /** @var \Pock\MockInterface[] */ private $mocks; + /** @var \Psr\Http\Client\ClientInterface|null */ + private $fallbackClient; + /** * PockBuilder constructor. */ @@ -48,7 +52,7 @@ class PockBuilder * * @return $this */ - public function host(string $host): PockBuilder + public function matchHost(string $host): PockBuilder { $this->closePrevious(); $this->matcher->addMatcher(new HostMatcher($host)); @@ -67,11 +71,26 @@ class PockBuilder $this->response = null; $this->throwable = null; $this->mocks = []; + + return $this; + } + + /** + * Sets fallback Client. It will be used if no request can be matched. + * + * @param \Psr\Http\Client\ClientInterface|null $fallbackClient + * + * @return \Pock\PockBuilder + */ + public function setFallbackClient(?ClientInterface $fallbackClient = null): PockBuilder + { + $this->fallbackClient = $fallbackClient; + return $this; } public function getClient(): Client { - return new Client($this->mocks); + return new Client($this->mocks, $this->fallbackClient); } private function closePrevious(): void