Primordyx Framework Documentation

HttpResult
in package

Comprehensive HTTP Request/Response Result Container with Performance Monitoring

Encapsulates complete HTTP request lifecycle data including request parameters, response content, cURL diagnostics, performance metrics, and debugging information. Provides structured access to all HTTP transaction details with built-in Timer integration for performance monitoring and analysis.

Key Features

  • Complete Transaction Data: Request and response details in single object
  • Performance Monitoring: Automatic Timer integration with detailed metrics
  • cURL Diagnostics: Full cURL error and info metadata capture
  • Response Analysis: Convenience methods for status codes, content types, success detection
  • Debug Support: Verbose logging, header inspection, and request replay data
  • Serialization: Export capabilities for logging, debugging, and audit trails
  • Flexible Access: Both getter/setter and read-only access patterns supported

Data Organization

  • Request Data: Method, URL, payload, and configuration used
  • Response Data: Body, headers, status code, and content type
  • Performance Data: Timing metrics via Timer class integration
  • Diagnostic Data: cURL errors, connection info, and verbose logs
  • Metadata: Configuration details and request/response serialization

Timer Integration

HttpResult is where actual Timer class integration occurs:

  • Constructor automatically starts named timer using HttpClientConfig name
  • stopTimer() method finalizes timing and captures detailed metrics
  • Timer name format: "http_client_{config_name}"
  • Performance data accessible via timerDetails() method

Usage Patterns

// HttpResult created automatically by HttpClient
$result = HttpClient::get('https://api.example.com/users');

// Access response data
$statusCode = $result->httpCode();
$responseBody = $result->response();
$headers = $result->responseHeaders();

// Analyze performance
$timing = $result->timerDetails();
echo "Request took: " . $timing['elapsed'] . " seconds";

// Check for errors
if ($result->curlError()) {
    error_log("cURL Error: " . $result->curlError());
}

// Export for logging
$logData = $result->asArray();

Response Analysis

Built-in convenience methods for common response analysis:

  • Success detection via HTTP status code ranges
  • Content-Type extraction and analysis
  • HTTP status code access and interpretation
  • Error condition detection and reporting
Tags
since
1.0.0

Table of Contents

Properties

$config  : HttpClientConfig
HTTP client configuration used for this request
$curl_errno  : mixed
cURL error number/code for request failures
$curl_error  : mixed
cURL error message if request failed
$curl_info  : mixed
Complete cURL information array from curl_getinfo()
$method  : string
HTTP request method used (GET, POST, PUT, DELETE, etc.)
$payload  : mixed
Request payload/body data sent with request
$response  : mixed
Raw HTTP response body content
$responseHeaders  : array<string|int, mixed>
HTTP response headers as associative array
$timerDetails  : array<string|int, mixed>
Detailed performance metrics from Timer class
$timerName  : string
Timer identifier for performance monitoring
$url  : string
Target URL for the HTTP request
$verboseLog  : array<string|int, mixed>
Verbose cURL debugging log entries

Methods

__construct()  : mixed
Initialize HTTP result container and start performance timer
asArray()  : array<string, mixed>
Export complete result data as associative array for logging and debugging
config()  : HttpClientConfig
Get the HttpClientConfig object used for this request
contentType()  : string|null
Get Content-Type header from HTTP response for content handling
curlErrNo()  : mixed
Get or set cURL error number/code for failed requests
curlError()  : mixed
Get or set cURL error message for failed requests
curlInfo()  : mixed
Get or set complete cURL information array from curl_getinfo()
getTimerName()  : string
Get the Timer identifier used for performance monitoring
httpCode()  : int
Get HTTP status code from response for quick status checking
method()  : string|null
Get or set the HTTP request method
payload()  : mixed
Get or set the request payload/body data
response()  : mixed
Get or set the raw HTTP response body content
responseHeaders()  : array<string|int, mixed>
Get or set HTTP response headers as associative array
stopTimer()  : void
Stop performance timer and capture detailed metrics
timerDetails()  : array<string|int, mixed>
Get or set detailed performance metrics from Timer class
toArray()  : array<string, mixed>
Alias for asArray() method for alternative naming convention
url()  : string|null
Get or set the target URL for HTTP request
verboseLog()  : array<string|int, mixed>
Get or set cURL verbose debugging log entries
wasSuccessful()  : bool
Determine if HTTP request was successful based on status code

