3 namespace BookStack\Http;
6 use GuzzleHttp\Handler\MockHandler;
7 use GuzzleHttp\HandlerStack;
8 use GuzzleHttp\Middleware;
9 use GuzzleHttp\Psr7\Request as GuzzleRequest;
10 use GuzzleHttp\Psr7\Response;
11 use Psr\Http\Client\ClientInterface;
13 class HttpRequestService
15 protected ?HandlerStack $handler = null;
18 * Build a new http client for sending requests on.
20 public function buildClient(int $timeout, array $options = []): ClientInterface
23 'timeout' => $timeout,
24 'handler' => $this->handler,
27 return new Client(array_merge($options, $defaultOptions));
31 * Create a new JSON http request for use with a client.
33 public function jsonRequest(string $method, string $uri, array $data): GuzzleRequest
35 $headers = ['Content-Type' => 'application/json'];
36 return new GuzzleRequest($method, $uri, $headers, json_encode($data));
40 * Mock any http clients built from this service, and response with the given responses.
41 * Returns history which can then be queried.
42 * @link https://docs.guzzlephp.org/en/stable/testing.html#history-middleware
44 public function mockClient(array $responses = [], bool $pad = true): HttpClientHistory
46 // By default, we pad out the responses with 10 successful values so that requests will be
47 // properly recorded for inspection. Otherwise, we can't later check if we're received
50 $response = new Response(200, [], 'success');
51 $responses = array_merge($responses, array_fill(0, 10, $response));
55 $history = Middleware::history($container);
56 $mock = new MockHandler($responses);
57 $this->handler = HandlerStack::create($mock);
58 $this->handler->push($history, 'history');
60 return new HttpClientHistory($container);
64 * Clear mocking that has been set up for clients.
66 public function clearMocking(): void
68 $this->handler = null;