forked from skylerkatz/hover
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ApiGateway.php
62 lines (50 loc) · 1.79 KB
/
ApiGateway.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
<?php
use hollodotme\FastCGI\Interfaces\ProvidesResponseData;
use Illuminate\Support\Str;
class ApiGateway
{
public function transformResponse(ProvidesResponseData $response): array
{
[$headers, $cookies] = $this->extractHeadersAndCookies($response->getHeaders());
$requiresEncoding = $this->isBase64EncodingRequired($headers);
return [
'cookies' => $cookies,
'isBase64Encoded' => $requiresEncoding,
'statusCode' => $this->getStatusFromHeaders($headers),
'headers' => $headers,
'body' => $requiresEncoding
? base64_encode($response->getBody())
: $response->getBody(),
];
}
private function extractHeadersAndCookies(array $incomingHeaders): array
{
$headers = [];
$cookies = [];
foreach ($incomingHeaders as $name => $values) {
$name = str_replace(' ', '-', ucwords(str_replace('-', ' ', $name)));
if ($name === 'Set-Cookie') {
$cookies = is_array($values) ? $values : [$values];
} else {
$headers[$name] = is_array($values) ? end($values) : $values;
}
}
return [$headers, $cookies];
}
private function getStatusFromHeaders(array $headers): int
{
$headers = array_change_key_case($headers, CASE_LOWER);
return isset($headers['status'])
? (int) explode(' ', $headers['status'])[0]
: 200;
}
public static function isBase64EncodingRequired($headers): bool
{
$contentType = $headers['Content-Type'] ?? 'text/html';
if (Str::startsWith($contentType, 'text/') ||
Str::contains($contentType, ['xml', 'json'])) {
return false;
}
return true;
}
}