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

116 lines
3.1 KiB
PHP

<?php
/**
* @package Bicycle
* @author Egor Isaev
* @description HTTP/Client/Request.php
* @copyright (c) 04/06/2026
*/
namespace System\Classes\HTTP\Client;
/**
* Билдер исходящего HTTP-запроса (fluent-интерфейс).
*/
class Request
{
/** @var string HTTP-метод */
private string $method = 'GET';
/** @var string Целевой URL */
private string $url;
/** @var array<string,string> Заголовки запроса */
private array $headers = [];
/** @var string|null Тело запроса */
private ?string $body = null;
/** @var int Таймаут в секундах */
private int $timeout = 30;
/**
* @param string $url Целевой URL
*/
public function __construct(string $url)
{
$this->url = $url;
}
/**
* Создаёт новый билдер запроса.
*
* @param string $url Целевой URL
* @return static
*/
public static function factory(string $url): static
{
return new static($url);
}
/**
* @param string $method HTTP-метод
* @return static
*/
public function method(string $method): static
{
$this->method = strtoupper($method);
return $this;
}
/**
* Добавляет заголовок.
*
* @param string $name Имя заголовка
* @param string $value Значение
* @return static
*/
public function header(string $name, string $value): static
{
$this->headers[$name] = $value;
return $this;
}
/**
* Устанавливает сырое тело запроса.
*
* @param string $body Тело
* @return static
*/
public function body(string $body): static
{
$this->body = $body;
return $this;
}
/**
* Устанавливает JSON-тело и соответствующие заголовки.
*
* @param array $data Данные для кодирования в JSON
* @return static
*/
public function json(array $data): static
{
$this->header('Content-Type', 'application/json');
$this->header('Accept', 'application/json');
$this->body = json_encode($data, JSON_UNESCAPED_UNICODE);
return $this;
}
/**
* @param int $seconds Таймаут в секундах
* @return static
*/
public function timeout(int $seconds): static
{
$this->timeout = $seconds;
return $this;
}
/** @return string HTTP-метод */
public function getMethod(): string { return $this->method; }
/** @return string Целевой URL */
public function getUrl(): string { return $this->url; }
/** @return array<string,string> Заголовки */
public function getHeaders(): array { return $this->headers; }
/** @return string|null Тело запроса */
public function getBody(): ?string { return $this->body; }
/** @return int Таймаут в секундах */
public function getTimeout(): int { return $this->timeout; }
}