MakesHttpRequests::handleRequestError()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 7
nc 4
nop 1
dl 0
loc 15
rs 10
c 1
b 0
f 0
1
<?php
2
3
namespace OhDear\PhpSdk;
4
5
use Exception;
6
use OhDear\PhpSdk\Exceptions\FailedActionException;
7
use OhDear\PhpSdk\Exceptions\NotFoundException;
8
use OhDear\PhpSdk\Exceptions\ValidationException;
9
use Psr\Http\Message\ResponseInterface;
10
11
trait MakesHttpRequests
12
{
13
    protected function get(string $uri)
14
    {
15
        return $this->request('GET', $uri);
16
    }
17
18
    protected function post(string $uri, array $payload = [])
19
    {
20
        return $this->request('POST', $uri, $payload);
21
    }
22
23
    protected function put(string $uri, array $payload = [])
24
    {
25
        return $this->request('PUT', $uri, $payload);
26
    }
27
28
    protected function delete(string $uri, array $payload = [])
29
    {
30
        return $this->request('DELETE', $uri, $payload);
31
    }
32
33
    protected function request(string $verb, string $uri, array $payload = [])
34
    {
35
        $response = $this->client->request(
36
            $verb,
37
            $uri,
38
            empty($payload) ? [] : ['form_params' => $payload]
39
        );
40
41
        if (! $this->isSuccessful($response)) {
42
            return $this->handleRequestError($response);
43
        }
44
45
        $responseBody = (string) $response->getBody();
46
47
        return json_decode($responseBody, true) ?: $responseBody;
48
    }
49
50
    public function isSuccessful($response): bool
51
    {
52
        if (! $response) {
53
            return false;
54
        }
55
56
        return (int) substr($response->getStatusCode(), 0, 1) === 2;
57
    }
58
59
    protected function handleRequestError(ResponseInterface $response): void
60
    {
61
        if ($response->getStatusCode() === 422) {
62
            throw new ValidationException(json_decode((string) $response->getBody(), true));
63
        }
64
65
        if ($response->getStatusCode() === 404) {
66
            throw new NotFoundException();
67
        }
68
69
        if ($response->getStatusCode() === 400) {
70
            throw new FailedActionException((string) $response->getBody());
71
        }
72
73
        throw new Exception((string) $response->getBody());
74
    }
75
}
76