Network

Reference for the Network module: an HTTP server front controller that captures the request path for routing, an HTTP client for outbound requests, URL parsing, blocking WebSocket clients, webhook registration, routing and queued processing, and optional logging of server and client requests to the database.

This page is a pure reference. For how the framework fits together, see the Guide.

Classes

NetworkWeb

The HTTP server front controller. Splits the request path into segments for the routing system, runs the routing callback, optionally logs the request and response, and renders a 500 page on an uncaught error.

Functions

Server

NetworkWeb::Server(callable $routingCallback): void

Start request handling: split the request URI into path segments for WebRoute, run the routing callback, optionally log the request and response, and record render timing. Renders a 500 page if the callback throws.

NameTypeDescription
$routingCallbackcallableThe routing callback that matches the request and produces the response.

Returns void

NetworkConfig

The module's configuration on the Config module: two optional boolean switches that turn server and client request logging on or off, and readers for them.

Init

NetworkConfig::Init(): void

Register the module's config schema: the optional LOG_SERVER_REQUESTS and LOG_CLIENT_REQUESTS boolean values, both defaulting to false. Called from the module index once the Config module is loaded.

Returns void

LogClientRequestsEnabled

NetworkConfig::LogClientRequestsEnabled(): bool

Whether logging of outgoing client requests to the database is enabled.

Returns bool True when client request logging is on.

LogServerRequestsEnabled

NetworkConfig::LogServerRequestsEnabled(): bool

Whether logging of incoming server requests to the database is enabled.

Returns bool True when server request logging is on.

NetworkWebClient

An HTTP client built on cURL. Offers GET, POST, PUT and DELETE, a request built from a request data object, and per-domain cookie storage that is applied to outbound requests and updated from responses. Optional logging records each request when enabled.

Delete

NetworkWebClient::Delete(string $url, ?array $optionalHeaders = null, ?string $moduleName = null, ?string $requestName = null): NetworkWebResponseData

Perform an HTTP DELETE request.

NameTypeDescription
$urlstringThe URL to request.
$optionalHeaders?arrayOptional headers to include.
$moduleName?stringOptional module name used when logging.
$requestName?stringOptional request name used when logging.

Returns NetworkWebResponseData The response.

Get

NetworkWebClient::Get(string $url, ?array $optionalHeaders = null, ?string $moduleName = null, ?string $requestName = null): NetworkWebResponseData

Perform an HTTP GET request.

NameTypeDescription
$urlstringThe URL to request.
$optionalHeaders?arrayOptional headers to include.
$moduleName?stringOptional module name used when logging.
$requestName?stringOptional request name used when logging.

Returns NetworkWebResponseData The response.

getCookieString

NetworkWebClient::getCookieString(string $url): string

The stored cookies for the URL's domain, as a single Cookie header string, or empty when there are none.

NameTypeDescription
$urlstringThe URL whose domain's cookies are read.

Returns string The cookie string for the domain.

Post

NetworkWebClient::Post(string $url, ?string $body = null, ?array $optionalHeaders = null, ?string $moduleName = null, ?string $requestName = null): NetworkWebResponseData

Perform an HTTP POST request with an optional body.

NameTypeDescription
$urlstringThe URL to request.
$body?stringOptional request body.
$optionalHeaders?arrayOptional headers to include.
$moduleName?stringOptional module name used when logging.
$requestName?stringOptional request name used when logging.

Returns NetworkWebResponseData The response.

Put

NetworkWebClient::Put(string $url, ?string $body = null, ?array $optionalHeaders = null, ?string $moduleName = null, ?string $requestName = null): NetworkWebResponseData

Perform an HTTP PUT request with an optional body.

NameTypeDescription
$urlstringThe URL to request.
$body?stringOptional request body.
$optionalHeaders?arrayOptional headers to include.
$moduleName?stringOptional module name used when logging.
$requestName?stringOptional request name used when logging.

Returns NetworkWebResponseData The response.

RequestWithData

NetworkWebClient::RequestWithData(NetworkWebRequestData $request): NetworkWebResponseData

Perform a request described by a request data object, synchronously.

NameTypeDescription
$requestNetworkWebRequestDataThe request to perform.

Returns NetworkWebResponseData The response.

updateCookiesFromHeaders

NetworkWebClient::updateCookiesFromHeaders(string $url, array $responseHeaders): void

Store any Set-Cookie values from response headers against the URL's domain, for use on later requests.

NameTypeDescription
$urlstringThe URL whose domain the cookies belong to.
$responseHeadersarrayResponse headers keyed by name.

Returns void

NetworkWebConnectionError