Properties

$curl_errno

cURL error number/code for request failures

private mixed $curl_errno = null
Tags
since
1.0.0

$curl_error

cURL error message if request failed

private mixed $curl_error = null
Tags
since
1.0.0

$curl_info

Complete cURL information array from curl_getinfo()

private mixed $curl_info = null
Tags
since
1.0.0

$method

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

private string $method = ''
Tags
since
1.0.0

$payload

Request payload/body data sent with request

private mixed $payload = null
Tags
since
1.0.0

$response

Raw HTTP response body content

private mixed $response = null
Tags
since
1.0.0

$responseHeaders

HTTP response headers as associative array

private array<string|int, mixed> $responseHeaders = []
Tags
since
1.0.0

$timerDetails

Detailed performance metrics from Timer class

private array<string|int, mixed> $timerDetails = []
Tags
since
1.0.0

$timerName

Timer identifier for performance monitoring

private string $timerName
Tags
since
1.0.0

$url

Target URL for the HTTP request

private string $url = ''
Tags
since
1.0.0

$verboseLog

Verbose cURL debugging log entries

private array<string|int, mixed> $verboseLog = []
Tags
since
1.0.0

Methods

__construct()

Initialize HTTP result container and start performance timer

public __construct(HttpClientConfig $config) : mixed

Creates new result container for HTTP request/response data and automatically starts named Timer using HttpClientConfig name for performance monitoring. Timer name format: "http_client_{config_name}".

Timer Integration

  • Extracts configuration name for timer identification
  • Starts Timer automatically using generated timer name
  • Timer must be stopped manually via stopTimer() method
  • Performance metrics captured when timer is stopped
Parameters
$config : HttpClientConfig

Configuration object used for the request

Tags
since
1.0.0
example
$config = new HttpClientConfig('api_call');
$result = new HttpResult($config);
// Timer "http_client_api_call" is now running

asArray()

Export complete result data as associative array for logging and debugging

public asArray() : array<string, mixed>

Converts all HTTP transaction data into structured array format suitable for JSON serialization, logging, debugging, and audit trail creation. Automatically handles JSON payload and response detection for proper data formatting.

Data Processing

  • Payload decoded as JSON if request Content-Type indicates JSON
  • Response decoded as JSON if response Content-Type indicates JSON
  • All other data included as-is for complete transaction picture
  • Configuration data included via HttpClientConfig::asArray()
Tags
since
1.0.0
example
$result = HttpClient::postJson('https://api.example.com/users', $userData);
$exportData = $result->asArray();

// Log complete transaction
error_log("API Request: " . json_encode($exportData, JSON_PRETTY_PRINT));

// Access specific data
$statusCode = $exportData['curl_info']['http_code'];
$responseData = $exportData['response']; // Already decoded from JSON
Return values
array<string, mixed>

Complete HTTP transaction data array

config()

Get the HttpClientConfig object used for this request

public config() : HttpClientConfig

Returns the original configuration object used to make the HTTP request. Useful for inspecting request headers, authentication, timeouts, and other configuration details after request completion.

Tags
since
1.0.0
example
$result = HttpClient::get('https://api.example.com/users', $config);

$requestConfig = $result->config();
$headers = $requestConfig->getAllHeaders();
$timeout = $requestConfig->timeout();
Return values
HttpClientConfig

Original configuration object from request

contentType()

Get Content-Type header from HTTP response for content handling

public contentType() : string|null

Convenience method that extracts Content-Type header from cURL info array. Useful for determining how to parse response body content (JSON, XML, HTML, etc.). Returns full Content-Type header value including charset if present.

Tags
since
1.0.0
example
// Parse response based on content type
$contentType = $result->contentType();
$responseBody = $result->response();

if (str_starts_with($contentType, 'application/json')) {
    $data = json_decode($responseBody, true);
} elseif (str_starts_with($contentType, 'application/xml')) {
    $data = simplexml_load_string($responseBody);
} elseif (str_starts_with($contentType, 'text/html')) {
    $data = parseHtmlResponse($responseBody);
} else {
    $data = $responseBody; // Handle as raw content
}

