-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApiConsumer.php
102 lines (89 loc) · 1.94 KB
/
ApiConsumer.php
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
<?php
use Exception as ClientException;
use Zttp\Zttp;
/**
* Class ApiConsumer
*/
class ApiConsumer {
private $client;
private $url;
private $username = '';
private $password = '';
/**
* Wps constructor.
* @param string $url
* @param string $username
* @param string $password
*/
public function __construct(string $url, string $username = '', string $password = '')
{
if ( $username !== '' ) {
$this->username = $username;
}
if ( $password !== '' ) {
$this->password = $password;
}
$token = $this->generateToken();
$this->client = Zttp::withHeaders(['Authorization' => 'Basic ' . $token]);
$this->url = $url;
}
/**
* @return string
*/
public function generateToken(): string
{
return base64_encode($this->username . ':' . $this->password);
}
/**
* @return array
* @throws Exception
*/
public function get(): array
{
// Send
$request = $this->client->get($this->url);
return $this->prepareResponse($request);
}
/**
* @param $response
* @return array
* @throws ClientException
*/
private function prepareResponse($response): array
{
if ($response->status() === 200) {
return $response->json();
}
throw new ClientException($response->status() . ': Invalid status code on response. Got: ' . $response->body());
}
/**
* Tacks on parameters to a url
* @param array $parameters
* @return self
*/
public function addGetParametersToUrl(array $parameters): self
{
$url = $this->url;
// No parameters? Go away.
if (empty($parameters)) {
return $url;
}
// Make sure our string is set up already to accept these
$url = trim($url, '&');
if (strpos($url, '?') === false) {
$url .= '?';
}
else {
$url .= '&';
}
// Loop through the parameters and stick em on
foreach ($parameters as $key => $value) {
if (\is_array($value)) {
$value = json_encode($value);
}
$url .= $key . '=' . $value . '&';
}
$this->url = $url;
return $this;
}
}