]> BookStack Code Mirror - bookstack/blob - app/Http/HttpRequestService.php
Started aligning app-wide outbound http calling behaviour
[bookstack] / app / Http / HttpRequestService.php
1 <?php
2
3 namespace BookStack\Http;
4
5 use GuzzleHttp\Client;
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;
11
12 class HttpRequestService
13 {
14     protected ?HandlerStack $handler = null;
15
16     /**
17      * Build a new http client for sending requests on.
18      */
19     public function buildClient(int $timeout, array $options): ClientInterface
20     {
21         $defaultOptions = [
22             'timeout' => $timeout,
23             'handler' => $this->handler,
24         ];
25
26         return new Client(array_merge($options, $defaultOptions));
27     }
28
29     /**
30      * Create a new JSON http request for use with a client.
31      */
32     public function jsonRequest(string $method, string $uri, array $data): GuzzleRequest
33     {
34         $headers = ['Content-Type' => 'application/json'];
35         return new GuzzleRequest($method, $uri, $headers, json_encode($data));
36     }
37
38     /**
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
42      */
43     public function mockClient(array $responses = []): HttpClientHistory
44     {
45         $container = [];
46         $history = Middleware::history($container);
47         $mock = new MockHandler($responses);
48         $this->handler = HandlerStack::create($mock);
49         $this->handler->push($history, 'history');
50
51         return new HttpClientHistory($container);
52     }
53
54     /**
55      * Clear mocking that has been set up for clients.
56      */
57     public function clearMocking(): void
58     {
59         $this->handler = null;
60     }
61 }