Bicycle/System/Classes/HTTP/Client/Curl.php
Egor Isaev b65603b4d0 dev
2026-06-23 10:44:18 +03:00

66 lines
1.8 KiB
PHP

<?php
/**
* @package Bicycle
* @author Egor Isaev
* @description HTTP/Client/Curl.php
* @copyright (c) 04/06/2026
*/
namespace System\Classes\HTTP\Client;
use RuntimeException;
/**
* Исполнитель исходящих HTTP-запросов через cURL.
*/
class Curl
{
/**
* Выполняет запрос и возвращает ответ.
*
* @param Request $request Подготовленный исходящий запрос
* @return Response
* @throws RuntimeException При ошибке cURL
*/
public function execute(Request $request): Response
{
$headers = [];
foreach ($request->getHeaders() as $name => $value) {
$headers[] = $name . ': ' . $value;
}
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $request->getUrl(),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_TIMEOUT => $request->getTimeout(),
CURLOPT_CONNECTTIMEOUT => 10,
]);
match ($request->getMethod()) {
'GET' => curl_setopt($ch, CURLOPT_HTTPGET, true),
'POST' => curl_setopt($ch, CURLOPT_POST, true),
default => curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $request->getMethod()),
};
if ($request->getBody() !== null) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $request->getBody());
}
$body = curl_exec($ch);
if ($body === false) {
$error = curl_error($ch);
curl_close($ch);
throw new RuntimeException('Curl error: ' . $error);
}
$status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return new Response($status, $body);
}
}