Primordyx Framework Documentation

HttpClient
in package

Modern HTTP Client with cURL Backend and Comprehensive Request Support

Static HTTP client providing secure, configurable web requests with full RESTful method support, automatic performance monitoring, request/response debugging, and optional mocking capabilities. Built on cURL with enterprise-grade security and monitoring features.

Key Features

  • RESTful Methods: Complete support for GET, POST, PUT, DELETE, and custom HTTP methods
  • JSON Integration: Native JSON encoding with automatic Content-Type header management
  • Security First: Basic auth, Bearer tokens, custom headers with secure defaults
  • Performance Monitoring: Automatic Timer integration via HttpResult for request tracking
  • Debug Support: Verbose cURL logging, response inspection, and request replay tools
  • Test-Friendly: Built-in mocking system for unit testing and development
  • Configuration Driven: Flexible request configuration via HttpClientConfig objects

Request Flow Architecture

  1. Method Call: Developer calls static method (get, post, etc.)
  2. Configuration: HttpClientConfig provides headers, auth, timeouts
  3. HttpResult Creation: Automatic timer start and request tracking
  4. cURL Execution: Secure HTTP request with comprehensive error handling
  5. Response Processing: Headers, body, and metadata captured in HttpResult
  6. Performance Tracking: Timer stopped with detailed metrics collection

Security Features

  • Secure Defaults: HTTPS preferred, secure authentication handling
  • Header Management: Case-insensitive header handling with duplicate support
  • Authentication: HTTP Basic Auth and OAuth2 Bearer token support
  • Request Isolation: Each request isolated with separate configuration
  • Error Handling: Comprehensive cURL error capture without information leakage

Usage Patterns

// Simple GET request
$result = HttpClient::get('https://api.example.com/users');

// POST with authentication
$config = new HttpClientConfig('api_request');
$config->bearerToken('abc123');
$result = HttpClient::postJson('https://api.example.com/users', $userData, $config);

// Advanced configuration
$config = new HttpClientConfig();
$config->timeout(60);
$config->setBasicAuth('user', 'pass');
$config->addHeader('X-Custom', 'value');
$result = HttpClient::put('https://api.example.com/resource/123', $data, $config);

Performance and Debugging

  • HttpResult objects automatically track request timing via Timer integration
  • Verbose logging captures complete cURL communication for troubleshooting
  • Request/response inspection available through HttpResult methods
  • Last request always accessible via lastHttpResult() for debugging

Testing and Mocking

  • Complete request mocking via fakeResponder() for unit tests
  • Mock responses return proper HttpResult objects for compatibility
  • EventManager integration for request lifecycle monitoring
  • Legacy utilities for cURL command generation and file downloads
Tags
since
1.0.0

Table of Contents

Properties

$lastHttpResult  : HttpResult|null
Most recently executed HTTP request result for debugging and inspection
$fakeResponder  : callable|null
Optional mock response handler for testing and development

Methods

buildCurlCommand()  : string
Generate equivalent cURL command line for debugging and testing purposes
delete()  : HttpResult
Execute HTTP DELETE request to remove resource from remote endpoint
downloadToFile()  : bool
Download file from URL directly to local filesystem using cURL
fakeResponder()  : void
Configure mock response handler for testing and development
get()  : HttpResult
Execute HTTP GET request to retrieve data from remote endpoint
lastHttpResult()  : HttpResult
Retrieve the most recent HttpResult object for debugging and inspection
post()  : HttpResult
Execute HTTP POST request to send data to remote endpoint
postJson()  : HttpResult
Execute HTTP POST request with automatic JSON encoding and headers
put()  : HttpResult
Execute HTTP PUT request to update or create resource at specific endpoint
request()  : HttpResult
Core HTTP request implementation using cURL

Properties

$lastHttpResult

Most recently executed HTTP request result for debugging and inspection

public static HttpResult|null $lastHttpResult = null

Automatically populated with HttpResult object from each HTTP request. Provides access to last request details without requiring explicit result storage. Useful for debugging, logging, and post-request analysis.

Tags
since
1.0.0

$fakeResponder

Optional mock response handler for testing and development

protected static callable|null $fakeResponder = null

When configured, this callable intercepts all HTTP requests and returns mock HttpResult objects instead of performing real network requests. Essential for unit testing and development environments requiring predictable API responses.

Signature: function(string $method, string $url, mixed $payload, HttpClientConfig $config): HttpResult

Tags
since
1.0.0

Methods

buildCurlCommand()

Generate equivalent cURL command line for debugging and testing purposes

public static buildCurlCommand(string $url, array<string|int, string> $headers, mixed $payload) : string

Legacy utility that constructs shell-safe cURL command equivalent to HttpClient request parameters. Useful for debugging, documentation, and manual request testing outside of PHP environment.