// Extract charset from content type
if (preg_match('/charset=([^;]+)/', $contentType, $matches)) {
    $charset = $matches[1];
    echo "Response charset: $charset";
}
Return values
string|null

Content-Type header value (e.g., 'application/json; charset=utf-8') or null if unavailable

curlErrNo()

Get or set cURL error number/code for failed requests

public curlErrNo([mixed|null $curl_errno = null ]) : mixed

Getter/setter for cURL error number returned by curl_errno(). Provides numeric error code for programmatic error handling and classification. Zero indicates no cURL-level errors occurred.

Parameters
$curl_errno : mixed|null = null

Optional new cURL error number to store

Tags
since
1.0.0
example
// Check for specific error conditions
$errorCode = $result->curlErrNo();

switch ($errorCode) {
    case 0:
        echo "No cURL errors";
        break;
    case 6:  // CURLE_COULDNT_RESOLVE_HOST
        echo "Could not resolve hostname";
        break;
    case 7:  // CURLE_COULDNT_CONNECT
        echo "Could not connect to server";
        break;
    case 28: // CURLE_OPERATION_TIMEDOUT
        echo "Request timed out";
        break;
    default:
        echo "cURL error $errorCode: " . $result->curlError();
}
Return values
mixed

Previous or current cURL error number

curlError()

Get or set cURL error message for failed requests

public curlError([mixed|null $curl_error = null ]) : mixed

Getter/setter for cURL error message returned by curl_error(). Contains human-readable description of connection or request failures. Empty string indicates no cURL-level errors occurred.

Parameters
$curl_error : mixed|null = null

Optional new cURL error message to store

Tags
since
1.0.0
example
// Check for cURL errors
$error = $result->curlError();
if (!empty($error)) {
    error_log("HTTP request failed: $error");
}

// Common cURL error handling
switch (true) {
    case str_contains($error, 'timeout'):
        echo "Request timed out - server may be overloaded";
        break;
    case str_contains($error, 'SSL'):
        echo "SSL/TLS connection failed - check certificates";
        break;
    case str_contains($error, 'resolve'):
        echo "DNS resolution failed - check hostname";
        break;
}
Return values
mixed

Previous or current cURL error message

curlInfo()

Get or set complete cURL information array from curl_getinfo()

public curlInfo([mixed|null $curl_info = null ]) : mixed

Getter/setter for comprehensive request metadata including timing details, connection information, SSL data, HTTP status code, content lengths, IP addresses, ports, and performance metrics.

Available Information

  • HTTP status code, content type, and response size
  • Timing data: total_time, namelookup_time, connect_time, etc.
  • Network details: primary_ip, primary_port, local_ip, local_port
  • SSL information: ssl_verify_result and certificate data
  • Transfer metrics: speed_upload, speed_download, size_upload, size_download
Parameters
$curl_info : mixed|null = null

Optional new cURL info array to store

Tags
since
1.0.0
example
// Get complete cURL information
$info = $result->curlInfo();

// Extract timing information
$totalTime = $info['total_time'];
$connectTime = $info['connect_time'];
$transferTime = $totalTime - $connectTime;

// Network diagnostics
echo "Connected to: " . $info['primary_ip'] . ":" . $info['primary_port'];
echo "Transfer speed: " . number_format($info['speed_download']) . " bytes/sec";

// Performance analysis
if ($info['total_time'] > 5.0) {
    echo "Slow request detected - consider optimizing";
}

Example keys:

array(26) {
   ["url"] => string(36) "https://api.example.com/v1/status"
   ["content_type"] => string(31) "application/json; charset=utf-8"
   ["http_code"] => int(200)
   ["header_size"] => int(289)
   ["request_size"] => int(158)
   ["filetime"] => int(-1)
   ["ssl_verify_result"] => int(0)
   ["redirect_count"] => int(0)
   ["total_time"] => float(0.234)
   ["namelookup_time"] => float(0.015)
   ["connect_time"] => float(0.045)
   ["pretransfer_time"] => float(0.051)
   ["size_upload"] => float(0)
   ["size_download"] => float(347)
   ["speed_download"] => float(1482)
   ["speed_upload"] => float(0)
   ["download_content_length"] => float(-1)
   ["upload_content_length"] => float(0)
   ["starttransfer_time"] => float(0.091)
   ["redirect_time"] => float(0)
   ["redirect_url"] => string(0) ""
   ["primary_ip"] => string(13) "93.184.216.34"
   ["certinfo"] => array(0) }
   ["primary_port"] => int(443)
   ["local_ip"] => string(13) "192.168.1.45"
   ["local_port"] => int(59832)
 }