An exception thrown when an outbound HTTP request cannot connect to the server.

Functions

__construct

new NetworkWebConnectionError(string $message = "Connection failed", int $code = 0, Throwable|null $previous = null)

Create a connection error with a message, code and optional previous throwable.

NameTypeDescription
$messagestringThe error message.
$codeintThe error code.
$previousThrowable|nullThe previous throwable, or null.

Returns NetworkWebConnectionError

NetworkWebDatabase

Logs outbound client requests and their responses to the database, and formats a header list into a string. Used by the client when client request logging is enabled.

Constants

ConstantValueDescription
NetworkWebDatabase::LOG_STATUS_IN_PROGRESS0The request has been logged but has no response yet.
NetworkWebDatabase::LOG_STATUS_SUCCESS1The request completed and a response was logged.
NetworkWebDatabase::LOG_STATUS_ERROR2The request failed and an error was logged.

AddError

NetworkWebDatabase::AddError(int $logId, float $durationMs, string|null $errorMessage = null): void

Update a logged client request with error status, its duration and an optional error message.

NameTypeDescription
$logIdintThe id of the log entry to update.
$durationMsfloatHow long the request ran before failing, in milliseconds.
$errorMessagestring|nullOptional error message.

Returns void

AddRequest

NetworkWebDatabase::AddRequest(string $method, string $url, string $requestBody, array|null $requestHeaders = null, string|null $moduleName = null, string|null $requestName = null): int

Log a new outbound client request and return its new log id.

NameTypeDescription
$methodstringThe HTTP method.
$urlstringThe URL being requested.
$requestBodystringThe request body content.
$requestHeadersarray|nullA list of NetworkWebHeaderData, or null.
$moduleNamestring|nullOptional module name.
$requestNamestring|nullOptional request name.

Returns int The id of the created log entry.

AddResponse

NetworkWebDatabase::AddResponse(int $logId, int $responseCode, string $responseBody, float $durationMs, array|null $responseHeaders = null): void

Update a logged client request with its successful response code, body, duration and headers.

NameTypeDescription
$logIdintThe id of the log entry to update.
$responseCodeintThe HTTP response code.
$responseBodystringThe response body content.
$durationMsfloatThe request duration in milliseconds.
$responseHeadersarray|nullA list of NetworkWebHeaderData, or null.

Returns void

HeadersToString

NetworkWebDatabase::HeadersToString(array|null $headers): string|null

Join a list of header data objects into one string, one "name: value" per line, or null when the list is empty.

NameTypeDescription
$headersarray|nullA list of NetworkWebHeaderData, or null.

Returns string|null The header string, or null.

NetworkWebHeaderData

Immutable name and value pair for an HTTP header. Fields and constructor only.

Properties

PropertyTypeDescription
$header->namestringThe header name (readonly).
$header->valuestringThe header value (readonly).

__construct

new NetworkWebHeaderData(string $name, string $value)

Create header data from a name and value.

NameTypeDescription
$namestringThe header name.
$valuestringThe header value.

Returns NetworkWebHeaderData

NetworkWebRequestData

Immutable outbound HTTP request. Fields and constructor only.

Properties

PropertyTypeDescription
$request->methodstringThe HTTP method (readonly).
$request->urlstringThe URL to request (readonly).
$request->bodystringThe request body (readonly).
$request->headersarray|nullThe request headers, or null (readonly).

__construct

new NetworkWebRequestData(string $method, string $url, string $body, array|null $headers)

Create a request from a method, URL, body and optional headers.

NameTypeDescription
$methodstringThe HTTP method.
$urlstringThe URL to request.
$bodystringThe request body.
$headersarray|nullThe request headers, or null.

Returns NetworkWebRequestData

NetworkWebResponse

Reads fields out of a response data object.

GetRedirectOptional

NetworkWebResponse::GetRedirectOptional(NetworkWebResponseData $response): ?string

The Location header value from a response, or null when there is none.

NameTypeDescription
$responseNetworkWebResponseDataThe response to read.

Returns ?string The redirect location, or null.

NetworkWebResponseData

Immutable HTTP response with its status code, headers and body, and conversions to and from JSON.

Properties

PropertyTypeDescription
$response->statusCodeintThe HTTP status code (readonly).
$response->headersarrayThe response headers keyed by name (readonly).
$response->responseBodystringThe response body (readonly).

__construct

new NetworkWebResponseData(int $statusCode = 0, array $headers = [], string $responseBody = '')

Create a response from a status code, headers and body.

NameTypeDescription
$statusCodeintThe HTTP status code.
$headersarrayThe response headers keyed by name.
$responseBodystringThe response body.

