-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathAdapter.php
More file actions
208 lines (170 loc) · 5.14 KB
/
Copy pathAdapter.php
File metadata and controls
208 lines (170 loc) · 5.14 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
<?php
namespace Utopia\Analytics;
use Exception;
abstract class Adapter
{
protected bool $enabled = true;
/**
* Useragent to use for requests
*/
protected string $userAgent = 'Utopia PHP Framework';
/**
* The IP address to forward to Plausible
*/
protected string $clientIP;
/**
* Endpoint
*/
protected string $endpoint;
/**
* Gets the name of the adapter.
*/
abstract public function getName(): string;
/**
* Global Headers
*
* @var array
*/
protected $headers = [
'Content-Type' => '',
];
/**
* Enables tracking for this instance.
*/
public function enable(): void
{
$this->enabled = true;
}
/**
* Disables tracking for this instance.
*/
public function disable(): void
{
$this->enabled = false;
}
/**
* Send the event to the adapter.
*/
abstract public function send(Event $event): bool;
/**
* Validate the adapter.
* Sends a test event to the adapter and validates if it was received.
*
* Throws an exception if the adapter is not valid.
*
* @throws Exception
*/
abstract public function validate(Event $event): bool;
/**
* Sets the client IP address.
*
* @param string $clientIP The IP address to use.
*/
public function setClientIP(string $clientIP): self
{
$this->clientIP = $clientIP;
return $this;
}
/**
* Sets the client user agent.
*
* @param string $userAgent The user agent to use.
*/
public function setUserAgent(string $userAgent): self
{
$this->userAgent = $userAgent;
return $this;
}
/**
* Creates an Event on the remote analytics platform.
*/
public function createEvent(Event $event): bool
{
return $this->send($event);
}
/**
* Call
*
* Make an API call
*
*
* @throws \Exception
*/
public function call(string $method, string $path = '', array $headers = [], array $params = []): array|string
{
$headers = array_merge($this->headers, $headers);
$ch = curl_init((str_contains($path, 'http') ? $path : $this->endpoint.$path.(($method == 'GET' && ! empty($params)) ? '?'.http_build_query($params) : '')));
$responseHeaders = [];
$responseStatus = -1;
$responseType = '';
$responseBody = '';
switch ($headers['Content-Type']) {
case 'application/json':
$query = json_encode($params);
break;
case 'multipart/form-data':
$query = $this->flatten($params);
break;
default:
$query = http_build_query($params);
break;
}
foreach ($headers as $i => $header) {
$headers[] = $i.':'.$header;
unset($headers[$i]);
}
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, php_uname('s').'-'.php_uname('r').':php-'.phpversion());
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, function ($curl, $header) use (&$responseHeaders) {
$len = strlen($header);
$header = explode(':', strtolower($header), 2);
if (count($header) < 2) { // ignore invalid headers
return $len;
}
$responseHeaders[strtolower(trim($header[0]))] = trim($header[1]);
return $len;
});
if ($method != 'GET') {
curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
}
$responseBody = curl_exec($ch);
$responseType = $responseHeaders['Content-Type'] ?? '';
$responseStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
switch (substr($responseType, 0, strpos($responseType, ';'))) {
case 'application/json':
$responseBody = json_decode($responseBody, true);
break;
}
if (curl_errno($ch)) {
throw new \Exception(curl_error($ch), $responseStatus);
}
curl_close($ch);
if ($responseStatus >= 400) {
if (is_array($responseBody)) {
throw new \Exception(json_encode($responseBody), $responseStatus);
} else {
throw new \Exception($responseStatus.': '.$responseBody, $responseStatus);
}
}
return $responseBody;
}
/**
* Flatten params array to PHP multiple format
*/
protected function flatten(array $data, string $prefix = ''): array
{
$output = [];
foreach ($data as $key => $value) {
$finalKey = $prefix ? "{$prefix}[{$key}]" : $key;
if (is_array($value)) {
$output += $this->flatten($value, $finalKey); // @todo: handle name collision here if needed
} else {
$output[$finalKey] = $value;
}
}
return $output;
}
}