VOOZH about

URL: https://deepwiki.com/hypervel/http-client/4.2-pendingrequest

⇱ PendingRequest | hypervel/http-client | DeepWiki


Loading...
Menu

PendingRequest

The PendingRequest class is the primary interface for building and executing HTTP requests in the Hypervel HTTP Client library. It provides a fluent configuration API for setting request parameters, manages the request execution lifecycle, and coordinates the handler stack that processes requests and responses.

This document covers the comprehensive functionality of PendingRequest including configuration methods, execution flow, and handler stack architecture. For information about the Factory that creates PendingRequest instances, see Factory. For details about the Request wrapper class, see Request. For response handling, see Response.

Sources: src/PendingRequest.php1-1337


Class Overview

The PendingRequest class serves as the central orchestrator for HTTP requests, accumulating configuration through method chaining and executing requests through Guzzle's HTTP client.

Core Responsibilities

ResponsibilityDescription
Configuration BuilderProvides fluent methods to configure headers, authentication, timeouts, body formats, and other request options
Request ExecutorManages synchronous and asynchronous request execution through Guzzle
Handler Stack ManagerBuilds and coordinates the middleware/handler stack for request processing
Retry CoordinatorImplements retry logic with configurable delays and conditions
Event DispatcherDispatches lifecycle events (RequestSending, ResponseReceived, ConnectionFailed)
Testing IntegrationSupports request stubbing and recording for testing purposes

Sources: src/PendingRequest.php38-210


Key Properties


Figure 1: PendingRequest Property Organization

The properties are organized into logical groups that represent different aspects of request configuration and execution state.

Sources: src/PendingRequest.php43-171


Initialization and Default Configuration

The PendingRequest constructor establishes default configuration and initializes collections for middleware and callbacks:


Figure 2: PendingRequest Initialization Sequence

Default Configuration Values:

OptionDefault ValuePurpose
connect_timeout10 secondsMaximum time to establish connection
timeout30 secondsMaximum time for complete request
http_errorsfalseGuzzle should not throw on 4xx/5xx status
crypto_methodSTREAM_CRYPTO_METHOD_TLSv1_2_CLIENTTLS version requirement
bodyFormat'json'Default request body format

Sources: src/PendingRequest.php187-210


Configuration API

The PendingRequest class provides an extensive fluent API for configuring HTTP requests. All configuration methods return $this to enable method chaining.

URL Configuration


Figure 3: URL Configuration Methods

MethodParametersDescription
baseUrl(string $url)Base URLSets the base URL that will be prepended to relative URLs
withUrlParameters(array $parameters)URL template parametersParameters for RFC 6570 URI template expansion

Example URL expansion: A URL like /users/{id}/posts with urlParameters = ['id' => 123] becomes /users/123/posts.

Sources: src/PendingRequest.php215-220 src/PendingRequest.php412-417 src/PendingRequest.php799-802

Body Format Configuration


Figure 4: Body Format Configuration Flow

MethodBody FormatContent-TypeUse Case
asJson()'json'application/jsonSending JSON data (default)
asForm()'form_params'application/x-www-form-urlencodedSending form data
asMultipart()'multipart'multipart/form-dataUploading files
withBody($content, $contentType)'body'CustomSending raw body content

Sources: src/PendingRequest.php225-299

File Attachments

The attach() method adds files to multipart requests:

ParameterTypeDescription
$name`stringarray`
$contents`resourcestring`
$filename`stringnull`
$headersarrayOptional per-file headers

When $name is an array, each element should be an array containing ['name', 'contents', 'filename', 'headers'].

Sources: src/PendingRequest.php257-281

Headers Configuration


Figure 5: Headers Configuration Methods

Sources: src/PendingRequest.php314-407

Authentication Methods

MethodParametersResult
withBasicAuth($username, $password)Username, passwordSets options['auth'] = [$username, $password]
withDigestAuth($username, $password)Username, passwordSets options['auth'] = [$username, $password, 'digest']
withToken($token, $type = 'Bearer')Token, token typeSets Authorization header to "{$type} {$token}"

Sources: src/PendingRequest.php372-397

Query Parameters and Cookies

MethodPurpose
withQueryParameters(array $parameters)Merges query parameters into options['query']
withCookies(array $cookies, string $domain)Creates CookieJar and merges into options['cookies']

Sources: src/PendingRequest.php304-311 src/PendingRequest.php422-429

Timeout Configuration

MethodParameterPurpose
timeout(float|int $seconds)Timeout in secondsSets options['timeout'] - total request timeout
connectTimeout(float|int $seconds)Timeout in secondsSets options['connect_timeout'] - connection establishment timeout

