Implement HTTP handling in GoogleWorkspaceToken class: add support for HTTP requests using streams when cURL is unavailable. Introduce private methods for cURL and stream handling, enhancing compatibility with environments lacking cURL support.

This commit is contained in:
2026-08-21 09:11:16 -04:00
parent b6aa436588
commit 728445e8ba

View File

@ -67,10 +67,25 @@ class GoogleWorkspaceToken
}
/**
* HTTP sans dépendre de lext curl (souvent absente en cPanel).
*
* @param list<string> $headers
* @return array{0:int,1:string}
*/
public function http(string $method, string $url, array $headers = [], ?string $body = null): array
{
if (\function_exists('curl_init')) {
return $this->httpCurl($method, $url, $headers, $body);
}
return $this->httpStream($method, $url, $headers, $body);
}
/**
* @param list<string> $headers
* @return array{0:int,1:string}
*/
private function httpCurl(string $method, string $url, array $headers, ?string $body): array
{
$ch = \curl_init($url);
$opts = [
@ -95,6 +110,60 @@ class GoogleWorkspaceToken
return [$code, $res];
}
/**
* @param list<string> $headers
* @return array{0:int,1:string}
*/
private function httpStream(string $method, string $url, array $headers, ?string $body): array
{
$headerLines = $headers;
if ($body !== null && $body !== '') {
$hasContentType = false;
foreach ($headerLines as $h) {
if (\stripos($h, 'Content-Type:') === 0) {
$hasContentType = true;
break;
}
}
if (! $hasContentType) {
$headerLines[] = 'Content-Type: application/x-www-form-urlencoded';
}
}
$opts = [
'http' => [
'method' => \strtoupper($method),
'header' => \implode("\r\n", $headerLines),
'timeout' => 60,
'ignore_errors' => true,
],
'ssl' => [
'verify_peer' => true,
'verify_peer_name' => true,
],
];
if ($body !== null) {
$opts['http']['content'] = $body;
}
$ctx = \stream_context_create($opts);
$res = @\file_get_contents($url, false, $ctx);
$code = 0;
if (isset($http_response_header) && \is_array($http_response_header)) {
foreach ($http_response_header as $line) {
if (\preg_match('#^HTTP/\S+\s+(\d+)#', $line, $m)) {
$code = (int) $m[1];
break;
}
}
}
if ($res === false) {
throw new \RuntimeException('HTTP stream error for ' . $url);
}
return [$code, $res];
}
private function b64url(string $data): string
{
return \rtrim(\strtr(\base64_encode($data), '+/', '-_'), '=');