Return values
mixed

Previous or current cURL information array

getTimerName()

Get the Timer identifier used for performance monitoring

public getTimerName() : string

Returns the name used for Timer class integration. Timer name is generated from HttpClientConfig name with "http_client_" prefix for identification.

Tags
since
1.0.0
example
$result = HttpClient::get('https://api.example.com', $config);
$timerName = $result->getTimerName(); // "http_client_config_name"
Return values
string

Timer name used for performance monitoring

httpCode()

Get HTTP status code from response for quick status checking

public httpCode() : int

Convenience method that extracts HTTP status code from cURL info array. Returns standard HTTP status codes (200, 404, 500, etc.) for response analysis and error handling.

Tags
since
1.0.0
example
// Check response status
$status = $result->httpCode();

switch ($status) {
    case 200:
        echo "Request successful";
        break;
    case 404:
        echo "Resource not found";
        break;
    case 500:
        echo "Server error occurred";
        break;
    default:
        echo "HTTP status: $status";
}

// Status range checking
if ($status >= 400) {
    echo "Client or server error occurred";
}
Return values
int

HTTP status code (200, 404, 500, etc.) or 0 if unavailable

method()

Get or set the HTTP request method

public method([string|null $method = null ]) : string|null

Getter/setter for HTTP method used in request (GET, POST, PUT, DELETE, etc.). When called without parameters, returns current method. When called with method parameter, updates stored method and returns previous value.

Parameters
$method : string|null = null

Optional new HTTP method to set

Tags
since
1.0.0
example
// Get current method
$requestMethod = $result->method(); // "POST"

// Set method (typically done by HttpClient)
$oldMethod = $result->method('PUT');
Return values
string|null

Previous method value or current method if getting

payload()

Get or set the request payload/body data

public payload([mixed|null $payload = null ]) : mixed

Getter/setter for request body content sent with HTTP request. Supports any data type including strings, arrays, and file resources. When called without parameters, returns current payload.

Parameters
$payload : mixed|null = null

Optional new payload data to store

Tags
since
1.0.0
example
// Get request payload
$sentData = $result->payload();

// Examine payload type and content
if (is_array($sentData)) {
    echo "Form data sent: " . print_r($sentData, true);
} else {
    echo "Raw data sent: " . $sentData;
}
Return values
mixed

Previous payload value or current payload if getting

response()

Get or set the raw HTTP response body content

public response([mixed|null $response = null ]) : mixed

Getter/setter for complete response body returned by HTTP server. Content is stored as-is without parsing or modification. For JSON responses, use json_decode() to parse content.

Parameters
$response : mixed|null = null

Optional new response body content to store

Tags
since
1.0.0
example
// Get response content
$responseBody = $result->response();

// Parse JSON responses
if ($result->contentType() === 'application/json') {
    $data = json_decode($responseBody, true);
}

// Handle different content types
$contentType = $result->contentType();
switch ($contentType) {
    case 'application/json':
        $parsed = json_decode($responseBody, true);
        break;
    case 'application/xml':
        $parsed = simplexml_load_string($responseBody);
        break;
    default:
        $parsed = $responseBody;
}
Return values
mixed

Previous or current response body content

responseHeaders()

Get or set HTTP response headers as associative array

public responseHeaders([array<string|int, mixed>|null $responseHeaders = null ]) : array<string|int, mixed>

Getter/setter for response headers captured from HTTP server response. Headers are stored as associative array with header names as keys. Supports duplicate headers via array values for headers with multiple values.

Parameters
$responseHeaders : array<string|int, mixed>|null = null

Optional new response headers to store

Tags
since
1.0.0
example
// Get all response headers
$headers = $result->responseHeaders();

// Check specific headers
$contentType = $headers['content-type'] ?? 'unknown';
$cacheControl = $headers['cache-control'] ?? null;