Returns NetworkWebResponseData

BodyJson

$response->BodyJson(): mixed

The response body decoded from JSON.

Returns mixed The decoded body.

FromJson

NetworkWebResponseData::FromJson(array $json): NetworkWebResponseData

Build a response from a decoded JSON array of statusCode, headers and responseBody.

NameTypeDescription
$jsonarrayThe decoded JSON fields.

Returns NetworkWebResponseData The response.

ToJson

$response->ToJson(): array

The response as an array of statusCode, headers and responseBody.

Returns array The response fields.

NetworkWebServerDatabase

Logs inbound server requests and their responses to the database. Used by the server front controller when server request logging is enabled.

Constants

ConstantValueDescription
NetworkWebServerDatabase::LOG_STATUS_IN_PROGRESS0The request has been logged but has no response yet.
NetworkWebServerDatabase::LOG_STATUS_SUCCESS1The request completed and a response was logged.
NetworkWebServerDatabase::LOG_STATUS_ERROR2The request failed and an error was logged.

AddError

NetworkWebServerDatabase::AddError(int $logId, float $durationMs, string|null $errorMessage = null): void

Update a logged server request with error status, its duration and an optional error message.

NameTypeDescription
$logIdintThe id of the log entry to update.
$durationMsfloatHow long the request ran before failing, in milliseconds.
$errorMessagestring|nullOptional error message.

Returns void

AddRequest

NetworkWebServerDatabase::AddRequest(string $method, string $url, string $requestBody, array|null $requestHeaders = null): int

Log a new inbound server request, splitting the URL into path and query, and return its new log id.

NameTypeDescription
$methodstringThe HTTP method.
$urlstringThe request URL path.
$requestBodystringThe request body content.
$requestHeadersarray|nullA list of NetworkWebHeaderData, or null.

Returns int The id of the created log entry.

AddResponse

NetworkWebServerDatabase::AddResponse(int $logId, int $responseCode, string $responseBody, float $durationMs, array|null $responseHeaders = null): void

Update a logged server request with its response code, body, duration and headers.

NameTypeDescription
$logIdintThe id of the log entry to update.
$responseCodeintThe HTTP response code.
$responseBodystringThe response body content.
$durationMsfloatThe request duration in milliseconds.
$responseHeadersarray|nullA list of NetworkWebHeaderData, or null.

Returns void

NetworkWebUrl

Parses a URL string into its component parts.

Functions

Parse

NetworkWebUrl::Parse(string $url): NetworkWebUrlData

Parse a URL into its protocol, host, port, path, query and anchor.

NameTypeDescription
$urlstringThe URL string to parse.

Returns NetworkWebUrlData The parsed URL.

NetworkWebUrlData

Immutable parsed URL. Fields and constructor only, with conversions to and from JSON.

Properties

PropertyTypeDescription
$url->protocolstringThe URL protocol or scheme (readonly).
$url->hoststringThe host (readonly).
$url->portintThe port (readonly).
$url->pathstringThe path (readonly).
$url->queryarray|nullThe query parameters keyed by name, or null (readonly).
$url->anchorstring|nullThe fragment or anchor, or null (readonly).

__construct

new NetworkWebUrlData(string $protocol = '', string $host = '', int $port = 80, string $path = '', array|null $query = null, string|null $anchor = null)

Create URL data from its parts.

NameTypeDescription
$protocolstringThe URL protocol or scheme.
$hoststringThe host.
$portintThe port.
$pathstringThe path.
$queryarray|nullThe query parameters keyed by name, or null.
$anchorstring|nullThe fragment or anchor, or null.

Returns NetworkWebUrlData

FromJson

NetworkWebUrlData::FromJson(array $json): NetworkWebUrlData

Build URL data from a decoded JSON array of its parts.

NameTypeDescription
$jsonarrayThe decoded JSON fields.

Returns NetworkWebUrlData The parsed URL.

ToJson

$url->ToJson(): array

The URL data as an array of its parts.

Returns array The URL fields.

NetworkWebhook

Routes incoming webhook requests. Under a base path, each registered webhook is matched at /base/<module>/<hook>, the call is recorded for queued processing, and the request returns 202 immediately.

Functions

Route

NetworkWebhook::Route(string $path): void

Set up routing for every registered webhook under a base path, recording each received call and returning 202 for asynchronous processing.

NameTypeDescription
$pathstringThe base path for webhooks.

Returns void

NetworkWebhookCallData

Immutable record of one received webhook call, with conversions to and from JSON.

Properties