Command Generation

  • Escapes all arguments for shell safety using escapeshellarg()
  • Includes headers with -H flags
  • Handles payload data with -d flag
  • Uses POST method by default (legacy behavior)
  • Generates executable command for terminal use
Parameters
$url : string

Target URL for the cURL command

$headers : array<string|int, string>

Raw header strings (e.g., "Content-Type: application/json")

$payload : mixed

Request body data (string or array)

Tags
since
1.0.0
example

Generate Debug Command

$headers = ['Content-Type: application/json', 'Authorization: Bearer abc123'];
$payload = '{"name": "test", "email": "test@example.com"}';
$command = HttpClient::buildCurlCommand('https://api.example.com/users', $headers, $payload);

// Output: curl -X POST 'https://api.example.com/users' -H 'Content-Type: application/json'
//         -H 'Authorization: Bearer abc123' -d '{"name": "test", "email": "test@example.com"}'
echo $command;
example

Array Payload Handling

$headers = ['Accept: application/json'];
$payload = ['user' => 'john', 'action' => 'login'];
$command = HttpClient::buildCurlCommand('https://api.example.com/auth', $headers, $payload);

// Payload automatically JSON-encoded for command generation
Return values
string

Shell-safe cURL command equivalent to request parameters

delete()

Execute HTTP DELETE request to remove resource from remote endpoint

public static delete(string $url[, HttpClientConfig|null $config = null ]) : HttpResult

Performs idempotent DELETE request to remove specified resource. No request body is typically sent with DELETE requests per REST conventions, though some APIs may accept additional parameters via query string or headers.

REST Semantics

  • Resource Removal: Delete specified resource from server
  • Idempotent: Multiple identical requests should have same result
  • No Payload: DELETE requests typically don't include request body
  • Status Codes: Usually returns 200, 204, or 404 depending on API design
Parameters
$url : string

Target resource URL to delete

$config : HttpClientConfig|null = null

Optional configuration (typically for auth/headers)

Tags
since
1.0.0
example

Simple Resource Deletion

$result = HttpClient::delete('https://api.example.com/users/123');
if ($result->curlInfo()['http_code'] === 204) {
    echo "User deleted successfully";
}
example

Authenticated Deletion

$config = new HttpClientConfig('delete_resource');
$config->bearerToken('abc123...');
$result = HttpClient::delete('https://api.example.com/documents/456', $config);
example

Bulk Deletion with Query Parameters

$config = new HttpClientConfig();
$config->setBasicAuth('admin', 'password');
$result = HttpClient::delete('https://api.example.com/posts?status=draft', $config);
Return values
HttpResult

Response confirmation with status code and any returned data

downloadToFile()

Download file from URL directly to local filesystem using cURL

public static downloadToFile(string $url, string $destPath) : bool

Legacy utility for simple file downloads without the full HttpClient/HttpResult overhead. Writes downloaded content directly to specified file path using cURL file stream handling for memory-efficient large file downloads.

Download Features

  • Memory Efficient: Streams directly to file without loading into memory
  • Redirect Following: Automatically follows HTTP redirects (FOLLOWLOCATION)
  • Timeout Protection: 30-second timeout to prevent hung downloads
  • Overwrite Behavior: Target file is overwritten if it exists
  • Simple Error Handling: Returns boolean success/failure status

Use Cases

  • Quick file downloads in utility scripts
  • Backup and synchronization tools
  • Asset downloads for applications
  • Simple file retrieval without response analysis needs
Parameters
$url : string

Source URL to download from

$destPath : string

Local filesystem path for downloaded file (will be overwritten)

Tags
since
1.0.0
example

Download Application Asset

$success = HttpClient::downloadToFile(
    'https://github.com/user/repo/archive/main.zip',
    '/tmp/repo-archive.zip'
);

if ($success) {
    echo "Archive downloaded successfully";
} else {
    echo "Download failed";
}
example

Backup Configuration File

$configUrl = 'https://api.example.com/config/production.json';
$localPath = '/var/backups/config-' . date('Y-m-d') . '.json';

if (HttpClient::downloadToFile($configUrl, $localPath)) {
    echo "Configuration backup created: $localPath";
}
Return values
bool

True if download completed successfully, false on any error

fakeResponder()

Configure mock response handler for testing and development

public static fakeResponder(callable|null $callback) : void

Installs or removes a callable that intercepts all HTTP requests made by HttpClient. When active, the mock handler receives request details and must return a properly configured HttpResult object. Essential for unit testing APIs without network dependencies.

Mock Handler Signature

function(string $method, string $url, mixed $payload, HttpClientConfig $config): HttpResult

