VOOZH about

URL: https://deepwiki.com/hypervel/http-client/4.1-factory

⇱ Factory | hypervel/http-client | DeepWiki


Loading...
Menu

Factory

The Factory class serves as the primary entry point for creating and managing HTTP requests in the Hypervel HTTP Client. It acts as a factory for PendingRequest instances, manages global configuration that applies to all requests, provides comprehensive testing utilities for faking HTTP responses, and handles connection management including connection pooling.

For information about configuring and executing individual requests, see PendingRequest. For details on testing utilities like assertions, see Assertions.

Sources: src/Factory.php1-526


Core Responsibilities

The Factory class fulfills four primary roles within the HTTP client architecture:

ResponsibilityDescriptionKey Methods
Request CreationInstantiates PendingRequest objects with pre-configured global settingscreatePendingRequest(), newPendingRequest(), __call()
Global ConfigurationManages middleware and options applied to all requests created by the factoryglobalMiddleware(), globalRequestMiddleware(), globalResponseMiddleware(), globalOptions()
Testing SupportProvides request faking, stubbing, recording, and assertion capabilitiesfake(), stubUrl(), sequence(), assertSent(), recorded()
Connection ManagementManages named HTTP client connections with optional connection poolingregisterConnection(), getClient(), resolve()

The Factory utilizes the Macroable trait src/Factory.php34-36 for runtime extensibility and the HasPoolProxy trait src/Factory.php33 for connection pooling capabilities.

Sources: src/Factory.php31-96


Factory Architecture

The following diagram illustrates the Factory's internal structure and its relationships with other components:


Sources: src/Factory.php38-96


Request Creation Flow

The Factory creates PendingRequest instances through a multi-step process that applies global configuration and testing hooks:


The __call() magic method src/Factory.php518-525 enables the Factory to act as a proxy for PendingRequest methods. When a method is called on the Factory that doesn't exist, it creates a new PendingRequest and forwards the method call to it.