Sources: src/PendingRequest.php476-491

Redirect and SSL Configuration

MethodPurpose
maxRedirects(int $max)Sets options['allow_redirects']['max']
withoutRedirecting()Sets options['allow_redirects'] = false
withoutVerifying()Sets options['verify'] = false (disables SSL verification)

Sources: src/PendingRequest.php434-459

Response Sink Configuration

The sink($to) method specifies where the response body should be written:


This is useful for downloading large files without loading them entirely into memory.

Sources: src/PendingRequest.php466-471


Retry Configuration

The retry() method configures automatic retry behavior for failed requests:


Figure 6: Retry Logic Flow

Parameters:

ParameterTypeDescription
$timesint|arrayNumber of attempts, or array of delay values
$sleepMillisecondsint|ClosureDelay between retries (ms), or callback receiving ($attempt, $exception)
$whencallable|nullCallback receiving ($exception, $pendingRequest) to determine if retry should occur
$throwboolWhether to throw exception when all retries are exhausted (default: true)

Sources: src/PendingRequest.php496-508 src/PendingRequest.php729-793


Error Handling Configuration


Figure 7: Error Handling Configuration and Execution

Sources: src/PendingRequest.php566-591 src/PendingRequest.php752-757


Middleware Configuration


Figure 8: Middleware Configuration Methods

MethodPurposeSignature
withMiddleware(callable $middleware)Adds generic Guzzle middlewarefunction($handler) { return function($request, $options) use ($handler) {...}; }
withRequestMiddleware(callable $middleware)Adds request-transforming middlewarefunction(RequestInterface $request) { return $modifiedRequest; }
withResponseMiddleware(callable $middleware)Adds response-transforming middlewarefunction(ResponseInterface $response) { return $modifiedResponse; }
beforeSending(callable $callback)Adds callback executed immediately before sendingfunction(Request $request, array $options, PendingRequest $pr) {...}

Sources: src/PendingRequest.php524-561


Request Execution Methods

The PendingRequest class provides convenience methods for common HTTP verbs:


Figure 9: Request Execution Flow

HTTP Method Signatures:

MethodParametersBody LocationReturns
get(string $url, $query = null)URL, optional query parametersN/A (GET requests)Response|PromiseInterface
head(string $url, $query = null)URL, optional query parametersN/A (HEAD requests)Response|PromiseInterface
post(string $url, $data = [])URL, request body dataUses $this->bodyFormatResponse|PromiseInterface
patch(string $url, $data = [])URL, request body dataUses $this->bodyFormatResponse|PromiseInterface
put(string $url, $data = [])URL, request body dataUses $this->bodyFormatResponse|PromiseInterface
delete(string $url, $data = [])URL, optional request body dataUses $this->bodyFormatResponse|PromiseInterface

Sources: src/PendingRequest.php628-705 src/PendingRequest.php713-794


Handler Stack Architecture

The handler stack is the core mechanism through which requests flow. It consists of multiple layers that process requests and responses:


Figure 10: Handler Stack Architecture

Handler Stack Construction Process

The buildHandlerStack() method creates a HandlerStack and populates it with handlers in Last-In-First-Out order:

  1. Base Handler: The Guzzle HTTP handler (can be customized with setHandler())
  2. Stub Handler: Intercepts requests for testing
  3. Recorder Handler: Records request/response pairs
  4. Before Sending Handler: Executes callbacks and dispatches events
  5. User Middleware: Custom middleware added by the user

Sources: src/PendingRequest.php1059-1078

Before Sending Handler


Figure 11: Before Sending Handler Execution

The handler wraps request execution and runs all beforeSendingCallbacks before passing control to the next handler. The default callback stores the request reference and dispatches the RequestSending event.

Sources: src/PendingRequest.php1083-1091 src/PendingRequest.php1173-1191

Recorder Handler

The recorder handler captures request/response pairs for test assertions:


Figure 12: Recorder Handler Flow

This handler records all requests and responses, enabling assertions like assertSent(), assertNotSent(), etc.

Sources: src/PendingRequest.php1095-1111

Stub Handler

The stub handler intercepts requests for testing and returns fake responses:


Figure 13: Stub Handler Decision Flow

The stub handler checks if any registered stub callback matches the request. If no match is found and preventStrayRequests is enabled, it throws an exception.

Sources: src/PendingRequest.php1116-1147 src/PendingRequest.php1154-1168


Request Execution Lifecycle

Synchronous Request Flow


Figure 14: Synchronous Request Execution Flow

Sources: src/PendingRequest.php713-794 src/PendingRequest.php953-972

Asynchronous Request Flow

When async(true) is called, the request execution returns a PromiseInterface instead of a Response:


Figure 15: Asynchronous Request Flow

Key differences in async mode:

  • Returns PromiseInterface instead of Response
  • Retry logic is recursive (creates new promises)
  • Exceptions are returned as promise rejection values
  • Handler uses requestAsync() instead of request()

Sources: src/PendingRequest.php853-885 src/PendingRequest.php892-946 src/PendingRequest.php1237-1242


Client Building and Connection Management


Figure 16: Client Building and Connection Management

Connection Configuration:

The connection() method allows specifying a named connection and optional configuration:


Sources: src/PendingRequest.php1035-1054 src/PendingRequest.php1059-1078 src/PendingRequest.php1315-1336


Testing Integration

The PendingRequest class integrates with the testing infrastructure through stub callbacks and prevention of stray requests:

Stub Callback Registration


Figure 17: Stub Callback System

Stub Callback Signature:


Sources: src/PendingRequest.php1215-1222 src/PendingRequest.php1116-1147

Preventing Stray Requests

The preventStrayRequests() method ensures that tests fail if an unexpected HTTP request is made:


When enabled, the stub handler throws a RuntimeException if no stub callback matches the request.

Sources: src/PendingRequest.php1227-1232 src/PendingRequest.php1127-1131


Event Dispatching

The PendingRequest class dispatches three lifecycle events:

Event Types and Timing

Event ClassWhen DispatchedPayload
RequestSendingImmediately before request is sentRequest object
ResponseReceivedAfter successful responseRequest and Response objects
ConnectionFailedWhen connection failsRequest and ConnectionException

Event Dispatch Flow


Figure 18: Event Dispatching Lifecycle

Events are only dispatched if the Factory has an event dispatcher configured (via $factory->getDispatcher()).

Sources: src/PendingRequest.php1255-1282 src/PendingRequest.php202-209 src/PendingRequest.php738 src/PendingRequest.php779 src/PendingRequest.php859 src/PendingRequest.php866


Debugging Methods

Dump and DD

Two methods assist with debugging requests:

MethodPurpose
dump(...$values)Dumps request, options, and any provided values before sending
dd(...$values)Dumps and dies (exits script) after dumping

Both methods use Symfony's VarDumper component and work by adding a beforeSending callback.

Example:


Sources: src/PendingRequest.php596-621


Option Merging

The PendingRequest class carefully merges options to ensure correct precedence:

Mergeable Options

The following options use array_merge_recursive:

  • cookies
  • form_params
  • headers
  • json
  • multipart
  • query

Other options are replaced rather than merged.

Merge Process


Figure 19: Option Merging Strategy

Sources: src/PendingRequest.php513-521 src/PendingRequest.php1196-1202 src/PendingRequest.php175-182


Advanced Option Methods

Custom Options

The withOptions(array $options) method allows setting any Guzzle option:


Transfer Statistics

The TransferStats object is automatically captured and stored in $this->transferStats. It contains:

  • Effective URI
  • Transfer time
  • Request/response sizes
  • Handler stats

Access it via the Response object after request execution.

Sources: src/PendingRequest.php513-521 src/PendingRequest.php958-964


Request Data Parsing

Before execution, request data is parsed and attached for testing assertions:


Figure 20: Request Data Parsing Flow

This parsed data is attached to the Request object for use in assertions and callbacks.

Sources: src/PendingRequest.php977-1002


Response Population

After receiving a response, additional metadata is populated:


This ensures the Response object has access to:

  • CookieJar with any cookies set during the request
  • TransferStats with timing and transfer information

Sources: src/PendingRequest.php1023-1030


Traits and Extensibility

The PendingRequest class uses two traits for extensibility:

TraitSource PackagePurpose
Conditionablehyperf/conditionableProvides when() and unless() methods for conditional configuration
Macroablehyperf/macroableAllows adding custom methods at runtime

Conditionable Example


Macroable Example


Sources: src/PendingRequest.php40-41


Summary

The PendingRequest class orchestrates the complete HTTP request lifecycle:

  1. Configuration Accumulation: Fluent methods build up request options
  2. Handler Stack Construction: Middleware, callbacks, and testing infrastructure are assembled
  3. Request Execution: Synchronous or asynchronous execution through Guzzle
  4. Retry Logic: Automatic retry with configurable conditions and delays
  5. Event Dispatching: Lifecycle events for monitoring and logging
  6. Response Processing: Wrapping and populating response data
  7. Testing Integration: Stubbing and recording for test assertions

The class maintains clear separation between configuration state (properties), execution logic (methods), and extensibility (traits), making it both powerful and maintainable.

Sources: src/PendingRequest.php1-1337

Refresh this wiki

On this page