HttpClientConfig
in package
HTTP Client Configuration Management for RESTful API Requests
Comprehensive configuration class for HTTP client operations providing secure authentication, custom headers, timeout management, proxy support, and debugging capabilities. Designed to work seamlessly with HttpClient for consistent, secure, and monitorable API communication.
Key Features
- Flexible Authentication: Basic auth, Bearer tokens, and custom authorization headers
- Header Management: Raw string headers supporting complex HTTP header scenarios
- Timeout Control: Separate connection and response timeout configuration
- Security Defaults: Secure configuration options with sensible fallbacks
- Debug Support: Verbose logging and named instances for performance monitoring
- Proxy Support: HTTP/HTTPS proxy configuration for enterprise environments
- Serialization: Export configuration as arrays or JSON for debugging/logging
Authentication Methods
- Basic Auth: Username/password authentication for traditional APIs
- Bearer Tokens: OAuth2 and API key authentication via Authorization header
- Custom Headers: Full control over authentication header format and content
Header Storage Design
Headers are stored as raw strings (not key-value pairs) to support:
- Multiple headers with same key name
- Complex header formats beyond simple key:value pairs
- Exact header formatting control for strict API requirements
- Case-insensitive header matching for HTTP standard compliance
Usage Patterns
// Basic API configuration
$config = new HttpClientConfig('user_api');
$config->timeout(30);
$config->bearerToken('abc123');
// Advanced enterprise configuration
$config = new HttpClientConfig('secure_api');
$config->proxy('http://proxy.corp.com:8080');
$config->setBasicAuth('api_user', 'secret');
$config->addHeader('X-API-Version', '2.1');
$config->verboseLogging(true);
// Use with HttpClient
$result = HttpClient::get('https://api.example.com/users', $config);
Performance Integration
- Named instances integrate with Timer class for performance monitoring
- Automatic timer creation using configuration name for request tracking
- Verbose logging captures detailed cURL communication for debugging
- Serializable configuration enables logging and audit trail creation
Tags
Table of Contents
Properties
- $authPass : string|null
- Password for HTTP Basic Authentication
- $authUser : string|null
- Username for HTTP Basic Authentication
- $bearerToken : string|null
- OAuth2 Bearer token for Authorization header
- $connectTimeout : int|null
- Connection establishment timeout in seconds
- $headers : array<string|int, string>
- Array of HTTP headers stored as raw strings.
- $name : string
- Configuration instance identifier for debugging and performance monitoring
- $proxy : string|null
- HTTP/HTTPS proxy server URL
- $timeout : int|null
- Request timeout in seconds for HTTP response completion
- $userAgent : string|null
- Custom User-Agent string for HTTP requests
- $verboseLogging : bool
- Enable detailed cURL verbose logging for debugging
Methods
- __construct() : mixed
- Initialize HTTP client configuration with optional identifier name
- addHeader() : string|null
- Add or replace HTTP header with case-insensitive key matching
- asArray() : array<string, mixed>
- Export complete configuration as associative array
- asJson() : string
- Export configuration as JSON string for logging or serialization
- authPass() : string|null
- Get or set password for HTTP Basic Authentication
- authUser() : string|null
- Get or set username for HTTP Basic Authentication
- bearerToken() : string
- Get or set OAuth2 Bearer token with automatic Authorization header management
- connectTimeout() : int|null
- Get or set TCP connection establishment timeout in seconds
- getAllHeaders() : array<string|int, string>
- Retrieve all configured headers as raw string array
- getHeader() : string|null
- Retrieve single header value by name with case-insensitive lookup
- headers() : array<string|int, string>
- Convenience alias for getAllHeaders()
- name() : string
- Get the configuration instance identifier
- proxy() : string|null
- Get or set HTTP/HTTPS proxy server configuration
- removeHeader() : string|null
- Remove header by name with case-insensitive matching
- reset() : void
- Reset all configuration options to default values
- setAllHeaders() : array<string|int, string>
- Replace entire header collection with new raw header strings
- setBasicAuth() : void
- Configure complete HTTP Basic Authentication credentials
- timeout() : int|null
- Get or set HTTP response timeout in seconds
- userAgent() : string
- Get or set User-Agent header with automatic default generation
- verboseLogging() : bool
- Get or set verbose cURL logging for debugging HTTP communication
- removeAndCapture() : string|null
- Remove first matching header and return its value
Properties
$authPass
Password for HTTP Basic Authentication
private
string|null
$authPass
= null
Tags
$authUser
Username for HTTP Basic Authentication
private
string|null
$authUser
= null
Tags
$bearerToken
OAuth2 Bearer token for Authorization header
private
string|null
$bearerToken
= null
Tags
$connectTimeout
Connection establishment timeout in seconds
private
int|null
$connectTimeout
= null
Tags
$headers
Array of HTTP headers stored as raw strings.
private
array<string|int, string>
$headers
= []
Each item should be a full header string, e.g., "Authorization: Bearer abc123". Note: This is NOT a key-value associative array, because some HTTP headers may appear multiple times or have structures not representable as a simple key => value pair.
Examples:
- "Authorization: Bearer xyz"
- "Accept: application/json"
- "X-Custom-Flag"
Internal methods normalize header keys for case-insensitive matching when adding/removing headers.
Tags
$name
Configuration instance identifier for debugging and performance monitoring
private
string
$name
Used for Timer integration, logging, and distinguishing between concurrent HTTP requests. Automatically generated using RandomStuff::words() if not provided in constructor. Never transmitted in HTTP requests - purely internal identifier.
Tags
$proxy
HTTP/HTTPS proxy server URL
private
string|null
$proxy
= null
Tags
$timeout
Request timeout in seconds for HTTP response completion
private
int|null
$timeout
= 30
Tags
$userAgent
Custom User-Agent string for HTTP requests
private
string|null
$userAgent
= null
Tags
$verboseLogging
Enable detailed cURL verbose logging for debugging
private
bool
$verboseLogging
= false
Tags
Methods
__construct()
Initialize HTTP client configuration with optional identifier name
public
__construct([string $name = '' ]) : mixed
Creates new configuration instance with secure defaults and optional naming for debugging and performance monitoring. Name can be integrated with Timer class for request tracking and verbose logging identification.
Name Generation
- Uses provided name if specified
- Generates random human-readable name via RandomStuff::words() if empty
- Name used for Timer integration and request identification
- Never transmitted over HTTP - purely internal identifier
Default Configuration
- 30-second request timeout
- No authentication configured
- Empty headers array
- Verbose logging disabled
- Default User-Agent auto-generated when first accessed
Parameters
- $name : string = ''
-
Optional identifier for debugging and performance monitoring
Tags
addHeader()
Add or replace HTTP header with case-insensitive key matching
public
addHeader(string $key, string $value) : string|null
Adds new header or replaces existing header with same key name. Uses case-insensitive matching to prevent duplicate headers while maintaining exact case formatting in stored header string. Returns previous value if header was replaced.
Replacement Behavior
- Removes any existing header with matching key (case-insensitive)
- Adds new header with exact case formatting as provided
- Returns previous header value if one was replaced
- Supports complex authorization schemes and custom header formats
Parameters
- $key : string
-
Header name (e.g., 'Authorization', 'Content-Type')
- $value : string
-
Header value (e.g., 'Bearer abc123', 'application/json')
Tags
Return values
string|null —Previous value if header was replaced, null if new header
asArray()
Export complete configuration as associative array
public
asArray() : array<string, mixed>
Returns all configuration settings in array format suitable for debugging, logging, serialization, or configuration transfer between instances. Includes all authentication, timeout, proxy, and header settings.
Tags
Return values
array<string, mixed> —Complete configuration array with all settings
asJson()
Export configuration as JSON string for logging or serialization
public
asJson() : string
Converts complete configuration to JSON format using standard json_encode. Useful for configuration logging, debugging output, or storing configuration state for later restoration.
Tags
Return values
string —JSON-encoded configuration string
authPass()
Get or set password for HTTP Basic Authentication
public
authPass([string|null $pass = null ]) : string|null
Configures password portion of HTTP Basic Authentication. Used with authUser() to create complete credentials for APIs requiring username/password authentication. Password is stored in memory and base64-encoded during HTTP request transmission.
Parameters
- $pass : string|null = null
-
Password to set (null to get current value)
Tags
Return values
string|null —Previous password value before any changes
authUser()
Get or set username for HTTP Basic Authentication
public
authUser([string|null $user = null ]) : string|null
Configures username portion of HTTP Basic Authentication. Used with authPass() to create Authorization header for APIs requiring traditional username/password authentication. Credentials are base64-encoded by HttpClient during request.
Parameters
- $user : string|null = null
-
Username to set (null to get current value)
Tags
Return values
string|null —Previous username value before any changes
bearerToken()
Get or set OAuth2 Bearer token with automatic Authorization header management
public
bearerToken([string|null $token = null ]) : string
Configures Bearer token authentication by setting both internal token storage and Authorization header automatically. Handles OAuth2, API keys, and other bearer token authentication schemes. Automatically formats Authorization header.
Header Management
- Automatically adds "Authorization: Bearer {token}" header
- Removes any existing Authorization header before adding new one
- Token stored separately for debugging and configuration export
- Header formatting follows OAuth2 RFC standards
Parameters
- $token : string|null = null
-
Bearer token to set (null to get current value)
Tags
Return values
string —Previous bearer token value before any changes
connectTimeout()
Get or set TCP connection establishment timeout in seconds
public
connectTimeout([int|null $seconds = null ]) : int|null
Configures maximum time to wait for initial TCP connection to remote server. Separate from response timeout to handle slow connection scenarios differently from slow response scenarios. Maps to cURL CURLOPT_CONNECTTIMEOUT.
Parameters
- $seconds : int|null = null
-
Connection timeout in seconds (null to get current value)
Tags
Return values
int|null —Previous connection timeout value before any changes
getAllHeaders()
Retrieve all configured headers as raw string array
public
getAllHeaders() : array<string|int, string>
Returns complete header collection as array of formatted header strings. Headers are not parsed into key-value pairs to preserve exact formatting and support complex HTTP header scenarios.
Tags
Return values
array<string|int, string> —Array of complete header strings in "Key: Value" format
getHeader()
Retrieve single header value by name with case-insensitive lookup
public
getHeader(string $key) : string|null
Searches configured headers for matching key name and returns the value portion. Uses case-insensitive matching for HTTP standard compliance while preserving exact header formatting.
Parameters
- $key : string
-
Header name to search for (e.g., 'Authorization', 'content-type')
Tags
Return values
string|null —Header value if found, null if header not configured
headers()
Convenience alias for getAllHeaders()
public
headers() : array<string|int, string>
Returns all configured headers as raw string array. Provided for improved code readability and developer convenience when accessing header collection.
Tags
Return values
array<string|int, string> —Array of complete header strings in "Key: Value" format
name()
Get the configuration instance identifier
public
name() : string
Returns the name used for debugging, performance monitoring, and Timer integration. Name is either provided during construction or auto-generated using random words.
Tags
Return values
string —Configuration instance identifier
proxy()
Get or set HTTP/HTTPS proxy server configuration
public
proxy([string|null $proxy = null ]) : string|null
Configures proxy server for routing HTTP requests through corporate firewalls or privacy networks. Supports both HTTP and HTTPS proxy protocols with optional authentication via proxy URL format.
Parameters
- $proxy : string|null = null
-
Proxy URL to set (null to get current value)
Tags
Return values
string|null —Previous proxy configuration before any changes
removeHeader()
Remove header by name with case-insensitive matching
public
removeHeader(string $key) : string|null
Removes first header matching the specified key name using case-insensitive comparison. Returns the value of removed header for confirmation or restoration.
Parameters
- $key : string
-
Header name to remove (e.g., 'Authorization', 'Content-Type')
Tags
Return values
string|null —Value of removed header or null if header not found
reset()
Reset all configuration options to default values
public
reset() : void
Clears all headers, authentication, timeouts, and other settings while preserving the configuration instance name. Useful for reusing configuration objects or clearing sensitive data after use.
Reset Behavior
- Clears all headers array
- Resets timeout to 30 seconds default
- Clears authentication credentials
- Removes proxy configuration
- Disables verbose logging
- Preserves instance name (does not change)
Tags
setAllHeaders()
Replace entire header collection with new raw header strings
public
setAllHeaders([array<string|int, string> $headers = [] ]) : array<string|int, string>
Completely replaces current headers with provided array. Each header must be formatted as complete "Key: Value" string. Does not validate header format or content - provides maximum flexibility for complex HTTP scenarios.
Header Format Requirements
- Each array element should be complete header string
- Format: "HeaderName: HeaderValue"
- Supports non-standard headers and complex authorization schemes
- No automatic validation or normalization applied
Parameters
- $headers : array<string|int, string> = []
-
Array of complete header strings in "Key: Value" format
Tags
Return values
array<string|int, string> —Previous headers that were replaced
setBasicAuth()
Configure complete HTTP Basic Authentication credentials
public
setBasicAuth([string $user = '' ][, string $pass = '' ]) : void
Convenience method for setting both username and password in single call. Equivalent to calling authUser() and authPass() separately but more readable for initialization scenarios.
Parameters
- $user : string = ''
-
Username for basic authentication
- $pass : string = ''
-
Password for basic authentication
Tags
timeout()
Get or set HTTP response timeout in seconds
public
timeout([int|null $seconds = null ]) : int|null
Configures maximum time to wait for complete HTTP response after connection is established. Does not include connection establishment time. Used by cURL CURLOPT_TIMEOUT for response timeout enforcement.
Parameters
- $seconds : int|null = null
-
Response timeout in seconds (null to get current value)
Tags
Return values
int|null —Previous timeout value before any changes
userAgent()
Get or set User-Agent header with automatic default generation
public
userAgent([string|null $ua = null ]) : string
Configures User-Agent header for HTTP requests with intelligent default handling. If no User-Agent is explicitly set, automatically generates default using PrimordyxInfo::version() for framework identification and compatibility tracking.
Default Behavior
- Auto-generates default User-Agent if none configured: "PrimordyxHttpClient/{version}"
- Automatically adds User-Agent header when value is set or accessed
- Returns current or default User-Agent string (never null)
- Default helps API providers identify Primordyx-based applications
Parameters
- $ua : string|null = null
-
User-Agent string to set (null to get current/default value)
Tags
Return values
string —Current User-Agent string (previous value if setting, current/default if getting)
verboseLogging()
Get or set verbose cURL logging for debugging HTTP communication
public
verboseLogging([bool|null $value = null ]) : bool
Enables detailed cURL verbose output capture for troubleshooting HTTP requests. Verbose logs include connection details, SSL handshake info, header transmission, and protocol-level communication. Logs accessible via HttpResult object.
Parameters
- $value : bool|null = null
-
Enable verbose logging (null to get current value)
Tags
Return values
bool —Previous verbose logging state before any changes
removeAndCapture()
Remove first matching header and return its value
private
removeAndCapture(string $key) : string|null
Internal method for case-insensitive header removal with value capture. Used by header replacement operations to prevent duplicate headers while preserving previous values for return.
Parameters
- $key : string
-
Header name to remove (without colon)
Tags
Return values
string|null —Value of removed header or null if not found