]> BookStack Code Mirror - bookstack/blob - app/Http/HttpRequestService.php
Removed redundant null check
[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 GuzzleHttp\Psr7\Response;
11 use Psr\Http\Client\ClientInterface;
12
13 class HttpRequestService
14 {
15     protected ?HandlerStack $handler = null;
16
17     /**
18      * Build a new http client for sending requests on.
19      */
20     public function buildClient(int $timeout, array $options = []): ClientInterface
21     {
22         $defaultOptions = [
23             'timeout' => $timeout,
24             'handler' => $this->handler,
25         ];
26
27         return new Client(array_merge($options, $defaultOptions));
28     }
29
30     /**
31      * Create a new JSON http request for use with a client.
32      */
33     public function jsonRequest(string $method, string $uri, array $data): GuzzleRequest
34     {
35         $headers = ['Content-Type' => 'application/json'];
36         return new GuzzleRequest($method, $uri, $headers, json_encode($data));
37     }
38
39     /**
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
43      */
44     public function mockClient(array $responses = [], bool $pad = true): HttpClientHistory
45     {
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
48         // too many requests.
49         if ($pad) {
50             $response = new Response(200, [], 'success');
51             $responses = array_merge($responses, array_fill(0, 10, $response));
52         }
53
54         $container = [];
55         $history = Middleware::history($container);
56         $mock = new MockHandler($responses);
57         $this->handler = HandlerStack::create($mock);
58         $this->handler->push($history, 'history');
59
60         return new HttpClientHistory($container);
61     }
62
63     /**
64      * Clear mocking that has been set up for clients.
65      */
66     public function clearMocking(): void
67     {
68         $this->handler = null;
69     }
70 }