1 | <?php |
||
11 | trait MakesHttpRequests |
||
12 | { |
||
13 | /** |
||
14 | * @param string $uri |
||
15 | * |
||
16 | * @return mixed |
||
17 | */ |
||
18 | protected function get(string $uri) |
||
19 | { |
||
20 | return $this->request('GET', $uri); |
||
21 | } |
||
22 | |||
23 | /** |
||
24 | * @param string $uri |
||
25 | * @param array $payload |
||
26 | * |
||
27 | * @return mixed |
||
28 | */ |
||
29 | protected function post(string $uri, array $payload = []) |
||
30 | { |
||
31 | return $this->request('POST', $uri, $payload); |
||
32 | } |
||
33 | |||
34 | /** |
||
35 | * @param string $uri |
||
36 | * @param array $payload |
||
37 | * |
||
38 | * @return mixed |
||
39 | */ |
||
40 | protected function put(string $uri, array $payload = []) |
||
41 | { |
||
42 | return $this->request('PUT', $uri, $payload); |
||
43 | } |
||
44 | |||
45 | /** |
||
46 | * @param string $uri |
||
47 | * @param array $payload |
||
48 | * |
||
49 | * @return mixed |
||
50 | */ |
||
51 | protected function delete(string $uri, array $payload = []) |
||
52 | { |
||
53 | return $this->request('DELETE', $uri, $payload); |
||
54 | } |
||
55 | |||
56 | /** |
||
57 | * @param string $verb |
||
58 | * @param string $uri |
||
59 | * @param array $payload |
||
60 | * |
||
61 | * @return mixed |
||
62 | */ |
||
63 | protected function request(string $verb, string $uri, array $payload = []) |
||
64 | { |
||
65 | $response = $this->client->request($verb, $uri, |
||
66 | empty($payload) ? [] : ['form_params' => $payload] |
||
67 | ); |
||
68 | |||
69 | if (subtr($response->getStatusCode(), 0, 1)) != 2) { |
||
|
|||
70 | return $this->handleRequestError($response); |
||
71 | } |
||
72 | |||
73 | $responseBody = (string) $response->getBody(); |
||
74 | |||
75 | return json_decode($responseBody, true) ?: $responseBody; |
||
76 | } |
||
77 | |||
78 | protected function handleRequestError(ResponseInterface $response) |
||
79 | { |
||
80 | if ($response->getStatusCode() === 422) { |
||
81 | throw new ValidationException(json_decode((string) $response->getBody(), true)); |
||
82 | } |
||
83 | |||
84 | if ($response->getStatusCode() === 404) { |
||
85 | throw new NotFoundException(); |
||
86 | } |
||
87 | |||
88 | if ($response->getStatusCode() === 400) { |
||
89 | throw new FailedActionException((string) $response->getBody()); |
||
90 | } |
||
91 | |||
92 | throw new Exception((string) $response->getBody()); |
||
93 | } |
||
94 | } |
||
95 |