This reference captures the concrete public surface of the FetchPHP library as implemented under src/Fetch. Use it to keep documentation and tests aligned with the code.
fetch(string|RequestInterface|null $resource = null, ?array $options = [])RequestInterface➜ forwarded to the global client with no option merging.null➜ returns the singletonFetch\Http\Clienthandler for chaining.- String URL ➜ runs through
process_request_options(), handlesbase_uridelegation, and returns eitherFetch\Http\Responseor a promise when the handler is in async mode. - Supported options mirror
RequestOptions::normalizeBodyOptions()(method, headers, body/json/form/multipart, query, timeout, connect_timeout, retries, retry_delay, auth, token, proxy, cookies, allow_redirects, cert, ssl_key, stream, progress, debug, cache, profiler configuration, etc.).
fetch_client(?array $options = null, bool $reset = false): Fetch\Http\Client- Maintains a static
Clientinstance;reset=truerecreates it. - Passing
$optionsclones the current handler with merged defaults (exceptions are wrapped inRuntimeExceptionwith context).
- Maintains a static
- Verb helpers
get/post/put/patch/delete()callrequest_method()which coerces array bodies to JSON unless$dataIsQueryis true. - Matrix async bridge helpers (
async,await,all,race,map,batch,retry) are re-exported when the corresponding\Matrix\*functions exist. - Internal helpers:
process_request_options(array $options)normalizes method enums/strings, headers, body precedence (json>form>multipart>body) and high-level flags.extract_body_and_content_type()returns the paired body +ContentType.handle_request_with_base_uri()wiresbase_uriby configuring the handler before invokingsendRequest.
- Implements PSR-18
ClientInterfaceand PSR-3LoggerAwareInterface. - Constructor arguments:
?ClientHandlerInterface $handler = null,array $options = [],?LoggerInterface $logger = null. Defaults to a newClientHandlerwith provided options and aNullLogger. static createWithBaseUri(string $baseUri, array $options = [])preloads a handler withbase_uri.sendRequest(RequestInterface $request): PsrResponseInterface- Converts PSR request to handler options, logs, and returns a PSR-7 compliant response (
Fetch\Http\Response). - Wraps
ConnectException,Guzzle\RequestException, and generic throwables into Fetch exceptions (NetworkException,RequestException,ClientException).
- Converts PSR request to handler options, logs, and returns a PSR-7 compliant response (
fetch(?string $url = null, ?array $options = [])- When
$urlis null returns the handler for fluent chaining. - Normalizes HTTP method via
Fetch\Enum\Method, infersContentType, appliesbase_urisupport, and delegates toClientHandler::withOptions()->sendRequest(). - Catches
Guzzle\RequestExceptionto surface error responses even when exceptions are thrown.
- When
- Verb conveniences:
get,post,put,patch,delete,head,optionscallmethodRequest()which pushes normalized method + body settings throughfetch(). getHttpClient()exposes the underlyingGuzzleHttp\ClientInterface.
Implements the union interface Fetch\Interfaces\ClientHandler, combining:
RequestConfigurator(withOptions,withHeader,withBody,withJson,withQueryParameters,timeout, etc.).RequestExecutor(request,sendRequest, verb helpers).PromiseHandler(async orchestration).RetryableHandler(retry,retryStatusCodes,retryExceptionsgetters/setters).CacheableRequestHandler(withCache,withoutCache,getCache,isCacheEnabled).DebuggableHandler(withLogLevel,withProfiler,withDebug,debug()snapshot,getLastDebugInfo()).PoolAwareHandler(withConnectionPool,withHttp2, DNS cache controls).HttpClientAware(inject your own Guzzle client).
Implementation relies on traits in src/Fetch/Concerns/:
ConfiguresRequests– base URI, headers, authentication, body helpers (withBodyenforces content-type/header consistency).HandlesUris– builds absolute URIs using handler options or immutableRequestContext.ManagesPromises– toggles async mode, exposesthen/catch/finally,map,sequence, and concurrency utilities (Matrix bridge).ManagesRetries– exposes fluent retry configuration and delegates execution toSupport\RetryStrategy.PerformsHttpRequests– orchestrates RequestContext creation, logging, caching, mocking, profiling, and actual HTTP execution (sync + async).HandlesMocking– consultsTesting\MockServerbefore hitting the network.ManagesConnectionPool– bridges toSupport\GlobalServicesfor shared pools/DNS cache/HTTP2.ManagesDebugAndProfiling– surfaceswithDebug,withProfiler, attachesDebugInfosnapshots per response.
Key runtime behaviors:
- Builds an immutable
RequestContextper call by merging factory defaults → global defaults → handler options → request overrides. - Supports synchronous and asynchronous execution. Async requests always bypass caching and use
React\Promisevia Matrix's helpers. - Integrates caching through
CacheManagerautomatically whenwithCache()was called or acacheoption is present. - Supports
MockServerfakes before network IO,Recorderintegration when recording is enabled. - Logging sanitizes sensitive headers and auth credentials.
- Extends Guzzle's PSR-7 request and adds:
- Factory helpers:
json(),form(),multipart(),get/post/...with enum-aware method normalization. - Mutators:
withJsonBody(),withFormBody(),withBody()(ensures stream/headers),withContentType(), query parameter builders,withBearerToken,withBasicAuth. - Inspection helpers:
supportsRequestBody(),getMethodEnum(),getContentTypeEnum(),hasJsonContent()etc. RequestImmutabilityTraitensures fluent operations preserve the extended type and optional custom request target.
- Factory helpers:
- Extends
GuzzleHttp\Psr7\Response, implementsFetch\Interfaces\Response+ArrayAccess. - Features:
- Static constructors:
createFromBase(),withJson(),created(),noContent(),withRedirect(). - Body helpers:
json(),object(),array(),text(),body(),blob(),arrayBuffer(),xml(). - Status helpers:
status(),statusText(),statusEnum(),isOk(),isNotFound(),failed(), etc. - Content helpers:
contentType(),contentTypeEnum(),hasJsonContent(),hasTextContent(). - JSON ArrayAccess (
$response['data']) for quick reads. - Debugging hooks:
withDebugInfo(DebugInfo $info)andgetDebugInfo()to inspect per-request snapshots. ResponseImmutabilityTraitkeeps buffered body contents in sync when streams are replaced.
- Static constructors:
-
Fetch\Support\RequestOptions- Central source of truth for option precedence and normalization.
- Merges defaults using
merge(...$optionSets), canonicalizes retry keys (max_retries→retries), enforces body precedence, injectsContent-Typeheaders when missing, and exposeswithAuth,withJson,withForm,withMultiparthelpers. normalizeMultipart()accepts associative or list-style arrays.toGuzzleOptions()filters supported keys;toFetchOptions()extracts Fetch-specific flags (base_uri,async,retries,cache,debug, etc.).- Validates method, timeout, retry values, and
base_uriformat.
-
Fetch\Support\RequestContext- Immutable snapshot of method, URI, async flag, timeouts, retries, cache/debug toggles, headers, extra options.
- Offers
with*clone builders (method, URI, async, timeout, retry config, cache/debug toggles, headers/options). - Computes derived queries: safe/idempotent method detection,
shouldUseCache(). - Emits arrays/Guzzle options for compatibility (
toArray(),toGuzzleOptions()).
-
Fetch\Support\DefaultsandRetryDefaults- Factory defaults (
HTTP_METHOD=GET,TIMEOUT=30). - Retry defaults:
MAX_RETRIES=1,RETRY_DELAY=100ms, jitter-capped atMAX_DELAY_MS=30000, status code list (408,429,5xx, Cloudflare 52x, etc.), default exception list (GuzzleHttp\Exception\ConnectException).
- Factory defaults (
-
Fetch\Support\RetryStrategy- Stateless service used by
ManagesRetries. - Accepts overrides for max retries, base delay, retryable status codes + exception classes, and exposes
execute(callable $request, ?callable $onRetry)pluscalculateDelay(),isRetryable(),isRetryableStatusCode(),isRetryableException(). - Adds jitter, caps delays, emits log events (
LoggerInterface, defaults toNullLogger).
- Stateless service used by
-
Fetch\Support\FetchProfiler,ProfilerInterface,ProfilerBridge,DebugConfig,DebugInfoFetchProfilercaptures per-request timing + memory metrics, DNS/connect/SSL events, summary stats.ProfilerBridgeguards all profiler/debug interactions (null-safe), generates unique request IDs, records events, and buildsDebugInfosnapshots with sanitized headers and optional body truncation perDebugInfo::getDefaultOptions().DebugConfigstores debug on/off + option overrides + linked profiler instance.
-
Fetch\Support\GlobalServices- Centralizes shared instances:
ConnectionPool,DnsCache, and merged default options. - Provides
initialize(),configurePool(),setDefaultOptions(),reset(),closeAllConnections(),clearDnsCache(),getStats(). - Used implicitly by
ClientHandler::create*()to ensure pooling infrastructure exists.
- Centralizes shared instances:
CacheInterfacecontract + two implementations:MemoryCache– in-memory LRU-ish store with max item count + TTL.FileCache– JSON-serialized responses on disk (/tmp/fetch-cacheby default) with size pruning.
CacheManager- Default options:
respect_cache_headers,default_ttl,stale_while_revalidate,stale_if_error,cache_methods(GET/HEAD),cache_status_codes,vary_headers,is_shared_cache. withCache()on the handler injects configuration (enabled,ttl,force_refresh,key,cache_body,respect_headers,is_shared_cache, etc.).getCachedResponse()returns either a hydratedResponse, a stale entry requiring revalidation, or metadata for conditional headers.- Supports conditional requests via
If-None-Match/If-Modified-Since, stale-while-revalidate serving, and stale-if-error fallbacks. cacheResponse()storesFetch\Http\Responseinstances asCachedResponsewith TTL derived from Cache-Control headers (viaCacheControl) or explicit overrides.
- Default options:
CachedResponse– value object storing status, headers, body, timestamps, ETag, Last-Modified; exposes freshness helpers.CacheControl– parser/builder for directives, TTL calculation,no-store,no-cache,must-revalidate, etc.CacheKeyGenerator– creates deterministic sha256 keys using method, normalized URI (scheme/host/port/path/query), configuredvary_headers, and optional body hash whencache_bodyis enabled for unsafe methods.
PoolConfiguration– toggles pooling, max connections, max per host/idle, keep-alive timeout, connection timeout, strategy, warmup counts, DNS cache TTL.ConnectionPool- Manages
HostConnectionPoolinstances per host:port:scheme key. ̀ - Tracks active connections, reuse metrics, average latency, exposesgetConnectionFromUrl(),getClientForUrl(),releaseConnection(),recordLatency(),closeAll().
- Manages
HostConnectionPool- Uses
SplQueueto track idleConnectionobjects. - Honors warmup configuration to eagerly create connections.
- Wraps each connection with a dedicated
Guzzle\Clientpre-configured for the host, keep-alive, and connection timeouts.
- Uses
Connection– records creation/last-used timestamps, active request count, keeps a reference to the host-specific Guzzle client, ensuresisReusable()respects keep-alive.DnsCache- Simple TTL-based cache for DNS lookups (A + AAAA fallback to
gethostbyname), supportsresolveFirst(),clear(),prune(),getStats(), throwsNetworkExceptionon failure.
- Simple TTL-based cache for DNS lookups (A + AAAA fallback to
Http2Configuration- Toggles HTTP/2 features, exposes curl options to enforce
CURL_HTTP_VERSION_2_0, optional multiplexing constants when available.
- Toggles HTTP/2 features, exposes curl options to enforce
ManagesPromisestrait exposes:async(?bool $async = true),isAsync().wrapAsync(callable $cb),awaitPromise(PromiseInterface $promise, ?float $timeout),all(),race(),any(),sequence().then,catch,finallyautomatically toggle async mode and callsendAsync().map(array $items, callable $cb, int $concurrency)usesmapBatched()for controlled concurrency.- Internally delegates to Matrix helpers (e.g.,
Matrix\Support\async,await,timeout) and rethrows timeouts asRuntimeException.
ManagesRetries::retry(int $retries, int $delayMs = 100)updates handler defaults; negative inputs throwInvalidArgumentException.retryStatusCodes()/retryExceptions()allow per-handler overrides beyond defaults.- Execution pipeline (sync + async) routes through
retryRequest(RequestContext|null, callable $request)which usesRetryStrategy::execute(). - Stored status codes/exceptions are also injected from
RequestContextwhen per-request options specifyretry_status_codesorretry_exceptions. - Exceptions:
Fetch\Exceptions\ClientException– base class implementingPsr\Http\Client\ClientExceptionInterface.NetworkException– implements PSRNetworkExceptionInterface.RequestException– wraps request/response pair.HttpException– legacy runtime exception exposingsetResponse()/getResponse().
MockServer- Singleton with
fake(array|Closure|null $patterns),preventStrayRequests(),allowStrayRequests(),startRecording(),stopRecording(),recorded(),assertSent(),assertNotSent(),assertSentCount(),assertNothingSent(),resetInstance(). - Accepts
MockResponse,MockResponseSequence, closures (receivingFetch\Http\Request), or arrays (auto-converted to JSON responses). - Matches URL patterns with glob-style wildcards (
*), optionally with HTTP method prefixes (e.g.,POST https://api/*).
- Singleton with
MockResponse- Builder for fake responses (
ok(),created(),noContent(),badRequest(),unauthorized(),forbidden(),notFound(),unprocessableEntity(),serverError(),serviceUnavailable()). - Supports
json(),sequence(),delay(ms),throw(Throwable), andexecute()to yield a realFetch\Http\Response.
- Builder for fake responses (
MockResponseSequence- Queue/loop semantics with
push(),pushJson(),pushStatus(),pushResponse(),whenEmpty(),loop(),next().
- Queue/loop semantics with
Recorderstart(),stop(),record(Request, ResponseInterface),isRecording(),getRecordings(),clear(),reset().replay($recordings)converts previous recordings intoMockServerfakes;exportToJson()/importFromJson()support persistence.
HandlesMockingtrait ensures every handler call consultsMockServerand triggersRecorder::record()when active.
Method– HTTP verbs with helpers:fromString(),tryFromString(),supportsRequestBody().ContentType– Common content types withfromString,tryFromString,normalizeContentType,isJson,isForm,isMultipart,isText.Status– Full catalog of HTTP status codes with helper predicates (isInformational,isSuccess,isClientError,isServerError,isCacheable,isNotModified,isEmpty) andphrase().
Fetch\Concerns\ConfiguresRequests– option/header/body/auth helpers plusreset().Fetch\Concerns\HandlesUris– validation, normalization, query building, base URI enforcement.Fetch\Concerns\PerformsHttpRequests– publichandle()factory, verb wrappers, caching/mocking/profiling pipeline, sync/async execution, stale-if-error logic.Fetch\Concerns\ManagesPromises– promise orchestration.Fetch\Concerns\ManagesRetries– fluent retry configuration and integration withRetryStrategy.Fetch\Concerns\ManagesConnectionPool– toggles pooling + HTTP/2, exposes diagnostics, DNS cache helpers.Fetch\Concerns\ManagesDebugAndProfiling–withDebug,withProfiler,getProfiler(), debug snapshot capture.Fetch\Concerns\HandlesMocking– converts handler options into PSR requests for the mock server.
ClientException– base runtime exception implementingClientExceptionInterface.NetworkException– indicates transport errors and carries the originating request.RequestException– wraps both request and response; used for retry logic and surfaced whenGuzzleraises.HttpException– legacy helper storing aResponseInterface.
This code map should be kept up to date as the implementation evolves to guarantee documentation and user guides remain accurate.