// Handle duplicate headers (stored as arrays)
if (is_array($headers['set-cookie'])) {
    foreach ($headers['set-cookie'] as $cookie) {
        echo "Cookie: $cookie\n";
    }
}
Return values
array<string|int, mixed>

Previous or current response headers array

stopTimer()

Stop performance timer and capture detailed metrics

public stopTimer() : void

Finalizes Timer tracking and captures comprehensive performance metrics including elapsed time, memory usage, and timing breakdown. Should be called once when HTTP request processing is complete.

Performance Data Captured

  • Total elapsed time for request/response cycle
  • Memory usage during request processing
  • Timing breakdown and performance analytics
  • Timer metadata for performance analysis
Tags
since
1.0.0
example
// Typically called automatically by HttpClient
$result->stopTimer();

// Access captured metrics
$metrics = $result->timerDetails();
echo "Request completed in: " . $metrics['elapsed'] . " seconds";

timerDetails()

Get or set detailed performance metrics from Timer class

public timerDetails([mixed|null $timerDetails = null ]) : array<string|int, mixed>

Getter/setter for comprehensive timing and performance data captured by Timer class during HTTP request processing. Contains elapsed time, memory usage, and detailed timing breakdown for performance analysis.

Parameters
$timerDetails : mixed|null = null

Optional new timer details array to store

Tags
since
1.0.0
example
// Get performance metrics
$metrics = $result->timerDetails();

// Display timing information
echo "Request elapsed time: " . $metrics['elapsed'] . " seconds\n";
echo "Memory used: " . $metrics['memory_used'] . " bytes\n";

// Performance monitoring
if ($metrics['elapsed'] > 2.0) {
    error_log("Slow API request detected: " . $metrics['elapsed'] . "s");
}
Return values
array<string|int, mixed>

Previous or current timer performance data

toArray()

Alias for asArray() method for alternative naming convention

public toArray() : array<string, mixed>

Provides alternative method name for array export functionality. Identical behavior to asArray() method.

Tags
since
1.0.0
Return values
array<string, mixed>

Complete HTTP transaction data array

url()

Get or set the target URL for HTTP request

public url([string|null $url = null ]) : string|null

Getter/setter method for request URL. When called without parameters, returns current URL. When called with URL parameter, updates stored URL and returns previous value.

Parameters
$url : string|null = null

Optional new URL to set

Tags
since
1.0.0
example
// Get current URL
$currentUrl = $result->url();

// Set new URL (typically done by HttpClient)
$oldUrl = $result->url('https://api.example.com/v2/users');
Return values
string|null

Previous URL value or current URL if getting

verboseLog()

Get or set cURL verbose debugging log entries

public verboseLog([array<string|int, mixed>|null $verboseLog = null ]) : array<string|int, mixed>

Getter/setter for detailed cURL communication log captured when verbose logging is enabled in HttpClientConfig. Provides low-level debugging information about HTTP connection, SSL handshake, and protocol details.

Parameters
$verboseLog : array<string|int, mixed>|null = null

Optional new verbose log entries to store

Tags
since
1.0.0
example
// Get verbose log for debugging
$debugLog = $result->verboseLog();
foreach ($debugLog as $line) {
    echo "cURL: $line\n";
}

// Check if verbose logging was enabled
if (count($debugLog) > 1 && $debugLog[0] !== 'No verbose log available') {
    echo "Verbose logging was active for this request";
}
Return values
array<string|int, mixed>

Previous or current verbose log entries

wasSuccessful()

Determine if HTTP request was successful based on status code

public wasSuccessful() : bool

Convenience method that checks if HTTP status code indicates success. Success is defined as 2xx status codes (200-299 range) per HTTP standards. Does not account for application-level errors in response body.

Tags
since
1.0.0
example
// Simple success checking
if ($result->wasSuccessful()) {
    $data = json_decode($result->response(), true);
    processSuccessfulResponse($data);
} else {
    handleHttpError($result->httpCode(), $result->response());
}

// Combined with cURL error checking
if ($result->curlError()) {
    echo "Network error: " . $result->curlError();
} elseif (!$result->wasSuccessful()) {
    echo "HTTP error " . $result->httpCode() . ": " . $result->response();
} else {
    echo "Request completed successfully";
}
Return values
bool

True if HTTP status code indicates success (2xx range), false otherwise


        
On this page

Search results