Completed
Push — master ( 3cb300...cba459 )
by Tobias
03:38
created

HttpApi::httpPut()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 8
Ratio 100 %

Importance

Changes 0
Metric Value
dl 8
loc 8
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
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\Hydrator;
8
use Happyr\ApiClient\Hydrator\NoopHydrator;
9
use Http\Client\HttpClient;
10
use Http\Message\RequestFactory;
11
use Psr\Http\Message\ResponseInterface;
12
13
/**
14
 * @author Tobias Nyholm <[email protected]>
15
 */
16
abstract class HttpApi
17
{
18
    /**
19
     * @var HttpClient
20
     */
21
    protected $httpClient;
22
23
    /**
24
     * @var Hydrator
25
     */
26
    protected $hydrator;
27
28
    /**
29
     * @var RequestFactory
30
     */
31
    protected $requestFactory;
32
33
    /**
34
     * @param HttpClient     $httpClient
35
     * @param RequestFactory $requestFactory
36
     * @param Hydrator       $hydrator
37
     */
38
    public function __construct(HttpClient $httpClient, Hydrator $hydrator, RequestFactory $requestFactory)
39
    {
40
        $this->httpClient = $httpClient;
41
        $this->requestFactory = $requestFactory;
42
        if (!$hydrator instanceof NoopHydrator) {
43
            $this->hydrator = $hydrator;
44
        }
45
    }
46
47
    /**
48
     * @param ResponseInterface $response
49
     * @param string            $class
50
     *
51
     * @throws \Exception
52
     *
53
     * @return mixed|ResponseInterface
54
     */
55
    protected function hydrateResponse(ResponseInterface $response, $class)
56
    {
57
        if (!$this->hydrator) {
58
            return $response;
59
        }
60
61
        if ($response->getStatusCode() !== 200 && $response->getStatusCode() !== 201) {
62
            $this->handleErrors($response);
63
        }
64
65
        return $this->hydrator->hydrate($response, $class);
66
    }
67
68
    /**
69
     * Send a GET request with query parameters.
70
     *
71
     * @param string $path           Request path
72
     * @param array  $params         GET parameters
73
     * @param array  $requestHeaders Request Headers
74
     *
75
     * @return ResponseInterface
76
     */
77 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...
78
    {
79
        if (count($params) > 0) {
80
            $path .= '?'.http_build_query($params);
81
        }
82
83
        return $this->httpClient->sendRequest(
84
            $this->requestFactory->createRequest('GET', $path, $requestHeaders)
85
        );
86
    }
87
88
    /**
89
     * Send a POST request with JSON-encoded parameters.
90
     *
91
     * @param string $path           Request path
92
     * @param array  $params         POST parameters to be JSON encoded
93
     * @param array  $requestHeaders Request headers
94
     *
95
     * @return ResponseInterface
96
     */
97
    protected function httpPost($path, array $params = [], array $requestHeaders = [])
98
    {
99
        $requestHeaders['Content-Type'] = 'application/x-www-form-urlencoded';
100
101
        return $this->httpPostRaw($path, http_build_query($params), $requestHeaders);
102
    }
103
104
    /**
105
     * Send a POST request with raw data.
106
     *
107
     * @param string       $path           Request path
108
     * @param array|string $body           Request body
109
     * @param array        $requestHeaders Request headers
110
     *
111
     * @return ResponseInterface
112
     */
113
    protected function httpPostRaw($path, $body, array $requestHeaders = [])
114
    {
115
        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...
116
            $this->requestFactory->createRequest('POST', $path, $requestHeaders, $body)
0 ignored issues
show
Bug introduced by
It seems like $body defined by parameter $body on line 113 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...
117
        );
118
    }
119
120
    /**
121
     * Send a PUT request with JSON-encoded parameters.
122
     *
123
     * @param string $path           Request path
124
     * @param array  $params         POST parameters to be JSON encoded
125
     * @param array  $requestHeaders Request headers
126
     *
127
     * @return ResponseInterface
128
     */
129 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...
130
    {
131
        $requestHeaders['Content-Type'] = 'application/x-www-form-urlencoded';
132
133
        return $this->httpClient->sendRequest(
134
            $this->requestFactory->createRequest('PUT', $path, $requestHeaders, http_build_query($params))
135
        );
136
    }
137
138
    /**
139
     * Send a DELETE request with JSON-encoded parameters.
140
     *
141
     * @param string $path           Request path
142
     * @param array  $params         POST parameters to be JSON encoded
143
     * @param array  $requestHeaders Request headers
144
     *
145
     * @return ResponseInterface
146
     */
147 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...
148
    {
149
        $requestHeaders['Content-Type'] = 'application/x-www-form-urlencoded';
150
151
        return $this->httpClient->sendRequest(
152
            $this->requestFactory->createRequest('DELETE', $path, $requestHeaders, http_build_query($params))
153
        );
154
    }
155
156
    /**
157
     * Handle HTTP errors.
158
     *
159
     * Call is controlled by the specific API methods.
160
     *
161
     * @param ResponseInterface $response
162
     *
163
     * @throws DomainException
164
     */
165
    protected function handleErrors(ResponseInterface $response)
166
    {
167
        $statusCode = $response->getStatusCode();
168
        switch ($statusCode) {
169
            case 400:
170
                throw DomainExceptions\HttpClientException::badRequest($response);
171
            case 401:
172
                throw DomainExceptions\HttpClientException::unauthorized($response);
173
            case 402:
174
                throw DomainExceptions\HttpClientException::requestFailed($response);
175
            case 404:
176
                throw DomainExceptions\HttpClientException::notFound($response);
177
            case 500 <= $statusCode:
178
                throw DomainExceptions\HttpServerException::serverError($statusCode);
179
            default:
180
                throw new DomainExceptions\UnknownErrorException();
181
        }
182
    }
183
}
184