PropertyTypeDescription
$call->idintThe call id (readonly).
$call->moduleIdentifierstringThe module that registered the webhook (readonly).
$call->hookIdentifierstringThe hook identifier (readonly).
$call->methodstringThe HTTP method (readonly).
$call->urlstringThe full request URL (readonly).
$call->pathstringThe path part of the URL (readonly).
$call->optionalQuery?stringThe query string, or null (readonly).
$call->bodystringThe request body (readonly).
$call->headersarray|nullThe request headers, or null (readonly).
$call->processedboolWhether the call has been processed (readonly).
$call->timestampintThe Unix timestamp when received (readonly).
$call->datestringThe date when received (readonly).

__construct

new NetworkWebhookCallData(int $id = 0, string $moduleIdentifier = '', string $hookIdentifier = '', string $method = '', string $url = '', string $path = '', ?string $optionalQuery = null, string $body = '', array|null $headers = null, bool $processed = false, int $timestamp = 0, string $date = '')

Create a webhook call record from its fields.

NameTypeDescription
$idintThe call id.
$moduleIdentifierstringThe module that registered the webhook.
$hookIdentifierstringThe hook identifier.
$methodstringThe HTTP method.
$urlstringThe full request URL.
$pathstringThe path part of the URL.
$optionalQuery?stringThe query string, or null.
$bodystringThe request body.
$headersarray|nullThe request headers, or null.
$processedboolWhether the call has been processed.
$timestampintThe Unix timestamp when received.
$datestringThe date when received.

Returns NetworkWebhookCallData

FromJson

NetworkWebhookCallData::FromJson(string $json): NetworkWebhookCallData

Build a webhook call record from a JSON string.

NameTypeDescription
$jsonstringThe JSON string.

Returns NetworkWebhookCallData The call record.

ToJson

$call->ToJson(): string

The webhook call record as a JSON string.

Returns string The JSON representation.

NetworkWebhookConfig

Registers webhooks and lists the registered ones. The registered webhooks are held in a public static array keyed by module and hook name.

Properties

PropertyTypeDescription
NetworkWebhookConfig::$webhooksarrayThe registered webhooks, keyed by "module_hook".

AddWebhook

NetworkWebhookConfig::AddWebhook(string $moduleName, string $hookName, string $description, callable $callback): void

Register a webhook and its callback under a module and hook name.

NameTypeDescription
$moduleNamestringThe module name for the webhook.
$hookNamestringThe hook name identifier.
$descriptionstringA brief description of the webhook.
$callbackcallableThe callback that handles the webhook request.

Returns void

GetWebhooks

NetworkWebhookConfig::GetWebhooks(): array

All registered webhooks, as a list.

Returns array A list of NetworkWebhookConfigWebhook.

NetworkWebhookConfigWebhook

Immutable registered webhook: its module and hook name, its description and its callback. Fields and constructor only.

Properties

PropertyTypeDescription
$webhook->moduleNamestringThe module name (readonly).
$webhook->hookNamestringThe hook name (readonly).
$webhook->descriptionstringThe description (readonly).
$webhook->callbackmixedThe callback that handles the webhook (readonly).

__construct

new NetworkWebhookConfigWebhook(string $moduleName, string $hookName, string $description, mixed $callback)

Create a registered webhook from its module and hook name, description and callback.

NameTypeDescription
$moduleNamestringThe module name.
$hookNamestringThe hook name.
$descriptionstringThe description.
$callbackmixedThe callback that handles the webhook.

Returns NetworkWebhookConfigWebhook

NetworkWebhookDatabase

Stores, reads and processes webhook call records. Records a received call, reads calls back, marks them processed, and runs the configured callback for a call.

AddCall

NetworkWebhookDatabase::AddCall(string $moduleIdentifier, string $hookIdentifier, string $method, string $url, string $requestBody, array|null $requestHeaders = null): int

Record a received webhook call, splitting the URL into path and query, and return its new id.

NameTypeDescription
$moduleIdentifierstringThe module that registered the webhook.
$hookIdentifierstringThe hook identifier.
$methodstringThe HTTP method.
$urlstringThe webhook URL path with optional query.
$requestBodystringThe request body content.
$requestHeadersarray|nullA list of NetworkWebHeaderData, or null.

Returns int The id of the created call record.

fromRow

NetworkWebhookDatabase::fromRow(object $row): NetworkWebhookCallData

Map a database row to a webhook call data object.

NameTypeDescription
$rowobjectThe database row.

Returns NetworkWebhookCallData The call record.

GetById

NetworkWebhookDatabase::GetById(int $webhookCallId): NetworkWebhookCallData

Read a webhook call record by id.

NameTypeDescription
$webhookCallIdintThe webhook call id.