The createPendingRequest() method src/Factory.php404-409 orchestrates the creation process:

  1. Calls newPendingRequest() to instantiate the PendingRequest src/Factory.php414-417
  2. Applies global middleware from $this->globalMiddleware
  3. Evaluates $this->globalOptions (if it's a Closure) and applies them
  4. Configures stub callbacks via stub()
  5. Sets the preventStrayRequests flag

Sources: src/Factory.php404-417 src/Factory.php518-525


Global Configuration

Global configuration allows you to define settings that apply to every request created by the Factory.

Global Middleware

The Factory supports three types of global middleware:

MethodPurposeImplementation
globalMiddleware()Adds raw Guzzle middlewareStored directly in $globalMiddleware array
globalRequestMiddleware()Adds request-mapping middlewareWraps callable with Middleware::mapRequest()
globalResponseMiddleware()Adds response-mapping middlewareWraps callable with Middleware::mapResponse()

Each method appends to the $globalMiddleware array src/Factory.php41 which is passed to every PendingRequest during construction src/Factory.php416


Sources: src/Factory.php99-126 src/Factory.php41 src/Factory.php416

Global Options

The globalOptions() method src/Factory.php131-136 sets options that will be merged into every request. The options can be provided as either an array or a Closure that returns an array, allowing for dynamic option generation.

When creating a PendingRequest, the Factory evaluates the global options using PHP's value() helper function src/Factory.php416 which executes Closures and returns the result.

Sources: src/Factory.php131-136 src/Factory.php46 src/Factory.php416


Testing Support

The Factory provides comprehensive testing capabilities through request stubbing, response faking, and request recording.

Stubbing Architecture


Sources: src/Factory.php51-72 src/Factory.php183-260 src/Factory.php311-382

Fake Response Creation

The static response() method src/Factory.php141-155 creates fake PSR-7 responses wrapped in Guzzle promises:

  • Array bodies: Automatically JSON-encoded with Content-Type: application/json header
  • String/int bodies: Passed directly to PSR-7 response
  • Returns a PromiseInterface using Create::promiseFor()

The static failedConnection() method src/Factory.php160-170 creates a Closure that returns a rejected promise containing a ConnectException, simulating network failures.

Sources: src/Factory.php141-170

Stub Registration

The fake() method src/Factory.php183-224 is the core stubbing mechanism:

  1. Enables recording: Calls record() to set $this->recording = true src/Factory.php185
  2. Clears previous recordings: Resets $this->recorded = [] src/Factory.php187
  3. Processes callback:
    • If null: Creates default stub returning 200 OK
    • If array: Calls stubUrl() for each URL pattern
    • If callable: Wraps in handler that resolves nested Closures

The stubUrl() method src/Factory.php239-260 registers URL-specific stubs using wildcard pattern matching via Str::is() src/Factory.php242

Sources: src/Factory.php183-260

Request Recording

When $this->recording is true, the Factory records all request/response pairs via recordRequestResponsePair() src/Factory.php301-306 The recorded pairs are stored in $this->recorded as an array of [Request, Response] tuples.

The recorded() method src/Factory.php387-399 returns a Collection of recorded pairs, optionally filtered by a callback.

Sources: src/Factory.php56-61 src/Factory.php291-306 src/Factory.php387-399

Assertions

The Factory provides PHPUnit-compatible assertion methods:

MethodPurposeImplementation
assertSent()Asserts a request matching callback was sentFilters recorded() and asserts count > 0
assertNotSent()Asserts no request matching callback was sentFilters recorded() and asserts count == 0
assertSentCount()Asserts exact number of requests sentUses PHPUnit::assertCount()
assertNothingSent()Asserts no requests were sentUses PHPUnit::assertEmpty()
assertSentInOrder()Asserts requests sent in specific orderValidates each index against callback
assertSequencesAreEmpty()Asserts all response sequences exhaustedChecks isEmpty() on each sequence

Sources: src/Factory.php311-382

Stray Request Prevention

The preventStrayRequests() method src/Factory.php265-270 sets a flag that causes unstubbed requests to throw exceptions during testing. This ensures all HTTP requests are explicitly faked.

The preventingStrayRequests() method src/Factory.php275-278 checks the flag state, while allowStrayRequests() src/Factory.php283-286 disables it.

Sources: src/Factory.php70 src/Factory.php265-286


Connection Management

The Factory manages named HTTP client connections with optional connection pooling support.

Connection Registration


The registerConnection() method src/Factory.php438-444 registers a named connection by:

  1. Adding the name to $this->poolables array via addPoolable() (from HasPoolProxy trait)
  2. Storing configuration in $this->connectionConfigs via setConnectionConfig()

Sources: src/Factory.php438-444 src/Factory.php508-513

Client Resolution

The getClient() method src/Factory.php451-454 delegates to resolve() src/Factory.php461-476 which:

  1. For unnamed connections: Creates a standard Guzzle Client via createClient() src/Factory.php464
  2. For named connections:

The createClient() method src/Factory.php481-487 instantiates a Guzzle Client with:

  • The provided HandlerStack
  • Cookie support enabled ('cookies' => true)

Sources: src/Factory.php451-487 src/Factory.php73 src/Factory.php78-83


Response Sequences

The sequence() method src/Factory.php175-178 creates ResponseSequence instances for returning ordered fake responses. Each sequence is stored in $this->responseSequences for later validation via assertSequencesAreEmpty().

The fakeSequence() method src/Factory.php229-234 provides a convenient way to create a sequence and immediately register it for a specific URL pattern.

Sources: src/Factory.php66 src/Factory.php175-178 src/Factory.php229-234


Event Dispatcher Integration

The Factory accepts an optional EventDispatcherInterface in its constructor src/Factory.php93-96 which is stored in $this->dispatcher src/Factory.php93 This dispatcher is passed to each PendingRequest during creation and is used to dispatch HTTP lifecycle events.

The getDispatcher() method src/Factory.php422-425 provides access to the dispatcher instance.

Sources: src/Factory.php93-96 src/Factory.php422-425


Method Categories Reference

Request Creation

Global Configuration

Response Creation

Stub Registration

Stray Request Control

Recording

Assertions

Connection Management

Event System

Sources: src/Factory.php1-526