Use stream HTTP instead of curl; avoid blank line when adding keys
This commit is contained in:
parent
2c57cb8828
commit
7ea118c64e
1 changed files with 21 additions and 15 deletions
36
src/lib.php
36
src/lib.php
|
|
@ -103,28 +103,31 @@ function is_authorized(array $groups): bool
|
||||||
|
|
||||||
function http_request(string $method, string $url, array $fields = [], array $headers = []): array
|
function http_request(string $method, string $url, array $fields = [], array $headers = []): array
|
||||||
{
|
{
|
||||||
$ch = curl_init($url);
|
|
||||||
curl_setopt_array($ch, [
|
|
||||||
CURLOPT_RETURNTRANSFER => true,
|
|
||||||
CURLOPT_TIMEOUT => 15,
|
|
||||||
CURLOPT_HTTPHEADER => $headers,
|
|
||||||
]);
|
|
||||||
if ($method === 'POST') {
|
if ($method === 'POST') {
|
||||||
curl_setopt($ch, CURLOPT_POST, true);
|
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
|
||||||
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
|
}
|
||||||
|
$options = [
|
||||||
|
'http' => [
|
||||||
|
'method' => $method,
|
||||||
|
'header' => implode("\r\n", $headers),
|
||||||
|
'timeout' => 15,
|
||||||
|
'ignore_errors' => true,
|
||||||
|
],
|
||||||
|
];
|
||||||
|
if ($method === 'POST') {
|
||||||
|
$options['http']['content'] = http_build_query($fields);
|
||||||
}
|
}
|
||||||
$body = curl_exec($ch);
|
|
||||||
$code = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
|
|
||||||
$error = curl_error($ch);
|
|
||||||
curl_close($ch);
|
|
||||||
|
|
||||||
|
$body = @file_get_contents($url, false, stream_context_create($options));
|
||||||
if ($body === false) {
|
if ($body === false) {
|
||||||
throw new RuntimeException("Request to $url failed: $error");
|
throw new RuntimeException("Request to $url failed.");
|
||||||
}
|
}
|
||||||
if ($code >= 400) {
|
preg_match('#^HTTP/\S+\s+(\d{3})#', $http_response_header[0] ?? '', $m);
|
||||||
|
$code = (int) ($m[1] ?? 0);
|
||||||
|
if ($code >= 400 || $code === 0) {
|
||||||
throw new RuntimeException("Request to $url returned HTTP $code");
|
throw new RuntimeException("Request to $url returned HTTP $code");
|
||||||
}
|
}
|
||||||
$json = json_decode((string) $body, true);
|
$json = json_decode($body, true);
|
||||||
return is_array($json) ? $json : [];
|
return is_array($json) ? $json : [];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -194,6 +197,9 @@ function env_apply(string $content, array $changes, array $deletes): string
|
||||||
}
|
}
|
||||||
$out[] = $line;
|
$out[] = $line;
|
||||||
}
|
}
|
||||||
|
while ($out !== [] && end($out) === '') {
|
||||||
|
array_pop($out);
|
||||||
|
}
|
||||||
foreach ($changes as $key => $value) {
|
foreach ($changes as $key => $value) {
|
||||||
if (!isset($written[$key])) {
|
if (!isset($written[$key])) {
|
||||||
$out[] = $key . '=' . $value;
|
$out[] = $key . '=' . $value;
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue