Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
100.00% |
13 / 13 |
|
100.00% |
5 / 5 |
CRAP | |
100.00% |
1 / 1 |
HttpClient | |
100.00% |
13 / 13 |
|
100.00% |
5 / 5 |
8 | |
100.00% |
1 / 1 |
__construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
setConnectionTimeout | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
2 | |||
getConnectionTimeout | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
request | |
100.00% |
6 / 6 |
|
100.00% |
1 / 1 |
2 | |||
validateHttpVerb | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
2 |
1 | <?php |
2 | |
3 | namespace pvc\http; |
4 | |
5 | use GuzzleHttp\Client as GuzzleClient; |
6 | use GuzzleHttp\Psr7\Request; |
7 | use Psr\Http\Message\ResponseInterface; |
8 | use pvc\http\err\ClientRuntimeException; |
9 | use pvc\http\err\InvalidConnectionTimeoutException; |
10 | use pvc\http\err\InvalidHttpVerbException; |
11 | use pvc\interfaces\http\UrlInterface; |
12 | use Throwable; |
13 | |
14 | class HttpClient |
15 | { |
16 | protected int $connectionTimeoutInSeconds = 3; |
17 | |
18 | /** |
19 | * @var array<string> |
20 | */ |
21 | protected array $httpVerbs = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS', 'CONNECT', 'TRACE']; |
22 | |
23 | public function __construct(protected GuzzleClient $guzzleClient) |
24 | { |
25 | } |
26 | |
27 | /** |
28 | * @param int $connectionTimeoutInSeconds |
29 | * @return void |
30 | */ |
31 | public function setConnectionTimeout(int $connectionTimeoutInSeconds): void |
32 | { |
33 | if ($connectionTimeoutInSeconds < 1) { |
34 | throw new InvalidConnectionTimeoutException($connectionTimeoutInSeconds); |
35 | } |
36 | $this->connectionTimeoutInSeconds = $connectionTimeoutInSeconds; |
37 | } |
38 | |
39 | /** |
40 | * @return int |
41 | */ |
42 | public function getConnectionTimeout(): int |
43 | { |
44 | return $this->connectionTimeoutInSeconds; |
45 | } |
46 | |
47 | /** |
48 | * @param string $requestType |
49 | * @param UrlInterface $url |
50 | * @return ResponseInterface |
51 | * @throws ClientRuntimeException |
52 | */ |
53 | public function request(string $requestType, UrlInterface $url): ResponseInterface |
54 | { |
55 | $this->validateHttpVerb($requestType); |
56 | $request = new Request($requestType, $url->render()); |
57 | $options = ['timeout' => $this->connectionTimeoutInSeconds]; |
58 | |
59 | /** |
60 | * the request type is valid and the url is properly formed at this point. Any remaining problems are |
61 | * some variety of runtime exception..... |
62 | */ |
63 | try { |
64 | return $this->guzzleClient->send($request, $options); |
65 | } catch (Throwable $e) { |
66 | throw new ClientRuntimeException($url->render(), $e); |
67 | } |
68 | } |
69 | |
70 | protected function validateHttpVerb(string $httpVerb): void |
71 | { |
72 | if (!in_array($httpVerb, $this->httpVerbs)) { |
73 | throw new InvalidHttpVerbException($httpVerb); |
74 | } |
75 | } |
76 | } |