-
-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathBaseEndpoint.php
More file actions
81 lines (65 loc) · 2.21 KB
/
BaseEndpoint.php
File metadata and controls
81 lines (65 loc) · 2.21 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
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
namespace Mvdnbrk\DhlParcel\Endpoints;
use Mvdnbrk\DhlParcel\Client;
use Mvdnbrk\DhlParcel\Contracts\ShouldAuthenticate;
use Mvdnbrk\DhlParcel\Exceptions\DhlParcelException;
abstract class BaseEndpoint
{
/** @var \Mvdnbrk\DhlParcel\Client */
protected $apiClient;
public function __construct(Client $client)
{
$this->apiClient = $client;
}
protected function buildQueryString(array $filters): string
{
if (empty($filters)) {
return '';
}
return '?'.http_build_query($filters);
}
protected function getRequestHeaders(array $headers): array
{
if ($this instanceof ShouldAuthenticate) {
$headers = array_merge($headers, [
'Authorization' => 'Bearer '.$this->apiClient->authentication->getAccessToken()->token,
]);
}
return $headers;
}
/**
* Perform a HTTP call to the API endpoint.
*
* @param string $httpMethod
* @param string $apiMethod
* @param string|null $httpBody
* @param array $requestHeaders
* @return string|object|null
*
* @throws \Mvdnbrk\DhlParcel\Exceptions\DhlParcelException
*/
protected function performApiCall(string $httpMethod, string $apiMethod, ?string $httpBody = null, array $requestHeaders = [])
{
$response = $this->apiClient->performHttpCall(
$httpMethod,
$apiMethod,
$httpBody,
$this->getRequestHeaders($requestHeaders)
);
if (collect($response->getHeader('Content-Type'))->first() == 'application/pdf') {
return $response->getBody()->getContents();
}
if ($response->getStatusCode() == 401) {
throw new DhlParcelException('Authentication failed', 0, $response);
}
$body = $response->getBody()->getContents();
$object = @json_decode($body);
if (json_last_error() != JSON_ERROR_NONE) {
throw new DhlParcelException("Unable to decode DHL Parcel response: '{$body}'.");
}
if ($response->getStatusCode() >= 400) {
throw DhlParcelException::createFromResponse($response);
}
return $object;
}
}