-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMakesHttpRequests.php
More file actions
68 lines (53 loc) · 1.82 KB
/
MakesHttpRequests.php
File metadata and controls
68 lines (53 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?php
declare(strict_types=1);
namespace RetroAchievements\Api;
use Psr\Http\Message\ResponseInterface;
use RetroAchievements\Api\Exceptions\GenericException;
use RetroAchievements\Api\Exceptions\NotFoundException;
use RetroAchievements\Api\Exceptions\UnauthorizedException;
trait MakesHttpRequests
{
protected function get(string $uri)
{
return $this->request('GET', $uri);
}
protected function post(string $uri, array $payload = [])
{
return $this->request('POST', $uri, $payload);
}
protected function put(string $uri, array $payload = [])
{
return $this->request('PUT', $uri, $payload);
}
protected function delete(string $uri, array $payload = [])
{
return $this->request('DELETE', $uri, $payload);
}
protected function request(string $verb, string $uri, array $payload = [])
{
$response = $this->client->request(
$verb,
$uri,
empty($payload) ? [] : ['form_params' => $payload]
);
if (! $this->isSuccessful($response)) {
$this->handleRequestError($response);
}
$responseBody = (string) $response->getBody();
return json_decode($responseBody, true) ?: $responseBody;
}
protected function isSuccessful(ResponseInterface $response): bool
{
return (int) substr((string) $response->getStatusCode(), 0, 1) === 2;
}
protected function handleRequestError(ResponseInterface $response): void
{
if ($response->getStatusCode() === 404) {
throw new NotFoundException((string) $response->getBody());
}
if ($response->getStatusCode() === 401) {
throw new UnauthorizedException((string) $response->getBody());
}
throw new GenericException((string) $response->getBody());
}
}