Returns NetworkWebhookCallData The call record.

GetIndexOfWebhookCall

NetworkWebhookDatabase::GetIndexOfWebhookCall(int $webhookCallId): int

The zero-based position of a call in the list ordered newest first, for working out which page it is on.

NameTypeDescription
$webhookCallIdintThe webhook call id.

Returns int The zero-based position.

GetMaxId

NetworkWebhookDatabase::GetMaxId(): int

The highest webhook call id, or 0 when there are no calls.

Returns int The maximum id.

MarkProcessed

NetworkWebhookDatabase::MarkProcessed(int $webhookCallId): void

Mark a webhook call as processed.

NameTypeDescription
$webhookCallIdintThe webhook call id.

Returns void

ProcessQueue

NetworkWebhookDatabase::ProcessQueue(int $webhookCallId): void

Run the configured callback for a webhook call and mark it processed, recording success or error counters.

NameTypeDescription
$webhookCallIdintThe webhook call id to process.

Returns void

NetworkWebhookQueueDatabase

The queue callbacks for webhook processing: leasing the next unprocessed calls, and running one call. Registered as the webhook queue's lease and process callbacks.

Functions

LockNext

NetworkWebhookQueueDatabase::LockNext(int $limit): array

Lock and return up to a number of unprocessed webhook call ids, oldest first, skipping rows already locked. Called within a transaction.

NameTypeDescription
$limitintThe maximum number of rows to lock and return.

Returns array A list of integer ids, empty when none are available.

Process

NetworkWebhookQueueDatabase::Process(int $webhookCallId): void

Run the configured callback for one webhook call and mark it processed, re-throwing on error so the queue can track it.

NameTypeDescription
$webhookCallIdintThe webhook call id to process.

Returns void

NetworkWebsocket

Blocking WebSocket clients built on TCP sockets: a simple client, and one that reconnects. Each takes callbacks for connection, messages, errors and close, and returns a cleanup function that closes the connection.

Client

NetworkWebsocket::Client(string $url, ?array $headers, callable $onConnect, ?callable $onError = null, ?callable $onClose = null, ?callable $onMessage = null): callable

Open a blocking WebSocket client without automatic reconnection, calling the callbacks as events occur.

NameTypeDescription
$urlstringThe WebSocket URL.
$headers?arrayOptional headers sent during the upgrade.
$onConnectcallableCalled when connected; receives send and close functions.
$onError?callableOptional callback called on error.
$onClose?callableOptional callback called when the connection closes.
$onMessage?callableOptional callback called when a message is received.

Returns callable A cleanup function that closes the connection.

ReconnectingClient

NetworkWebsocket::ReconnectingClient(string $url, ?array $headers, callable $onConnect, ?callable $onReconnect = null, ?callable $onError = null, ?callable $onClose = null, ?callable $onMessage = null): callable

Open a WebSocket client with a reconnection callback, calling onReconnect on re-establishment.

NameTypeDescription
$urlstringThe WebSocket URL.
$headers?arrayOptional headers sent during the upgrade.
$onConnectcallableCalled when first connected.
$onReconnect?callableOptional callback called when a reconnection is established.
$onError?callableOptional callback called on error.
$onClose?callableOptional callback called when the connection closes.
$onMessage?callableOptional callback called when a message is received.

Returns callable A cleanup function that closes the connection and stops reconnecting.

NetworkWebsocketDatabase

Logs WebSocket connections and events to the database. Used by the WebSocket clients to record connection, message, error and close events.

Constants

ConstantValueDescription
NetworkWebsocketDatabase::EVENT_TYPE_CONNECTION'connection'A connection event.
NetworkWebsocketDatabase::EVENT_TYPE_MESSAGE'message'A message event.
NetworkWebsocketDatabase::EVENT_TYPE_ERROR'error'An error event.
NetworkWebsocketDatabase::EVENT_TYPE_CLOSE'close'A close event.

AddConnection

NetworkWebsocketDatabase::AddConnection(string $url, array|null $headers = null): int

Log a new WebSocket connection and return its new log id.

NameTypeDescription
$urlstringThe WebSocket URL.
$headersarray|nullOptional headers sent during connection.

Returns int The id of the created connection log entry.

AddEvent

NetworkWebsocketDatabase::AddEvent(int $connectionId, string $eventType, string|null $eventData = null): int

Log a WebSocket event against a connection and return its new log id.

NameTypeDescription
$connectionIdintThe connection id.
$eventTypestringOne of the EVENT_TYPE constants.
$eventDatastring|nullOptional event data.

Returns int The id of the created event log entry.