-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpStreamWrapperClient.php
More file actions
113 lines (93 loc) · 2.94 KB
/
HttpStreamWrapperClient.php
File metadata and controls
113 lines (93 loc) · 2.94 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
<?php
declare(strict_types=1);
namespace Marein\Nchan\HttpAdapter;
use Marein\Nchan\Exception\NchanException;
use Marein\Nchan\Http\Client;
use Marein\Nchan\Http\Request;
use Marein\Nchan\Http\Response;
final class HttpStreamWrapperClient implements Client
{
private Credentials $credentials;
public function __construct(Credentials $credentials)
{
$this->credentials = $credentials;
}
public static function withDefaults(): HttpStreamWrapperClient
{
return new self(
new WithoutAuthenticationCredentials()
);
}
public function get(Request $request): Response
{
return $this->request('GET', $request);
}
public function post(Request $request): Response
{
return $this->request('POST', $request);
}
public function delete(Request $request): Response
{
return $this->request('DELETE', $request);
}
/**
* @throws NchanException
*/
private function request(string $method, Request $request): Response
{
$request = $this->credentials->authenticate($request);
$url = $request->url()->toString();
$headers = $request->headers();
$body = $request->body();
$options = [
'http' =>
[
'method' => $method,
'header' => $this->prepareHeadersForStreamContext($headers),
'content' => $body,
'ignore_errors' => true
]
];
$context = stream_context_create($options);
// Suppress errors for file_get_contents. We will analyze this ourselves.
$errorReportingLevelBeforeFileGetContents = error_reporting(0);
$responseBody = file_get_contents(
$url,
false,
$context
);
error_reporting($errorReportingLevelBeforeFileGetContents);
if ($responseBody === false) {
throw new NchanException(
error_get_last()['message'] ?? 'Unable to connect to ' . $url . '.'
);
}
$responseHeaders = (PHP_VERSION_ID >= 80500
? http_get_last_response_headers()
: $http_response_header) ?? [];
return HttpStreamWrapperResponse::fromResponse($responseHeaders, $responseBody);
}
/**
* Transforms the array from
* [
* 'firstHeaderName' => 'firstHeaderValue',
* 'secondHeaderName' => 'secondHeaderValue'
* ]
* to string
* "firstHeaderName: firstHeaderValue\r\n
* secondHeaderName: secondHeaderValue".
*
* @param array<string, string> $headers
*/
private function prepareHeadersForStreamContext(array $headers): string
{
return implode(
"\r\n",
array_map(
static fn(string $name, string $value) => $name . ': ' . $value,
array_keys($headers),
$headers
)
);
}
}