117 lines
2.7 KiB
PHP
117 lines
2.7 KiB
PHP
<?php
|
|
// HttpRequestBuilder.php
|
|
// Created: 2022-02-08
|
|
// Updated: 2025-03-07
|
|
|
|
namespace Index\Http;
|
|
|
|
use InvalidArgumentException;
|
|
|
|
/**
|
|
* Represents a HTTP request message builder.
|
|
*/
|
|
final class HttpRequestBuilder extends HttpMessageBuilder {
|
|
/**
|
|
* Origin remote address.
|
|
*/
|
|
public string $remoteAddress = '::';
|
|
|
|
/**
|
|
* Origin ISO 3166 country code.
|
|
*/
|
|
public string $countryCode = 'XX';
|
|
|
|
/**
|
|
* HTTP request method.
|
|
*/
|
|
public string $method = 'GET';
|
|
|
|
/**
|
|
* Whether the request was made over HTTPS or not.
|
|
*/
|
|
public bool $secure = false;
|
|
|
|
/**
|
|
* HTTP request host.
|
|
*/
|
|
public string $host = '';
|
|
|
|
/**
|
|
* HTTP request path.
|
|
*/
|
|
public string $path = '/';
|
|
|
|
/**
|
|
* HTTP request query params.
|
|
*
|
|
* @var array<string, string[]>
|
|
*/
|
|
public array $params = [];
|
|
|
|
/**
|
|
* HTTP request cookies.
|
|
*
|
|
* @var array<string, string>
|
|
*/
|
|
public array $cookies = [];
|
|
|
|
/**
|
|
* Sets a HTTP request query param.
|
|
*
|
|
* @param string $name Name of the query field.
|
|
* @param string[] $value Value of the query field.
|
|
*/
|
|
public function setParam(string $name, array $value): void {
|
|
$this->params[$name] = $value;
|
|
}
|
|
|
|
/**
|
|
* Removes a HTTP request query param.
|
|
*
|
|
* @param string $name Name of the query field.
|
|
*/
|
|
public function removeParam(string $name): void {
|
|
unset($this->params[$name]);
|
|
}
|
|
|
|
/**
|
|
* Sets a HTTP request cookie.
|
|
*
|
|
* @param string $name Name of the cookie.
|
|
* @param string $value Value of the cookie.
|
|
*/
|
|
public function setCookie(string $name, string $value): void {
|
|
$this->cookies[$name] = $value;
|
|
}
|
|
|
|
/**
|
|
* Removes a HTTP request cookie.
|
|
*
|
|
* @param string $name Name of the cookie.
|
|
*/
|
|
public function removeCookie(string $name): void {
|
|
unset($this->cookies[$name]);
|
|
}
|
|
|
|
/**
|
|
* Creates a HttpRequest instance from this builder.
|
|
*
|
|
* @return HttpRequest An instance representing this builder.
|
|
*/
|
|
public function toRequest(): HttpRequest {
|
|
return new HttpRequest(
|
|
$this->protocolVersion, $this->headers, $this->body ?? NullStream::instance(),
|
|
[
|
|
HttpRequest::ATTR_COUNTRY_CODE => $this->countryCode,
|
|
HttpRequest::ATTR_REMOTE_ADDRESS => $this->remoteAddress,
|
|
],
|
|
$this->method,
|
|
new HttpUri(
|
|
scheme: $this->secure ? 'https' : 'http',
|
|
host: $this->host,
|
|
path: $this->path,
|
|
),
|
|
$this->params, $this->cookies,
|
|
);
|
|
}
|
|
}
|