Handler Responsibilities

  • Create HttpResult with provided config
  • Set appropriate response data, headers, and status
  • Call stopTimer() to complete performance tracking
  • Return properly configured HttpResult object

EventManager Integration

Fires 'HttpClient.request.CallingFakeResponder' event when mock handler is invoked.

Parameters
$callback : callable|null

Mock handler function or null to disable mocking

Tags
since
1.0.0
example

Basic Mock Setup

HttpClient::fakeResponder(function($method, $url, $payload, $config) {
    $result = new HttpResult($config);
    $result->method($method);
    $result->url($url);
    $result->response('{"success": true, "mock": true}');
    $result->stopTimer();
    return $result;
});

// All requests now return mock data
$response = HttpClient::get('https://api.example.com');
example

Conditional Mocking

HttpClient::fakeResponder(function($method, $url, $payload, $config) {
    $result = new HttpResult($config);
    $result->method($method)->url($url);

    if (str_contains($url, '/users')) {
        $result->response('{"users": [{"id": 1, "name": "Test User"}]}');
    } else {
        $result->response('{"error": "Not found"}');
        $result->curlInfo(['http_code' => 404]);
    }

    $result->stopTimer();
    return $result;
});
example

Disable Mocking

HttpClient::fakeResponder(null); // Restore normal HTTP behavior

get()

Execute HTTP GET request to retrieve data from remote endpoint

public static get(string $url[, HttpClientConfig|null $config = null ]) : HttpResult

Performs idempotent GET request to specified URL with optional configuration. Automatically creates HttpResult with Timer integration for performance monitoring. No request body is sent with GET requests per HTTP standard.

Parameters
$url : string

