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 Psr\Http\Client\ClientInterface;
12 class HttpRequestService
14 protected ?HandlerStack $handler = null;
17 * Build a new http client for sending requests on.
19 public function buildClient(int $timeout, array $options): ClientInterface
22 'timeout' => $timeout,
23 'handler' => $this->handler,
26 return new Client(array_merge($options, $defaultOptions));
30 * Create a new JSON http request for use with a client.
32 public function jsonRequest(string $method, string $uri, array $data): GuzzleRequest
34 $headers = ['Content-Type' => 'application/json'];
35 return new GuzzleRequest($method, $uri, $headers, json_encode($data));
39 * Mock any http clients built from this service, and response with the given responses.
40 * Returns history which can then be queried.
41 * @link https://docs.guzzlephp.org/en/stable/testing.html#history-middleware
43 public function mockClient(array $responses = []): HttpClientHistory
46 $history = Middleware::history($container);
47 $mock = new MockHandler($responses);
48 $this->handler = HandlerStack::create($mock);
49 $this->handler->push($history, 'history');
51 return new HttpClientHistory($container);
55 * Clear mocking that has been set up for clients.
57 public function clearMocking(): void
59 $this->handler = null;