ability to fallback to another client, fix for a typo

This commit is contained in:
Pavel 2021-05-13 21:51:13 +03:00
parent 2429eab7f8
commit fea8179292
2 changed files with 35 additions and 3 deletions

View File

@ -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();
}
}

View File

@ -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