Completed
Push — master ( ff5b0d...faa513 )
by Tobias
05:10 queued 02:50
created

HttpApi::httpGet()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 10
Ratio 100 %

Importance

Changes 0
Metric Value
dl 10
loc 10
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 3
1
<?php
2
3
namespace Happyr\ApiClient\Api;
4
5
use Happyr\ApiClient\Exception\Domain as DomainExceptions;
6
use Happyr\ApiClient\Exception\DomainException;
7
use Happyr\ApiClient\Hydrator\NoopHydrator;
8
use Http\Client\HttpClient;
9
use Happyr\ApiClient\Hydrator\Hydrator;
10
use Happyr\ApiClient\RequestBuilder;
11
use Http\Message\RequestFactory;
12
use Psr\Http\Message\ResponseInterface;
13
14
/**
15
 * @author Tobias Nyholm <[email protected]>
16
 */
17
abstract class HttpApi
18
{
19
    /**
20
     * @var HttpClient
21
     */
22
    protected $httpClient;
23
24
    /**
25
     * @var Hydrator
26
     */
27
    protected $hydrator;
28
29
    /**
30
     * @var RequestFactory
31
     */
32
    protected $requestFactory;
33
34
    /**
35
     * @param HttpClient     $httpClient
36
     * @param RequestFactory $requestFactory
37
     * @param Hydrator       $hydrator
38
     */
39
    public function __construct(HttpClient $httpClient, Hydrator $hydrator, RequestFactory $requestFactory)
40
    {
41
        $this->httpClient = $httpClient;
42
        $this->requestFactory = $requestFactory;
43
        if (!$hydrator instanceof NoopHydrator) {
44
            $this->hydrator = $hydrator;
45
        }
46
    }
47
48
    /**
49
     * @param ResponseInterface $response
50
     * @param string            $class
51
     *
52
     * @return mixed|ResponseInterface
53
     *
54
     * @throws \Exception
55
     */
56
    protected function hydrateResponse(ResponseInterface $response, $class)
57
    {
58
        if (!$this->hydrator) {
59
            return $response;
60
        }
61
62
        if ($response->getStatusCode() !== 200 && $response->getStatusCode() !== 201) {
63
            $this->handleErrors($response);
64
        }
65
66
        return $this->hydrator->hydrate($response, $class);
67
    }
68
69
    /**
70
     * Send a GET request with query parameters.
71
     *
72
     * @param string $path           Request path
73
     * @param array  $params         GET parameters
74
     * @param array  $requestHeaders Request Headers
75
     *
76
     * @return ResponseInterface
77
     */
78 View Code Duplication
    protected function httpGet($path, array $params = [], array $requestHeaders = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
79
    {
80
        if (count($params) > 0) {
81
            $path .= '?'.http_build_query($params);
82
        }
83
84
        return $this->httpClient->sendRequest(
85
            $this->requestFactory->createRequest('GET', $path, $requestHeaders)
86
        );
87
    }
88
89
    /**
90
     * Send a POST request with JSON-encoded parameters.
91
     *
92
     * @param string $path           Request path
93
     * @param array  $params         POST parameters to be JSON encoded
94
     * @param array  $requestHeaders Request headers
95
     *
96
     * @return ResponseInterface
97
     */
98
    protected function httpPost($path, array $params = [], array $requestHeaders = [])
99
    {
100
        $requestHeaders['Content-Type'] = 'application/x-www-form-urlencoded';
101
102
        return $this->httpPostRaw($path, http_build_query($params), $requestHeaders);
103
    }
104
105
    /**
106
     * Send a POST request with raw data.
107
     *
108
     * @param string       $path           Request path
109
     * @param array|string $body           Request body
110
     * @param array        $requestHeaders Request headers
111
     *
112
     * @return ResponseInterface
113
     */
114
    protected function httpPostRaw($path, $body, array $requestHeaders = [])
115
    {
116
        return $response = $this->httpClient->sendRequest(
0 ignored issues
show
Unused Code introduced by
$response is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
117
            $this->requestFactory->createRequest('POST', $path, $requestHeaders, $body)
0 ignored issues
show
Bug introduced by
It seems like $body defined by parameter $body on line 114 can also be of type array; however, Http\Message\RequestFactory::createRequest() does only seem to accept resource|string|object<P...e\StreamInterface>|null, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
118
        );
119
    }
120
121
    /**
122
     * Send a PUT request with JSON-encoded parameters.
123
     *
124
     * @param string $path           Request path
125
     * @param array  $params         POST parameters to be JSON encoded
126
     * @param array  $requestHeaders Request headers
127
     *
128
     * @return ResponseInterface
129
     */
130 View Code Duplication
    protected function httpPut($path, array $params = [], array $requestHeaders = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
131
    {
132
        $requestHeaders['Content-Type'] = 'application/x-www-form-urlencoded';
133
134
        return $this->httpClient->sendRequest(
135
            $this->requestFactory->createRequest('PUT', $path, $requestHeaders, http_build_query($params))
136
        );
137
    }
138
139
    /**
140
     * Send a DELETE request with JSON-encoded parameters.
141
     *
142
     * @param string $path           Request path
143
     * @param array  $params         POST parameters to be JSON encoded
144
     * @param array  $requestHeaders Request headers
145
     *
146
     * @return ResponseInterface
147
     */
148 View Code Duplication
    protected function httpDelete($path, array $params = [], array $requestHeaders = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
149
    {
150
        $requestHeaders['Content-Type'] = 'application/x-www-form-urlencoded';
151
152
        return $this->httpClient->sendRequest(
153
            $this->requestFactory->createRequest('DELETE', $path, $requestHeaders, http_build_query($params))
154
        );
155
    }
156
157
    /**
158
     * Handle HTTP errors.
159
     *
160
     * Call is controlled by the specific API methods.
161
     *
162
     * @param ResponseInterface $response
163
     *
164
     * @throws DomainException
165
     */
166
    protected function handleErrors(ResponseInterface $response)
167
    {
168
        switch ($response->getStatusCode()) {
169
            case 404:
170
                throw new DomainExceptions\NotFoundException();
171
            default:
172
                throw new DomainExceptions\UnknownErrorException();
173
        }
174
    }
175
}
176