MakesHttpRequests   A
last analyzed

Complexity

Total Complexity 14

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 23
dl 0
loc 63
rs 10
c 2
b 0
f 0
wmc 14

7 Methods

Rating   Name   Duplication   Size   Complexity  
A put() 0 3 1
A request() 0 15 4
A post() 0 3 1
A get() 0 3 1
A isSuccessful() 0 7 2
A delete() 0 3 1
A handleRequestError() 0 15 4
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