Primordyx Framework Documentation

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
since
1.0.0

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
since
1.0.0

$authUser

Username for HTTP Basic Authentication

private string|null $authUser = null
Tags
since
1.0.0

$bearerToken

OAuth2 Bearer token for Authorization header

private string|null $bearerToken = null
Tags
since
1.0.0

$connectTimeout

Connection establishment timeout in seconds

private int|null $connectTimeout = null
Tags
since
1.0.0

$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
since
1.0.0

$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
since
1.0.0

$proxy

HTTP/HTTPS proxy server URL

private string|null $proxy = null
Tags
since
1.0.0

$timeout

Request timeout in seconds for HTTP response completion

private int|null $timeout = 30
Tags
since
1.0.0

$userAgent

Custom User-Agent string for HTTP requests

private string|null $userAgent = null
Tags
since
1.0.0

$verboseLogging

Enable detailed cURL verbose logging for debugging

private bool $verboseLogging = false
Tags
since
1.0.0

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
since
1.0.0
example
// Named configuration for monitoring
$config = new HttpClientConfig('payment_api');

// Auto-generated name for ad-hoc requests
$config = new HttpClientConfig();
echo $config->name(); // e.g., "brave-elephant-42"

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
since
1.0.0
example
// Add new header
$config->addHeader('Accept', 'application/json');

// Replace existing header
$old = $config->addHeader('Accept', 'application/xml');
// Returns: "application/json"

// Custom authorization
$config->addHeader('Authorization', 'Custom-Scheme token=xyz');
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
since
1.0.0
example
$config = new HttpClientConfig('test');
$config->timeout(60);
$config->bearerToken('abc123');

$array = $config->asArray();
// Returns: ['name' => 'test', 'timeout' => 60, 'bearer_token' => 'abc123', ...]
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
since
1.0.0
example
$config = new HttpClientConfig('api');
$config->addHeader('Accept', 'application/json');

$json = $config->asJson();
error_log("API Config: $json");
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
since
1.0.0
example
// Set secure credentials
$config->authUser('api_user');
$config->authPass('complex_password_123');

// Clear credentials for security
$config->authPass(null);
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
since
1.0.0
example
// Configure API credentials
$config->authUser('api_user');
$config->authPass('secret123');

// Retrieve current username
$username = $config->authUser(); // "api_user"
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
since
1.0.0
example
// OAuth2 API authentication
$config->bearerToken('eyJhbGciOiJIUzI1NiIs...');
// Automatically adds: Authorization: Bearer eyJhbGciOiJIUzI1NiIs...

// API key authentication
$config->bearerToken('sk_live_abc123xyz789');

// Clear token and authorization
$config->bearerToken(null);
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
since
1.0.0
example
// Set 10-second connection timeout for faster failure detection
$config->connectTimeout(10);

// Different timeouts for connection vs response
$config->connectTimeout(10);  // Quick connection required
$config->timeout(300);        // Allow slow responses
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
since
1.0.0
example
$config->addHeader('Accept', 'application/json');
$config->addHeader('Authorization', 'Bearer abc123');

$headers = $config->getAllHeaders();
// Returns: ['Accept: application/json', 'Authorization: Bearer abc123']
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
since
1.0.0
example
$config->addHeader('Content-Type', 'application/json');

$value = $config->getHeader('content-type'); // Case-insensitive
// Returns: "application/json"

$missing = $config->getHeader('Authorization');
// Returns: null
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
since
1.0.0
example
// Both calls are equivalent
$headers1 = $config->getAllHeaders();
$headers2 = $config->headers();
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
since
1.0.0
example
$config = new HttpClientConfig('api_client');
echo $config->name(); // "api_client"
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
since
1.0.0
example
// Basic proxy configuration
$config->proxy('http://proxy.corp.com:8080');

// Proxy with authentication
$config->proxy('http://user:pass@proxy.corp.com:8080');

// HTTPS proxy
$config->proxy('https://secure-proxy.example.com:443');
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
since
1.0.0
example
$config->addHeader('Authorization', 'Bearer abc123');

$removed = $config->removeHeader('authorization'); // Case-insensitive
// Returns: "Bearer abc123"
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
since
1.0.0
example
$config = new HttpClientConfig('reusable');
$config->bearerToken('abc123');
$config->timeout(60);

$config->reset(); // Clear sensitive data
// Name is preserved, but auth and timeout are reset

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
since
1.0.0
example
$newHeaders = [
    'Content-Type: application/json',
    'Authorization: Bearer xyz123',
    'X-Custom-Header: custom-value'
];

$oldHeaders = $config->setAllHeaders($newHeaders);
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
since
1.0.0
example
// Set complete credentials in one call
$config->setBasicAuth('api_user', 'secret_password');

// Equivalent to:
// $config->authUser('api_user');
// $config->authPass('secret_password');

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
since
1.0.0
example
// Set 60-second timeout for slow APIs
$oldTimeout = $config->timeout(60);

// Get current timeout
$current = $config->timeout(); // 60
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
since
1.0.0
example
// Custom User-Agent for specific application
$config->userAgent('MyApp/2.1.4 (+https://myapp.com)');

// Get current User-Agent (auto-generates default if none set)
$ua = $config->userAgent(); // "PrimordyxHttpClient/1.0.0"

// API-specific User-Agent
$config->userAgent('MyBot/1.0 (Webhook-Handler)');
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
since
1.0.0
example
// Enable debugging for problematic API
$config->verboseLogging(true);
$result = HttpClient::get('https://api.example.com', $config);
var_dump($result->verboseLog()); // Detailed cURL communication

// Disable for production
$config->verboseLogging(false);
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
since
1.0.0
Return values
string|null

Value of removed header or null if not found


        
On this page

Search results