Target URL to request (must include protocol: http:// or https://)

$config : HttpClientConfig|null = null

Optional request configuration (headers, auth, timeouts)

Tags
since
1.0.0
example

Simple Data Retrieval

$result = HttpClient::get('https://api.github.com/users/octocat');
$userData = json_decode($result->response(), true);
example

With Authentication

$config = new HttpClientConfig('github_api');
$config->bearerToken('ghp_abc123...');
$result = HttpClient::get('https://api.github.com/user', $config);
example

With Custom Headers

$config = new HttpClientConfig();
$config->addHeader('Accept', 'application/vnd.github.v3+json');
$config->userAgent('MyApp/1.0');
$result = HttpClient::get('https://api.github.com/repos/owner/repo', $config);
Return values
HttpResult

Complete response object with body, headers, timing, and metadata

lastHttpResult()

Retrieve the most recent HttpResult object for debugging and inspection

public static lastHttpResult() : HttpResult

Returns the HttpResult from the last HTTP request made by any HttpClient method. Useful for post-request analysis, debugging, and accessing detailed request metadata without storing HttpResult objects explicitly.

Use Cases

  • Debugging: Inspect failed requests without complex error handling
  • Logging: Access detailed request/response data for audit trails
  • Testing: Verify request details in unit tests and integration tests
  • Performance Analysis: Review timing and cURL metadata after requests
Tags
since
1.0.0
example

Debug Request Details

HttpClient::get('https://api.example.com/users');
$last = HttpClient::lastHttpResult();

echo "Request took: " . $last->timerDetails['elapsed'] . " seconds\n";
echo "HTTP Status: " . $last->curlInfo()['http_code'] . "\n";
echo "Response size: " . strlen($last->response()) . " bytes\n";
example

Error Analysis

$result = HttpClient::post('https://api.example.com/data', $payload);
if ($result->curlError()) {
    $debug = HttpClient::lastHttpResult();
    error_log("cURL Error: " . $debug->curlError());
    error_log("Request URL: " . $debug->url());
    error_log("Request Method: " . $debug->method());
}
Return values
HttpResult

Last executed request result or null if no requests made

post()

Execute HTTP POST request to send data to remote endpoint

public static post(string $url[, mixed|null $payload = null ][, HttpClientConfig|null $config = null ]) : HttpResult

Performs POST request with optional payload to create resources or submit data. Supports multiple payload formats including strings, arrays, and file uploads. Automatically configures cURL options based on payload type.

Payload Handling

  • String payloads: Sent as-is with Content-Type from headers
  • Array payloads: URL-encoded for form submissions or multipart for file uploads
  • Null payload: Empty POST request (valid for some APIs)
  • File uploads: Use CURLFile objects in array payload
Parameters
$url : string

Target URL to send data to (must include protocol)

$payload : mixed|null = null

Request body data (string, array, or null)

$config : HttpClientConfig|null = null

Optional request configuration

Tags
since
1.0.0
example

Form Data Submission

$formData = ['name' => 'John Doe', 'email' => 'john@example.com'];
$result = HttpClient::post('https://api.example.com/users', $formData);
example

Raw Data Post

$xmlData = '<user><name>John</name><email>john@example.com</email></user>';
$config = new HttpClientConfig();
$config->addHeader('Content-Type', 'application/xml');
$result = HttpClient::post('https://api.example.com/users', $xmlData, $config);
example

File Upload

$uploadData = [
    'document' => new CURLFile('/path/to/file.pdf', 'application/pdf'),
    'description' => 'Important document'
];
$result = HttpClient::post('https://api.example.com/upload', $uploadData);
Return values
HttpResult

Complete response object with server response and metadata

postJson()

Execute HTTP POST request with automatic JSON encoding and headers

public static postJson(string $url, array<string|int, mixed> $payload[, HttpClientConfig|null $config = null ]) : HttpResult

Convenience method that automatically JSON-encodes array payload and sets appropriate Content-Type header for JSON API communication. Equivalent to calling post() with json_encode() and manual header configuration.

Automatic Configuration

  • Payload automatically JSON-encoded using json_encode()
  • Content-Type header automatically set to 'application/json'
  • HttpClientConfig created automatically if not provided
  • All other POST functionality available (auth, timeouts, etc.)
Parameters
$url : string

Target API endpoint for JSON data submission

$payload : array<string|int, mixed>

Associative array to be JSON-encoded as request body

$config : HttpClientConfig|null = null

Optional configuration (auto-created if null)

Tags
since
1.0.0
example

REST API Resource Creation

$userData = [
    'name' => 'Jane Smith',
    'email' => 'jane@example.com',
    'role' => 'admin'
];
$result = HttpClient::postJson('https://api.example.com/v1/users', $userData);
$newUser = json_decode($result->response(), true);
example

With Authentication

$config = new HttpClientConfig('create_user');
$config->bearerToken('Bearer abc123...');

$result = HttpClient::postJson(
    'https://api.example.com/v1/users',
    ['name' => 'John', 'email' => 'john@example.com'],
    $config
);
example

Complex Nested Data

$orderData = [
    'customer' => ['id' => 123, 'name' => 'John Doe'],
    'items' => [
        ['sku' => 'ABC123', 'quantity' => 2, 'price' => 29.99],
        ['sku' => 'XYZ789', 'quantity' => 1, 'price' => 49.99]
    ],
    'shipping' => ['method' => 'overnight', 'address' => '...']
];
$result = HttpClient::postJson('https://api.example.com/orders', $orderData);
Return values
HttpResult

Complete response object with API response and metadata

put()

Execute HTTP PUT request to update or create resource at specific endpoint

public static put(string $url[, mixed|null $payload = null ][, HttpClientConfig|null $config = null ]) : HttpResult

Performs idempotent PUT request to update entire resource or create new resource at specified URL. Supports same payload formats as POST method but with different semantic meaning per REST conventions.

REST Semantics

  • Update Existing: Replace entire resource with provided data
  • Create New: Create resource at specific URL if it doesn't exist
  • Idempotent: Multiple identical requests should have same result
  • Complete Replacement: Partial updates typically use PATCH method
Parameters
$url : string

Target resource URL for update/creation

$payload : mixed|null = null

Complete resource data (string, array, or null)

$config : HttpClientConfig|null = null

Optional request configuration

Tags
since
1.0.0
example

Update User Resource

$userData = ['name' => 'Jane Doe', 'email' => 'jane@example.com', 'active' => true];
$result = HttpClient::put('https://api.example.com/users/123', $userData);
example

JSON Resource Update

$config = new HttpClientConfig('update_user');
$config->addHeader('Content-Type', 'application/json');
$config->bearerToken('abc123');

$userData = json_encode(['name' => 'Updated Name', 'status' => 'active']);
$result = HttpClient::put('https://api.example.com/users/456', $userData, $config);
example

Create Resource at Specific URL

// Create new document with specific ID
$docData = ['title' => 'New Document', 'content' => 'Document content...'];
$result = HttpClient::put('https://api.example.com/documents/new-doc-id', $docData);
Return values
HttpResult

Complete response with server confirmation and metadata

request()

Core HTTP request implementation using cURL

private static request(string $method, string $url[, mixed|null $payload = null ][, HttpClientConfig|null $config = null ]) : HttpResult

Internal method that executes HTTP requests with cURL, handles authentication, captures responses, and manages performance tracking via HttpResult objects.

Parameters
$method : string

HTTP method (GET, POST, PUT, DELETE, etc.)

$url : string

Target URL

$payload : mixed|null = null

Request body data or null

$config : HttpClientConfig|null = null

Request configuration or null for defaults

Tags
since
1.0.0
Return values
HttpResult

Complete response object with metadata


        
On this page

Search results