rafalmasiarek / http-client
Lazy, concurrent curl-based HTTP client with DNS pinning, retry, SSE, caching, and rate limiting — extracted from rafalmasiarek/dashboard-kit.
Requires
- php: >=8.2
- psr/log: ^3.0
- rafalmasiarek/dns-resolver: ^0.2.0
Requires (Dev)
None
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-17 23:37:41 UTC
README
Lazy, concurrent curl-based HTTP client with DNS pinning, retry, SSE, caching, and rate limiting — extracted from dashboard-kit.
License
The MIT License (MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files, to deal in the Software
without restriction.
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.
Source: https://opensource.org/licenses/MIT
Authors
Index
Classes
CachingHttpClient—rafalmasiarek\HttpClient\HttpChunkedFileDownloader—rafalmasiarek\HttpClient\HttpCurlHttpClient—rafalmasiarek\HttpClient\HttpCurlResponse—rafalmasiarek\HttpClient\HttpDefaultRetryStrategy—rafalmasiarek\HttpClient\HttpDownloadException—rafalmasiarek\HttpClient\HttpEventSourceClient—rafalmasiarek\HttpClient\HttpFileHttpCacheStore—rafalmasiarek\HttpClient\HttpHttpResponse—rafalmasiarek\HttpClient\HttpHttpTransportDebug—rafalmasiarek\HttpClient\HttpRetryHttpClient—rafalmasiarek\HttpClient\HttpServerSentEvent—rafalmasiarek\HttpClient\HttpThrottlingHttpClient—rafalmasiarek\HttpClient\Http
Interfaces
HttpCacheStoreInterface—rafalmasiarek\HttpClient\HttpHttpClientInterface—rafalmasiarek\HttpClient\HttpHttpResponseInterface—rafalmasiarek\HttpClient\HttpRetryStrategyInterface—rafalmasiarek\HttpClient\Http
Enums
TransportErrorKind—rafalmasiarek\HttpClient\Http
CachingHttpClient
final class — rafalmasiarek\HttpClient\Http\CachingHttpClient · source
Decorates an HttpClientInterface with a practical subset of RFC 9111: freshness via Cache-Control max-age/Expires, revalidation via ETag/Last-Modified once stale. Only GET/HEAD are cached. Out of scope: Vary support, stale-while-revalidate/stale-if-error, request collapsing. No usable freshness lifetime (no max-age, no Expires) means not cacheable — no guessed default TTL.
implements HttpClientInterface
Depends on: HttpCacheStoreInterface
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | — | — |
request() |
public | HttpResponseInterface |
— |
fromCachedEntry() |
private | HttpResponseInterface |
— |
fetchAndMaybeCache() |
private | HttpResponseInterface |
— |
computeTtl() |
private | int|null |
— |
cacheKey() |
private | string |
— |
__construct()
CachingHttpClient __construct()
public function __construct(HttpClientInterface $client, HttpCacheStoreInterface $store, int $maxTtl)
| Param | Type | Description |
|---|---|---|
$client |
HttpClientInterface |
Underlying transport. |
$store |
HttpCacheStoreInterface |
Where cached entries are persisted. |
$maxTtl |
int |
Upper bound on any computed freshness lifetime, in seconds. |
request()
CachingHttpClient request()
public function request(string $method, string $url, array $options): HttpResponseInterface
| Param | Type | Description |
|---|---|---|
$method |
string |
— |
$url |
string |
— |
$options |
array<string, mixed> |
— |
Returns: HttpResponseInterface
fromCachedEntry()
CachingHttpClient fromCachedEntry()
private function fromCachedEntry(array $entry): HttpResponseInterface
| Param | Type | Description |
|---|---|---|
$entry |
array<string, mixed> |
— |
Returns: HttpResponseInterface
fetchAndMaybeCache()
CachingHttpClient fetchAndMaybeCache()
private function fetchAndMaybeCache(string $method, string $url, array $options, string $key, ?array $stale): HttpResponseInterface
| Param | Type | Description |
|---|---|---|
$method |
string |
— |
$url |
string |
— |
$options |
array<string, mixed> |
— |
$key |
string |
— |
$stale |
array<string, mixed>|null |
Expired entry whose validators can be sent for revalidation. |
Returns: HttpResponseInterface
computeTtl()
CachingHttpClient computeTtl()
private function computeTtl(HttpResponseInterface $response): ?int
| Param | Type | Description |
|---|---|---|
$response |
HttpResponseInterface |
— |
Returns: int\|null — Null when the response gives no usable freshness lifetime (no max-age, no Expires) or explicitly forbids storage (Cache-Control: no-store/private).
cacheKey()
CachingHttpClient cacheKey()
private function cacheKey(string $method, string $url): string
| Param | Type | Description |
|---|---|---|
$method |
string |
— |
$url |
string |
— |
Returns: string
ChunkedFileDownloader
final class — rafalmasiarek\HttpClient\Http\ChunkedFileDownloader · source
Downloads a large file in range-requested chunks, retrying failed chunks individually instead of restarting the whole transfer, and resuming from an existing partial download when the destination already has one. Writes to a "{destination}.part" sidecar and only renames it onto the real destination once the transfer completes successfully — a reader can never observe a truncated file at the destination path. A resume is only trusted when a "{destination}.part.meta" sidecar recorded the source's ETag/Last-Modified from the response that started the partial file. Without it (missing, or an older download that predates this file), the partial is discarded and the download restarts from scratch — resuming an unvalidated partial risks silently splicing bytes from two different versions of the resource into one corrupt file. When a validated resume gets a 200 back instead of 206 (server ignored If-Range because the resource changed, or doesn't support Range at all), the partial and its metadata are discarded and the download restarts once, from that response. Falls back to a single, unranged request when the server ignores the Range header on a fresh (offset 0) download — a server that can't resume mid-download can't be resumed at all.
Depends on: HttpClientInterface
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | — | — |
download() |
public | void |
Downloads $url to $destinationPath. |
attempt() |
private | void |
Runs one download pass against $partPath, restarting itself exactly once (via $restarted) when a trusted resume turns out to be invalid. |
fetchChunkWithRetry() |
private | HttpResponseInterface |
Fetches one chunk, retrying on transport failure. |
parseTotalSize() |
private | int|null |
Extracts the total resource size from a Content-Range header value ("bytes start-end/total"). |
readIfRange() |
private | string|null |
Reads the If-Range validator persisted for an existing partial download. |
writeIfRange() |
private | string|null |
Persists the ETag/Last-Modified from a chunk response as the resume validator, preferring ETag. Returns null (and writes nothing) when neither is present — a resume after a crash for such a resource is never trusted, only completing the current, uninterrupted process is possible. |
__construct()
ChunkedFileDownloader __construct()
public function __construct(HttpClientInterface $http, int $chunkSize, int $maxRetriesPerChunk)
| Param | Type | Description |
|---|---|---|
$http |
HttpClientInterface |
Client used to fetch each chunk. |
$chunkSize |
int |
Bytes requested per range, e.g. 8 MiB. |
$maxRetriesPerChunk |
int |
Attempts per chunk before giving up. |
download()
ChunkedFileDownloader download()
public function download(string $url, string $destinationPath, array $requestOptions): void
Downloads $url to $destinationPath.
| Param | Type | Description |
|---|---|---|
$url |
string |
Absolute URL. |
$destinationPath |
string |
Final file path; a same-directory ".part" sidecar is used during the transfer and atomically renamed onto this path only once it completes successfully. |
$requestOptions |
array<string, mixed> |
Extra HttpClientInterface::request() options (e.g. headers, timeout, local_cert) merged into every chunk request. 'Range'/'If-Range' headers, if present, are overridden per chunk. |
| Throws | When |
|---|---|
DownloadException |
On a write failure, an unexpected status code, a server that can't resume a partial download, or a chunk that exhausts its retries. |
attempt()
ChunkedFileDownloader attempt()
private function attempt(string $url, string $partPath, string $metaPath, array $requestOptions, bool $restarted): void
Runs one download pass against $partPath, restarting itself exactly once (via $restarted) when a trusted resume turns out to be invalid.
| Param | Type | Description |
|---|---|---|
$url |
string |
— |
$partPath |
string |
— |
$metaPath |
string |
— |
$requestOptions |
array<string, mixed> |
— |
$restarted |
bool |
Whether this call is already a post-restart retry. |
| Throws | When |
|---|---|
DownloadException |
— |
fetchChunkWithRetry()
ChunkedFileDownloader fetchChunkWithRetry()
private function fetchChunkWithRetry(string $url, array $options): HttpResponseInterface
Fetches one chunk, retrying on transport failure.
| Param | Type | Description |
|---|---|---|
$url |
string |
— |
$options |
array<string, mixed> |
Already carries the Range/If-Range headers for this chunk. |
Returns: HttpResponseInterface
| Throws | When |
|---|---|
DownloadException |
When every attempt fails. |
parseTotalSize()
ChunkedFileDownloader parseTotalSize()
private function parseTotalSize(string $contentRange): ?int
Extracts the total resource size from a Content-Range header value ("bytes start-end/total").
| Param | Type | Description |
|---|---|---|
$contentRange |
string |
— |
Returns: int\|null
readIfRange()
ChunkedFileDownloader readIfRange()
private function readIfRange(string $metaPath): ?string
Reads the If-Range validator persisted for an existing partial download.
| Param | Type | Description |
|---|---|---|
$metaPath |
string |
— |
Returns: string\|null — The ETag or Last-Modified value to send as If-Range, or null when no (trustworthy) validator was recorded.
writeIfRange()
ChunkedFileDownloader writeIfRange()
private function writeIfRange(string $metaPath, HttpResponseInterface $response): ?string
Persists the ETag/Last-Modified from a chunk response as the resume validator, preferring ETag. Returns null (and writes nothing) when neither is present — a resume after a crash for such a resource is never trusted, only completing the current, uninterrupted process is possible.
| Param | Type | Description |
|---|---|---|
$metaPath |
string |
— |
$response |
HttpResponseInterface |
— |
Returns: string\|null
CurlHttpClient
final class — rafalmasiarek\HttpClient\Http\CurlHttpClient · source
curl-based HttpClientInterface implementation. Resolves hostnames via an injected DnsResolverInterface and pins the result with CURLOPT_RESOLVE instead of curl's own DNS. A failed resolve falls back to curl's own resolution, except under 'block_private_network' (see buildHandle()), where an unconfirmed target is treated as unsafe. request() returns a lazy CurlResponse (see HttpResponseInterface). Every response from one client instance shares one curl_multi handle, created lazily; CurlResponse drives it on first access. Redirects are followed by CurlResponse itself, one hop at a time, so credential headers get stripped and the private-network check re-run on every hop, not just the first.
implements HttpClientInterface
Depends on: DnsResolverInterface, \CurlMultiHandle
| Property | Type | Visibility | Description |
|---|---|---|---|
$multi |
\CurlMultiHandle|null |
private | Lazily created; shared by every CurlResponse this client produces. |
$pending |
array<int, CurlResponse> |
private | In-flight responses, keyed by spl_object_id() of their current curl handle. |
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | — | — |
request() |
public | HttpResponseInterface |
Extra $options beyond HttpClientInterface::request(): 'follow_redirects' (bool, default true); 'block_private_network' (bool, default false), re-checked on every redirect hop; 'max_connect_duration' (float seconds) — connect phase only, separate from 'timeout'; 'on_progress' (callable(int $dlNow, int $dlSize, array $info): void), called periodically — a thrown exception aborts the transfer (see getError()). |
buildHandle() |
public | \CurlHandle|null |
Builds one hop's curl handle, wiring its header/body callbacks to write directly into $forResponse. Returns null (after marking $forResponse done via _completeBlocked()) when block_private_network refuses the target — there's no handle to register in that case. |
registerHandle() |
public | void |
— |
forget() |
public | void |
— |
pumpUntilDone() |
public | void |
Drives the shared curl_multi handle until $target's current hop finishes. Every other pending handle advances in the same loop — that's the concurrency. |
finishOne() |
private | void |
— |
multi() |
private | \CurlMultiHandle |
— |
resolveBody() |
private | array{string|array<string, mixed>|null, array<string, string|list<string>>} |
Resolves the request body and any headers implied by it (e.g. Content-Type for JSON). A 'body' array without any \CURLFile/\CURLStringFile value is form-urlencoded. One containing such a value is passed to curl as-is, which then sends it as multipart/form-data with its own boundary and Content-Type — no header is added here in that case, since ours would conflict with curl's boundary. |
hasFileParts() |
private | bool |
— |
formatHeaders() |
private | list<string> |
— |
stripCredentialHeaders() |
public | array<string, string|list<string>> |
Removes Authorization/Proxy-Authorization/Cookie headers (case-insensitive name match) — called when a redirect crosses origins, so credentials meant for the original host are never sent to wherever it redirected to. |
resolveRedirectUrl() |
public | string |
Resolves a redirect's Location header against the URL it came from. Handles absolute URLs, protocol-relative ("//host/path"), absolute-path ("/path"), and relative paths (resolved against the base URL's directory, with "." and ".." segments collapsed). |
normalizePath() |
private | string |
Collapses "." and ".." path segments. |
isCrossOrigin() |
public | bool |
— |
applyTlsOptions() |
private | void |
Applies client-certificate (mTLS) options, when provided. Supported $options keys: local_cert (client cert path), local_pk (private key path, when separate from the cert), passphrase (private key passphrase), cafile (custom CA bundle path). |
applyQuery() |
private | string |
Appends query parameters to a URL. |
resolveHostIp() |
private | string|null |
Resolves a host to the IP that will actually be connected to: the host itself when it's already a literal IP, otherwise the first address the configured DNS resolver returns for it. Returns null when the host is absent or resolution fails — callers fall back to curl's own resolution in that case, except where 'block_private_network' is set (see buildHandle()), where a null result is treated as unsafe rather than silently allowed. |
isPrivateOrReservedIp() |
private | bool |
— |
buildResolveOption() |
private | string|null |
Builds a CURLOPT_RESOLVE entry pinning $host to an already-resolved $ip. |
__construct()
CurlHttpClient __construct()
public function __construct(DnsResolverInterface $dns)
| Param | Type | Description |
|---|---|---|
$dns |
DnsResolverInterface |
Resolver used to pin each request's target IP. |
request()
CurlHttpClient request()
public function request(string $method, string $url, array $options): HttpResponseInterface
Extra $options beyond HttpClientInterface::request(): 'follow_redirects' (bool, default true); 'block_private_network' (bool, default false), re-checked on every redirect hop; 'max_connect_duration' (float seconds) — connect phase only, separate from 'timeout'; 'on_progress' (callable(int $dlNow, int $dlSize, array $info): void), called periodically — a thrown exception aborts the transfer (see getError()).
| Param | Type | Description |
|---|---|---|
$method |
string |
— |
$url |
string |
— |
$options |
array<string, mixed> |
— |
Returns: HttpResponseInterface
buildHandle()
CurlHttpClient buildHandle()
@internal — Called only by CurlResponse (initial request and each redirect hop).
public function buildHandle(string $method, string $url, array $options, CurlResponse $forResponse): ?\CurlHandle
Builds one hop's curl handle, wiring its header/body callbacks to write directly into $forResponse. Returns null (after marking $forResponse done via _completeBlocked()) when block_private_network refuses the target — there's no handle to register in that case.
| Param | Type | Description |
|---|---|---|
$method |
string |
— |
$url |
string |
— |
$options |
array<string, mixed> |
— |
$forResponse |
CurlResponse |
— |
Returns: \CurlHandle\|null
registerHandle()
CurlHttpClient registerHandle()
@internal — Called only by CurlResponse, to add a freshly built handle to this client's shared curl_multi handle.
public function registerHandle(\CurlHandle $handle, CurlResponse $response): void
| Param | Type | Description |
|---|---|---|
$handle |
\CurlHandle |
— |
$response |
CurlResponse |
— |
forget()
CurlHttpClient forget()
@internal — Called only by CurlResponse::cancel(), to remove a handle before it has finished.
public function forget(\CurlHandle $handle): void
| Param | Type | Description |
|---|---|---|
$handle |
\CurlHandle |
— |
pumpUntilDone()
CurlHttpClient pumpUntilDone()
@internal — Called only by CurlResponse::ensureComplete().
public function pumpUntilDone(CurlResponse $target): void
Drives the shared curl_multi handle until $target's current hop finishes. Every other pending handle advances in the same loop — that's the concurrency.
| Param | Type | Description |
|---|---|---|
$target |
CurlResponse |
— |
finishOne()
CurlHttpClient finishOne()
private function finishOne(\CurlMultiHandle $multi, array $info): void
| Param | Type | Description |
|---|---|---|
$multi |
\CurlMultiHandle |
— |
$info |
array{msg: int, result: int, handle: \CurlHandle} |
One entry from curl_multi_info_read(). |
resolveBody()
CurlHttpClient resolveBody()
private function resolveBody(array $options): array
Resolves the request body and any headers implied by it (e.g. Content-Type for JSON). A 'body' array without any \CURLFile/\CURLStringFile value is form-urlencoded. One containing such a value is passed to curl as-is, which then sends it as multipart/form-data with its own boundary and Content-Type — no header is added here in that case, since ours would conflict with curl's boundary.
| Param | Type | Description |
|---|---|---|
$options |
array<string, mixed> |
— |
Returns: array{string\|array<string, mixed>\|null, array<string, string\|list<string>>}
hasFileParts()
CurlHttpClient hasFileParts()
private function hasFileParts(array $body): bool
| Param | Type | Description |
|---|---|---|
$body |
array<string, mixed> |
— |
Returns: bool — True when any value is a file part (multipart/form-data upload).
formatHeaders()
CurlHttpClient formatHeaders()
private function formatHeaders(array $headers): array
| Param | Type | Description |
|---|---|---|
$headers |
array<string, string|list<string>> |
— |
Returns: list<string>
stripCredentialHeaders()
CurlHttpClient stripCredentialHeaders()
@internal — Called only by CurlResponse on a cross-origin redirect.
public function stripCredentialHeaders(array $headers): array
Removes Authorization/Proxy-Authorization/Cookie headers (case-insensitive name match) — called when a redirect crosses origins, so credentials meant for the original host are never sent to wherever it redirected to.
| Param | Type | Description |
|---|---|---|
$headers |
array<string, string|list<string>> |
— |
Returns: array<string, string\|list<string>>
resolveRedirectUrl()
CurlHttpClient resolveRedirectUrl()
@internal — Called only by CurlResponse on a redirect.
public function resolveRedirectUrl(string $baseUrl, string $location): string
Resolves a redirect's Location header against the URL it came from. Handles absolute URLs, protocol-relative ("//host/path"), absolute-path ("/path"), and relative paths (resolved against the base URL's directory, with "." and ".." segments collapsed).
| Param | Type | Description |
|---|---|---|
$baseUrl |
string |
— |
$location |
string |
— |
Returns: string
normalizePath()
CurlHttpClient normalizePath()
private function normalizePath(string $path): string
Collapses "." and ".." path segments.
| Param | Type | Description |
|---|---|---|
$path |
string |
— |
Returns: string
isCrossOrigin()
CurlHttpClient isCrossOrigin()
@internal — Called only by CurlResponse on a redirect.
public function isCrossOrigin(string $urlA, string $urlB): bool
| Param | Type | Description |
|---|---|---|
$urlA |
string |
— |
$urlB |
string |
— |
Returns: bool — True when scheme, host, or port differ between the two URLs. Unparseable input is treated as cross-origin (fail safe).
applyTlsOptions()
CurlHttpClient applyTlsOptions()
private function applyTlsOptions(\CurlHandle $ch, array $options): void
Applies client-certificate (mTLS) options, when provided. Supported $options keys: local_cert (client cert path), local_pk (private key path, when separate from the cert), passphrase (private key passphrase), cafile (custom CA bundle path).
| Param | Type | Description |
|---|---|---|
$ch |
\CurlHandle |
— |
$options |
array<string, mixed> |
— |
applyQuery()
CurlHttpClient applyQuery()
private function applyQuery(string $url, array $query): string
Appends query parameters to a URL.
| Param | Type | Description |
|---|---|---|
$url |
string |
— |
$query |
array<string, mixed> |
— |
Returns: string
resolveHostIp()
CurlHttpClient resolveHostIp()
private function resolveHostIp(?string $host): ?string
Resolves a host to the IP that will actually be connected to: the host itself when it's already a literal IP, otherwise the first address the configured DNS resolver returns for it. Returns null when the host is absent or resolution fails — callers fall back to curl's own resolution in that case, except where 'block_private_network' is set (see buildHandle()), where a null result is treated as unsafe rather than silently allowed.
| Param | Type | Description |
|---|---|---|
$host |
string|null |
— |
Returns: string\|null
isPrivateOrReservedIp()
CurlHttpClient isPrivateOrReservedIp()
private function isPrivateOrReservedIp(string $ip): bool
| Param | Type | Description |
|---|---|---|
$ip |
string |
Candidate IPv4/IPv6 address (or a hostname that failed to resolve). |
Returns: bool — True when $ip is not a valid public, routable address — this includes private ranges (RFC 1918, ULA, ...), loopback, link-local, reserved ranges, and anything that isn't a valid IP at all (e.g. an unresolved hostname passed through), so unresolvable input fails closed.
buildResolveOption()
CurlHttpClient buildResolveOption()
private function buildResolveOption(string $url, string $host, string $ip): ?string
Builds a CURLOPT_RESOLVE entry pinning $host to an already-resolved $ip.
| Param | Type | Description |
|---|---|---|
$url |
string |
— |
$host |
string |
— |
$ip |
string |
— |
Returns: string\|null — "host:port:ip" (IPv6 addresses bracketed).
CurlResponse
final class — rafalmasiarek\HttpClient\Http\CurlResponse · source
Lazy HttpResponseInterface returned by CurlHttpClient. Registers its curl handle on the client's shared curl_multi and returns immediately; the first accessor call pumps that shared handle until this response's hop is done, finishing any other pending responses along the way too.
implements HttpResponseInterface
Depends on: CurlHttpClient, \CurlHandle, TransportErrorKind
| Property | Type | Visibility | Description |
|---|---|---|---|
$handle |
\CurlHandle|null |
private | Current hop's handle. Null once this hop has finished (closed) or was blocked before starting. |
$hopDone |
bool |
private | Whether the current hop (not necessarily the final one, if redirects remain) has finished. |
$done |
bool |
private | Whether this response is fully resolved (no more redirects to follow). |
$canceled |
bool |
private | — |
$statusCode |
int |
private | — |
$headers |
array<string, list<string>> |
private | — |
$body |
string |
private | — |
$error |
?string |
private | — |
$errorKind |
?TransportErrorKind |
private | — |
$lastInfo |
array<string, mixed> |
private | Snapshot of curl_getinfo() from the most recently finished hop. |
$redirectCount |
int |
private | — |
$finalUrl |
string |
private | — |
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | — | — |
getStatusCode() |
public | int |
— |
getHeaders() |
public | array |
— |
getHeader() |
public | ?string |
— |
getHeaderLine() |
public | string |
— |
getContent() |
public | string |
— |
json() |
public | mixed |
— |
isSuccessful() |
public | bool |
— |
getError() |
public | ?string |
— |
getErrorKind() |
public | ?TransportErrorKind |
— |
getInfo() |
public | mixed |
— |
cancel() |
public | void |
— |
_onHeaderLine() |
public | void |
— |
_onBodyChunk() |
public | void |
— |
_completeBlocked() |
public | void |
— |
_hopFinished() |
public | void |
— |
_handle() |
public | ?\CurlHandle |
— |
ensureComplete() |
private | void |
Drives the shared curl_multi handle (via the owning client) until this response's current hop finishes, then follows any redirect by rebuilding and re-registering a new handle, repeating until a final response is reached. |
maybeFollowRedirect() |
private | bool |
— |
__construct()
CurlResponse __construct()
public function __construct(CurlHttpClient $client, string $method, string $url, array $options, bool $followRedirects)
| Param | Type | Description |
|---|---|---|
$client |
CurlHttpClient |
Owner — drives the shared curl_multi handle and builds each hop's curl handle. |
$method |
string |
HTTP method. May be downgraded to GET on a 301/302/303 redirect of a non-GET/HEAD request. |
$url |
string |
Request URL (reassigned to each redirect's target). |
$options |
array<string, mixed> |
Request options, as passed to CurlHttpClient::request(). |
$followRedirects |
bool |
Whether to transparently follow 3xx responses. |
getHeader()
CurlResponse getHeader()
public function getHeader(string $name): ?string
| Param | Type | Description |
|---|---|---|
$name |
string |
— |
Returns: ?string
getHeaderLine()
CurlResponse getHeaderLine()
public function getHeaderLine(string $name): string
| Param | Type | Description |
|---|---|---|
$name |
string |
— |
Returns: string
getErrorKind()
CurlResponse getErrorKind()
public function getErrorKind(): ?TransportErrorKind
Returns: ?TransportErrorKind
getInfo()
CurlResponse getInfo()
public function getInfo(?string $key): mixed
| Param | Type | Description |
|---|---|---|
$key |
?string |
— |
Returns: mixed
_onHeaderLine()
CurlResponse _onHeaderLine()
@internal — Called only by CurlHttpClient's CURLOPT_HEADERFUNCTION closure.
public function _onHeaderLine(string $line): void
| Param | Type | Description |
|---|---|---|
$line |
string |
— |
_onBodyChunk()
CurlResponse _onBodyChunk()
@internal — Called only by CurlHttpClient's CURLOPT_WRITEFUNCTION closure.
public function _onBodyChunk(string $chunk): void
| Param | Type | Description |
|---|---|---|
$chunk |
string |
— |
_completeBlocked()
CurlResponse _completeBlocked()
@internal — Called only by CurlHttpClient::buildHandle() when a block_private_network check refuses the target before a handle is even created.
public function _completeBlocked(string $host): void
| Param | Type | Description |
|---|---|---|
$host |
string |
— |
_hopFinished()
CurlResponse _hopFinished()
@internal — Called only by CurlHttpClient::pumpUntilDone(). Handle is already closed by then.
public function _hopFinished(int $statusCode, ?string $error, array $info, ?TransportErrorKind $errorKind): void
| Param | Type | Description |
|---|---|---|
$statusCode |
int |
— |
$error |
?string |
— |
$info |
array<string, mixed> |
curl_getinfo() snapshot taken before close. |
$errorKind |
?TransportErrorKind |
— |
_handle()
CurlResponse _handle()
@internal — Exposes the current hop's handle to CurlHttpClient::pumpUntilDone().
public function _handle(): ?\CurlHandle
Returns: ?\CurlHandle
ensureComplete()
CurlResponse ensureComplete()
private function ensureComplete(): void
Drives the shared curl_multi handle (via the owning client) until this response's current hop finishes, then follows any redirect by rebuilding and re-registering a new handle, repeating until a final response is reached.
maybeFollowRedirect()
CurlResponse maybeFollowRedirect()
private function maybeFollowRedirect(): bool
Returns: bool — True when a redirect was followed (caller should keep looping); false when this response is final.
DefaultRetryStrategy
final class — rafalmasiarek\HttpClient\Http\DefaultRetryStrategy · source
Retries transport-level failures and a conservative set of transient HTTP statuses, only for methods considered safe to replay automatically. Never retries a non-idempotent method (POST, PATCH, ...) — a caller that knows its request body is safe to resend should retry it explicitly rather than rely on this default.
implements RetryStrategyInterface
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | — | — |
shouldRetry() |
public | bool |
— |
getDelayMilliseconds() |
public | int |
— |
parseRetryAfter() |
private | int|null |
Parses a Retry-After header value (delay-seconds or an HTTP-date) into seconds from now. |
__construct()
DefaultRetryStrategy __construct()
public function __construct(int $maxRetries, int $baseDelayMs, int $maxDelayMs, int $jitterMs)
| Param | Type | Description |
|---|---|---|
$maxRetries |
int |
Attempts after the first, e.g. 3 means up to 4 total tries. |
$baseDelayMs |
int |
Base for exponential backoff (doubles each attempt). |
$maxDelayMs |
int |
Upper bound on any single computed delay, including Retry-After. |
$jitterMs |
int |
Random extra delay added on top, to avoid synchronized retry storms. |
shouldRetry()
DefaultRetryStrategy shouldRetry()
public function shouldRetry(string $method, HttpResponseInterface $response, int $attempt): bool
| Param | Type | Description |
|---|---|---|
$method |
string |
— |
$response |
HttpResponseInterface |
— |
$attempt |
int |
— |
Returns: bool
getDelayMilliseconds()
DefaultRetryStrategy getDelayMilliseconds()
public function getDelayMilliseconds(HttpResponseInterface $response, int $attempt): int
| Param | Type | Description |
|---|---|---|
$response |
HttpResponseInterface |
— |
$attempt |
int |
— |
Returns: int
parseRetryAfter()
DefaultRetryStrategy parseRetryAfter()
private function parseRetryAfter(string $value): ?int
Parses a Retry-After header value (delay-seconds or an HTTP-date) into seconds from now.
| Param | Type | Description |
|---|---|---|
$value |
string |
— |
Returns: int\|null — Null when absent or unparseable.
DownloadException
class — rafalmasiarek\HttpClient\Http\DownloadException · source
Thrown when ChunkedFileDownloader cannot complete a download.
extends \RuntimeException
EventSourceClient
final class — rafalmasiarek\HttpClient\Http\EventSourceClient · source
Consumes a "text/event-stream" (Server-Sent Events) endpoint, invoking a callback per parsed frame. Separate, callback-based API — not built on HttpClientInterface, since a stream delivers incrementally and CurlResponse only resolves whole responses. connect() blocks until the server closes, a transport error occurs, or $onEvent returns false.
Depends on: DnsResolverInterface
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | — | — |
connect() |
public | string|null |
$options supports 'headers'/'verify_peer' (as in HttpClientInterface::request()) plus 'last_event_id' (string), sent as the Last-Event-ID header for a reconnect. |
extractFrame() |
private | array{string, string}|null |
Extracts the next complete, blank-line-terminated frame from $buffer, if any. |
parseFrame() |
private | ServerSentEvent|null |
— |
formatHeaders() |
private | list<string> |
— |
resolveHostIp() |
private | string|null |
— |
buildResolveOption() |
private | string|null |
— |
__construct()
EventSourceClient __construct()
public function __construct(DnsResolverInterface $dns)
| Param | Type | Description |
|---|---|---|
$dns |
DnsResolverInterface |
Resolver used to pin the connection's target IP, same as CurlHttpClient. |
connect()
EventSourceClient connect()
public function connect(string $url, callable $onEvent, array $options): ?string
$options supports 'headers'/'verify_peer' (as in HttpClientInterface::request()) plus 'last_event_id' (string), sent as the Last-Event-ID header for a reconnect.
| Param | Type | Description |
|---|---|---|
$url |
string |
— |
$onEvent |
callable |
— |
$options |
array<string, mixed> |
— |
Returns: string\|null — Last "id:" seen on the stream (feed back as 'last_event_id' on a reconnect), or null if none arrived.
| Throws | When |
|---|---|
\RuntimeException |
On a connection failure before any data arrived. |
extractFrame()
EventSourceClient extractFrame()
private function extractFrame(string $buffer): ?array
Extracts the next complete, blank-line-terminated frame from $buffer, if any.
| Param | Type | Description |
|---|---|---|
$buffer |
string |
— |
Returns: array{string, string}\|null — [frame, remaining buffer], or null when no complete frame is available yet.
parseFrame()
EventSourceClient parseFrame()
private function parseFrame(string $raw): ?ServerSentEvent
| Param | Type | Description |
|---|---|---|
$raw |
string |
One frame's worth of lines (no trailing blank line). |
Returns: ServerSentEvent\|null — Null for a frame with no data line (e.g. a bare comment/retry frame).
formatHeaders()
EventSourceClient formatHeaders()
private function formatHeaders(array $headers): array
| Param | Type | Description |
|---|---|---|
$headers |
array<string, string|list<string>> |
— |
Returns: list<string>
resolveHostIp()
EventSourceClient resolveHostIp()
private function resolveHostIp(?string $host): ?string
| Param | Type | Description |
|---|---|---|
$host |
string|null |
— |
Returns: string\|null
buildResolveOption()
EventSourceClient buildResolveOption()
private function buildResolveOption(string $url, string $host, string $ip): ?string
| Param | Type | Description |
|---|---|---|
$url |
string |
— |
$host |
string |
— |
$ip |
string |
— |
Returns: string\|null
FileHttpCacheStore
final class — rafalmasiarek\HttpClient\Http\FileHttpCacheStore · source
Default HttpCacheStoreInterface backend: one JSON file per key. LOCK_EX on write only — not meant for high-concurrency shared caches.
implements HttpCacheStoreInterface
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | — | — |
get() |
public | ?array |
— |
set() |
public | void |
— |
path() |
private | string |
— |
__construct()
FileHttpCacheStore __construct()
public function __construct(string $directory)
| Param | Type | Description |
|---|---|---|
$directory |
string |
Created on first write if it doesn't exist. |
get()
FileHttpCacheStore get()
public function get(string $key): ?array
| Param | Type | Description |
|---|---|---|
$key |
string |
— |
Returns: ?array
set()
FileHttpCacheStore set()
public function set(string $key, array $entry, int $ttl): void
| Param | Type | Description |
|---|---|---|
$key |
string |
— |
$entry |
array |
— |
$ttl |
int |
— |
path()
FileHttpCacheStore path()
private function path(string $key): string
| Param | Type | Description |
|---|---|---|
$key |
string |
— |
Returns: string
HttpCacheStoreInterface
interface — rafalmasiarek\HttpClient\Http\HttpCacheStoreInterface · source
Minimal storage contract for CachingHttpClient — not PSR-16/PSR-6, just get/set with a TTL, so a backend doesn't need a PSR cache dependency.
| Method | Visibility | Returns | Summary |
|---|---|---|---|
get() |
public | array<string, mixed>|null |
Returns the entry regardless of freshness — CachingHttpClient checks 'expires_at' itself, since a stale entry's validators are still needed. |
set() |
public | void |
— |
get()
HttpCacheStoreInterface get()
public function get(string $key): ?array
Returns the entry regardless of freshness — CachingHttpClient checks 'expires_at' itself, since a stale entry's validators are still needed.
| Param | Type | Description |
|---|---|---|
$key |
string |
— |
Returns: array<string, mixed>\|null — Null only when no entry exists.
set()
HttpCacheStoreInterface set()
public function set(string $key, array $entry, int $ttl): void
| Param | Type | Description |
|---|---|---|
$key |
string |
— |
$entry |
array<string, mixed> |
— |
$ttl |
int |
Seconds until this entry should be treated as expired. |
HttpClientInterface
interface — rafalmasiarek\HttpClient\Http\HttpClientInterface · source
Minimal HTTP client contract, option shape inspired by Symfony HttpClient / Guzzle.
| Method | Visibility | Returns | Summary |
|---|---|---|---|
request() |
public | HttpResponseInterface |
Performs an HTTP request. Supported $options keys: - headers (array<string,string|list>) : request headers; an array value sends the same header name multiple times - query (array<string,mixed>) : appended to the URL as a query string - body (string|array<string,mixed>) : request body. A string is sent as-is. An array is sent application/x-www-form-urlencoded, unless it contains a \CURLFile/\CURLStringFile value, in which case it's sent multipart/form-data (curl sets its own boundary + Content-Type). - json (mixed) : JSON-encoded request body; sets Content-Type: application/json (ignored if 'body' is also set) - timeout (float) : total request timeout in seconds - auth_basic (string|array{0:string,1:string}) : HTTP Basic Auth, as "user:pass" or [user, pass] - verify_peer (bool) : verify the server's TLS certificate (default: true) - follow_redirects (bool) : follow HTTP redirects (default: true). Set false to inspect a redirect response itself (status + Location header) instead of the final destination. Implementations that follow redirects themselves (rather than delegating to the underlying transport) must strip Authorization/Cookie/ Proxy-Authorization headers and auth_basic when a redirect hop crosses origins (scheme, host, or port differs). - block_private_network (bool) : refuse to connect when the target host resolves to a private or reserved-range address (default: false), re-checked on every redirect hop. Intended for requests to externally-supplied URLs (e.g. a user-submitted link a background job fetches) as an SSRF guard — leave unset for requests to hardcoded, trusted endpoints. - local_cert (string) : client certificate path, for mTLS - local_pk (string) : client private key path, when separate from local_cert - passphrase (string) : client private key passphrase - cafile (string) : custom CA bundle path - max_connect_duration (float) : limits only the connect phase (DNS+TCP+TLS), in seconds, separately from 'timeout' which bounds the whole request. Not every implementation supports this distinction. - on_progress (callable(int $dlNow, int $dlSize, array $info): void) : called periodically as the transfer progresses (at least once per second while data is flowing; $dlSize is -1 when unknown). A thrown exception aborts the transfer and is reported via HttpResponseInterface::getError(). Not every implementation calls this. Returns a lazy response: no network I/O has necessarily happened yet when this method returns. The first call to any accessor on the returned object (getStatusCode(), getHeaders(), getContent(), ...) drives the request to completion. Calling request() several times before reading any of the responses lets an implementation that shares a single underlying transport (e.g. one curl_multi handle) run them concurrently; reading a response immediately makes that one call behave synchronously. |
request()
HttpClientInterface request()
public function request(string $method, string $url, array $options): HttpResponseInterface
Performs an HTTP request. Supported $options keys: - headers (array<string,string|list>) : request headers; an array value sends the same header name multiple times - query (array<string,mixed>) : appended to the URL as a query string - body (string|array<string,mixed>) : request body. A string is sent as-is. An array is sent application/x-www-form-urlencoded, unless it contains a \CURLFile/\CURLStringFile value, in which case it's sent multipart/form-data (curl sets its own boundary + Content-Type). - json (mixed) : JSON-encoded request body; sets Content-Type: application/json (ignored if 'body' is also set) - timeout (float) : total request timeout in seconds - auth_basic (string|array{0:string,1:string}) : HTTP Basic Auth, as "user:pass" or [user, pass] - verify_peer (bool) : verify the server's TLS certificate (default: true) - follow_redirects (bool) : follow HTTP redirects (default: true). Set false to inspect a redirect response itself (status + Location header) instead of the final destination. Implementations that follow redirects themselves (rather than delegating to the underlying transport) must strip Authorization/Cookie/ Proxy-Authorization headers and auth_basic when a redirect hop crosses origins (scheme, host, or port differs). - block_private_network (bool) : refuse to connect when the target host resolves to a private or reserved-range address (default: false), re-checked on every redirect hop. Intended for requests to externally-supplied URLs (e.g. a user-submitted link a background job fetches) as an SSRF guard — leave unset for requests to hardcoded, trusted endpoints. - local_cert (string) : client certificate path, for mTLS - local_pk (string) : client private key path, when separate from local_cert - passphrase (string) : client private key passphrase - cafile (string) : custom CA bundle path - max_connect_duration (float) : limits only the connect phase (DNS+TCP+TLS), in seconds, separately from 'timeout' which bounds the whole request. Not every implementation supports this distinction. - on_progress (callable(int $dlNow, int $dlSize, array $info): void) : called periodically as the transfer progresses (at least once per second while data is flowing; $dlSize is -1 when unknown). A thrown exception aborts the transfer and is reported via HttpResponseInterface::getError(). Not every implementation calls this. Returns a lazy response: no network I/O has necessarily happened yet when this method returns. The first call to any accessor on the returned object (getStatusCode(), getHeaders(), getContent(), ...) drives the request to completion. Calling request() several times before reading any of the responses lets an implementation that shares a single underlying transport (e.g. one curl_multi handle) run them concurrently; reading a response immediately makes that one call behave synchronously.
| Param | Type | Description |
|---|---|---|
$method |
string |
HTTP method (GET, POST, ...). |
$url |
string |
Absolute URL. |
$options |
array<string, mixed> |
See above. |
Returns: HttpResponseInterface
HttpResponse
final readonly class — rafalmasiarek\HttpClient\Http\HttpResponse · source
Eager (already-resolved) HttpResponseInterface implementation. Useful for constructing a synthetic response (CachingHttpClient serving a cached entry, a test double, ...) where there's no real lazy transfer to drive — every accessor just returns the value given at construction time. CurlHttpClient does not return this class for a real network request; it returns CurlResponse, which is genuinely lazy. See HttpResponseInterface.
implements HttpResponseInterface
Depends on: HttpTransportDebug, TransportErrorKind
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | — | — |
getStatusCode() |
public | int |
— |
getHeaders() |
public | array |
— |
getHeader() |
public | ?string |
— |
getHeaderLine() |
public | string |
— |
getContent() |
public | string |
— |
json() |
public | mixed |
— |
isSuccessful() |
public | bool |
— |
getError() |
public | ?string |
— |
getErrorKind() |
public | ?TransportErrorKind |
— |
getInfo() |
public | mixed |
— |
cancel() |
public | void |
— |
__construct()
HttpResponse __construct()
public function __construct(int $statusCode, array $headers, string $body, ?string $error, ?HttpTransportDebug $debug, ?TransportErrorKind $errorKind)
| Param | Type | Description |
|---|---|---|
$statusCode |
int |
HTTP status code. 0 when the request never reached the server. |
$headers |
array<string, list<string>> |
Response headers, lowercase names, all values per name preserved (e.g. multiple Set-Cookie headers). |
$body |
string |
Response body. |
$error |
string|null |
curl error message, when the request failed at the transport level. |
$debug |
HttpTransportDebug|null |
Timing/target info from curl_getinfo(), for diagnosing connectivity failures. Not populated by every HttpClientInterface implementation. |
$errorKind |
TransportErrorKind|null |
Structured classification of $error, when known. |
getHeader()
HttpResponse getHeader()
public function getHeader(string $name): ?string
| Param | Type | Description |
|---|---|---|
$name |
string |
— |
Returns: ?string
getHeaderLine()
HttpResponse getHeaderLine()
public function getHeaderLine(string $name): string
| Param | Type | Description |
|---|---|---|
$name |
string |
— |
Returns: string
getErrorKind()
HttpResponse getErrorKind()
public function getErrorKind(): ?TransportErrorKind
Returns: ?TransportErrorKind
getInfo()
HttpResponse getInfo()
public function getInfo(?string $key): mixed
| Param | Type | Description |
|---|---|---|
$key |
?string |
— |
Returns: mixed
HttpResponseInterface
interface — rafalmasiarek\HttpClient\Http\HttpResponseInterface · source
Lazy HTTP response. request() returns one immediately; the first accessor call below drives the transfer to completion. Firing several request() calls before reading any response runs them concurrently. No header-only wait, no chunked streaming — one accessor call resolves everything. Transport failures are reported via getError(), not exceptions.
| Method | Visibility | Returns | Summary |
|---|---|---|---|
getStatusCode() |
public | int |
— |
getHeaders() |
public | array<string, list<string>> |
— |
getHeader() |
public | string|null |
— |
getHeaderLine() |
public | string |
— |
getContent() |
public | string |
— |
json() |
public | mixed |
— |
isSuccessful() |
public | bool |
— |
getError() |
public | string|null |
— |
getErrorKind() |
public | TransportErrorKind|null |
Structured classification of getError() — for a caller that needs to branch on why a request failed without string-matching getError()'s free-text message. Based on curl's own error code (e.g. CURLE_OPERATION_TIMEDOUT), not the message text, so it's stable across curl/PHP versions. Null whenever getError() is null. |
getInfo() |
public | mixed |
Non-blocking transport metadata — never drives the transfer forward, so it's safe to call at any time, including before this response has been read. |
cancel() |
public | void |
Aborts the request if it hasn't finished yet. A no-op once the response is complete. After this, getStatusCode() is 0 and getError() reports the cancellation. |
getStatusCode()
HttpResponseInterface getStatusCode()
public function getStatusCode(): int
Returns: int — HTTP status code. 0 when the request never reached the server.
getHeaders()
HttpResponseInterface getHeaders()
public function getHeaders(): array
Returns: array<string, list<string>> — Lowercase header names, all values per name preserved (e.g. multiple Set-Cookie).
getHeader()
HttpResponseInterface getHeader()
public function getHeader(string $name): ?string
| Param | Type | Description |
|---|---|---|
$name |
string |
Header name, case-insensitive. |
Returns: string\|null — The first value, or null when absent.
getHeaderLine()
HttpResponseInterface getHeaderLine()
public function getHeaderLine(string $name): string
| Param | Type | Description |
|---|---|---|
$name |
string |
Header name, case-insensitive. |
Returns: string — All values, comma-joined (PSR-7 convention), or empty when absent.
getContent()
HttpResponseInterface getContent()
public function getContent(): string
Returns: string — Response body.
json()
HttpResponseInterface json()
public function json(): mixed
Returns: mixed — Body decoded as JSON, or null when it isn't valid JSON.
isSuccessful()
HttpResponseInterface isSuccessful()
public function isSuccessful(): bool
Returns: bool — True when the request completed with no transport error and a 2xx status.
getError()
HttpResponseInterface getError()
public function getError(): ?string
Returns: string\|null — Transport-level error (DNS failure, connection refused, timeout, a block_private_network refusal, ...), or null when none occurred. A non-2xx HTTP status that the server actually returned is not an error by itself — check getStatusCode() for that.
getErrorKind()
HttpResponseInterface getErrorKind()
public function getErrorKind(): ?TransportErrorKind
Structured classification of getError() — for a caller that needs to branch on why a request failed without string-matching getError()'s free-text message. Based on curl's own error code (e.g. CURLE_OPERATION_TIMEDOUT), not the message text, so it's stable across curl/PHP versions. Null whenever getError() is null.
Returns: TransportErrorKind\|null
getInfo()
HttpResponseInterface getInfo()
public function getInfo(?string $key): mixed
Non-blocking transport metadata — never drives the transfer forward, so it's safe to call at any time, including before this response has been read.
| Param | Type | Description |
|---|---|---|
$key |
string|null |
When given, returns just that key's value (or null if absent/not yet known); when null, returns the full info array. |
Returns: mixed
cancel()
HttpResponseInterface cancel()
public function cancel(): void
Aborts the request if it hasn't finished yet. A no-op once the response is complete. After this, getStatusCode() is 0 and getError() reports the cancellation.
HttpTransportDebug
final readonly class — rafalmasiarek\HttpClient\Http\HttpTransportDebug · source
Low-level transport timing/target info for a single request, sourced from curl_getinfo(). Meant for diagnosing connectivity failures (DNS, connect, TLS, timeout) — not for routine success-path use.
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | — | — |
fromCurlInfo() |
public static | self |
Builds an instance from a raw curl_getinfo() array. |
toArray() |
public | array<string, float|string|int|null> |
— |
__construct()
HttpTransportDebug __construct()
public function __construct(float $namelookupTime, float $connectTime, float $appconnectTime, float $totalTime, ?string $primaryIp, ?int $primaryPort)
| Param | Type | Description |
|---|---|---|
$namelookupTime |
float |
Seconds from start until name resolution completed. |
$connectTime |
float |
Seconds from start until the TCP connection was established. |
$appconnectTime |
float |
Seconds from start until the TLS/SSL handshake completed (0 for plain HTTP). |
$totalTime |
float |
Total seconds for the whole request. |
$primaryIp |
string|null |
IP address actually connected to, or null when the connection never got that far. |
$primaryPort |
int|null |
Port actually connected to, or null when the connection never got that far. |
fromCurlInfo()
HttpTransportDebug fromCurlInfo()
public static function fromCurlInfo(array $info): self
Builds an instance from a raw curl_getinfo() array.
| Param | Type | Description |
|---|---|---|
$info |
array<string, mixed> |
Result of curl_getinfo($ch). |
Returns: self
toArray()
HttpTransportDebug toArray()
public function toArray(): array
Returns: array<string, float\|string\|int\|null>
RetryHttpClient
final class — rafalmasiarek\HttpClient\Http\RetryHttpClient · source
Decorates an HttpClientInterface with retry-on-transient-failure behavior, so individual callers don't each reimplement their own retry loop. Delegates the actual retry/idempotency policy to a RetryStrategyInterface — this class only owns the attempt loop, the sleep between attempts, which base URI (if more than one was given) each attempt uses, and (when a logger is given) reporting each retry.
implements HttpClientInterface
Depends on: RetryStrategyInterface, LoggerInterface
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | — | — |
request() |
public | HttpResponseInterface |
Supports one extra option beyond HttpClientInterface::request(): 'base_uri' (string, or list). When a list is given, $url is treated as a path appended to whichever base the current attempt uses — the first attempt uses index 0, each retry advances to the next base (clamped to the last one once retries outnumber the list), so a failing host doesn't get retried against itself when an alternate is available. |
normalizeBaseUris() |
private | list<string>|null |
— |
buildUrlForAttempt() |
private | string |
— |
__construct()
RetryHttpClient __construct()
public function __construct(HttpClientInterface $client, RetryStrategyInterface $strategy, ?LoggerInterface $logger)
| Param | Type | Description |
|---|---|---|
$client |
HttpClientInterface |
Underlying transport. |
$strategy |
RetryStrategyInterface |
Retry policy. |
$logger |
LoggerInterface|null |
Receives an 'http.request.retry' debug entry for every retried attempt. Optional. |
request()
RetryHttpClient request()
public function request(string $method, string $url, array $options): HttpResponseInterface
Supports one extra option beyond HttpClientInterface::request(): 'base_uri' (string, or list). When a list is given, $url is treated as a path appended to whichever base the current attempt uses — the first attempt uses index 0, each retry advances to the next base (clamped to the last one once retries outnumber the list), so a failing host doesn't get retried against itself when an alternate is available.
| Param | Type | Description |
|---|---|---|
$method |
string |
— |
$url |
string |
— |
$options |
array<string, mixed> |
— |
Returns: HttpResponseInterface — The first response the strategy stops retrying on — may itself be an error/non-2xx response; this method never throws for a failure the strategy declines to retry.
normalizeBaseUris()
RetryHttpClient normalizeBaseUris()
private function normalizeBaseUris(mixed $baseUri): ?array
| Param | Type | Description |
|---|---|---|
$baseUri |
mixed |
— |
Returns: list<string>\|null — Null when absent/empty — request() then uses $url as-is every attempt.
buildUrlForAttempt()
RetryHttpClient buildUrlForAttempt()
private function buildUrlForAttempt(array $baseUris, string $path, int $attempt): string
| Param | Type | Description |
|---|---|---|
$baseUris |
list<string> |
— |
$path |
string |
— |
$attempt |
int |
1-based. |
Returns: string
RetryStrategyInterface
interface — rafalmasiarek\HttpClient\Http\RetryStrategyInterface · source
Decides whether and how long to wait before retrying a request, given the response RetryHttpClient just received (or the transport error it carries).
| Method | Visibility | Returns | Summary |
|---|---|---|---|
shouldRetry() |
public | bool |
— |
getDelayMilliseconds() |
public | int |
— |
shouldRetry()
RetryStrategyInterface shouldRetry()
public function shouldRetry(string $method, HttpResponseInterface $response, int $attempt): bool
| Param | Type | Description |
|---|---|---|
$method |
string |
HTTP method of the request that was just attempted. |
$response |
HttpResponseInterface |
The response received (getStatusCode() 0 and a non-null getError() mean a transport-level failure, not an HTTP response). |
$attempt |
int |
1-based count of attempts made so far, including this one. |
Returns: bool — True to retry.
getDelayMilliseconds()
RetryStrategyInterface getDelayMilliseconds()
public function getDelayMilliseconds(HttpResponseInterface $response, int $attempt): int
| Param | Type | Description |
|---|---|---|
$response |
HttpResponseInterface |
The response that triggered the retry. |
$attempt |
int |
1-based count of attempts made so far, including this one. |
Returns: int — Milliseconds to wait before the next attempt.
ServerSentEvent
final readonly class — rafalmasiarek\HttpClient\Http\ServerSentEvent · source
One parsed "text/event-stream" frame (a blank-line-terminated block of id:/event:/data:/retry: lines), as delivered by EventSourceClient.
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | — | — |
getArrayData() |
public | mixed |
— |
__construct()
ServerSentEvent __construct()
public function __construct(string $data, string $event, ?string $id, ?int $retry)
| Param | Type | Description |
|---|---|---|
$data |
string |
Concatenation of every "data:" line in the frame, joined by "\n" (per the SSE spec) — empty string when the frame had no data line. |
$event |
string |
Event type. "message" when the frame had no explicit "event:" line. |
$id |
string|null |
Last "id:" value seen (persists across frames per the spec, but EventSourceClient hands you a single frame's view, not the running value). |
$retry |
int|null |
Reconnection time in milliseconds, when the frame set one. |
getArrayData()
ServerSentEvent getArrayData()
public function getArrayData(): mixed
Returns: mixed — Decoded JSON, or null when $data isn't valid JSON.
ThrottlingHttpClient
final class — rafalmasiarek\HttpClient\Http\ThrottlingHttpClient · source
Decorates an HttpClientInterface with a token-bucket rate limit. In-process only — bounds one PHP process's rate, not a ceiling shared across workers/servers. request() blocks until a token is free; no "429, try later" path, since this is for self-imposed outbound pacing.
implements HttpClientInterface
| Property | Type | Visibility | Description |
|---|---|---|---|
$tokens |
float |
private | Current token count, replenished lazily on each request()/wait check. |
$lastRefill |
float |
private | microtime(true) of the last refill computation. |
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | — | — |
request() |
public | HttpResponseInterface |
— |
waitForToken() |
private | void |
— |
refill() |
private | void |
— |
__construct()
ThrottlingHttpClient __construct()
public function __construct(HttpClientInterface $client, float $maxTokens, float $refillPerSecond)
| Param | Type | Description |
|---|---|---|
$client |
HttpClientInterface |
Underlying transport. |
$maxTokens |
float |
Bucket capacity — the largest burst allowed. |
$refillPerSecond |
float |
Tokens added per second (the steady-state rate). |
request()
ThrottlingHttpClient request()
public function request(string $method, string $url, array $options): HttpResponseInterface
| Param | Type | Description |
|---|---|---|
$method |
string |
— |
$url |
string |
— |
$options |
array<string, mixed> |
— |
Returns: HttpResponseInterface
TransportErrorKind
enum — rafalmasiarek\HttpClient\Http\TransportErrorKind · source
Structured classification of a transport-level failure — HttpResponseInterface::getError()'s companion for callers that need to branch on why a request failed without string-matching getError()'s free-text message (which is only ever curl_strerror()'s exact English wording, not guaranteed stable, and not comparable across a different HttpClientInterface implementation).
| Case | Value |
|---|---|
Timeout |
— |
DnsFailure |
— |
ConnectionRefused |
— |
Tls |
— |
Blocked |
— |
Canceled |
— |
Unknown |
— |
| Method | Visibility | Returns | Summary |
|---|---|---|---|
fromCurlErrno() |
public static | self |
Classifies a curl_errno() value (a CURLE_* constant) into this enum. |