bradleyhodges/api-manager

APIManager
in package

Class APIManager

This class manages various aspects of API operations, including error handling, security headers, Cross-Origin Resource Sharing (CORS), response management, rate limiting, CSRF protection, and utility loading. It integrates with key security and logging packages to provide a robust and secure framework for API-driven applications.

Table of Contents

Methods

__construct()  : mixed
APIManager constructor.
addHeader()  : void
Adds a header to the response.
checkRateLimit()  : RateLimit
Checks the current rate limit status without consuming a token.
decodeJSON()  : array<string|int, mixed>
Decodes a JSON string into a PHP array with error handling.
encodeJson()  : string
Encodes a PHP array into a JSON string with error handling.
errorLog()  : $this
Adds a log message, similar to PHP's error_log function.
expectParameters()  : array<string|int, mixed>|b
Validates and sanitizes the expected parameters from a given source (e.g., JSON, XML, POST, GET, REQUEST).
getClientIp()  : string|null
Securely retrieve the client's IP address.
getCsrfTokenManager()  : CsrfTokenManager|null
Retrieves the initialized CSRF token manager.
getJSONPayload()  : array<string|int, mixed>
Retrieves JSON payload from the request body and decodes it into a PHP array.
getRateLimitRemainingAttempts()  : int
Gets the number of remaining attempts before the rate limit is reached.
getRateLimitStatus()  : array<string|int, mixed>
Gets the current rate limit status.
getSanitizedGET()  : string|null
Retrieves sanitized input from the $_GET superglobal.
getSanitizedPOST()  : string|null
Retrieves sanitized input from the $_POST superglobal.
handleError()  : void
Custom error handler for the APIManager.
handleException()  : void
Custom exception handler for the APIManager.
handleShutdown()  : void
Handles fatal errors by logging them and sending a 500 response.
isJson()  : bool
Checks if a given string is a valid JSON.
removeHeader()  : void
Removes a header from the response.
requireFile()  : void
Securely requires a file.
requireOnceFile()  : void
Securely requires_once a file.
resetRateLimit()  : self
Resets the rate limiter for a specific ID.
responseManager()  : ApiResponseManager
Retrieves the response manager instance.
sanitizeInput()  : string|null
Sanitizes, trims, and optionally truncates a string.
setRateLimitStorage()  : self
Sets the storage backend for the rate limiter.
setResponseContentType()  : void
Sets the response Content-Type header.
useCORS()  : self
Initializes and configures CORS handling.
useCsrfManager()  : self
Initializes the CSRF token manager.
useHTTP()  : HTTP
Creates and returns an HTTP instance with the provided configuration.
useRateLimiter()  : self
Initializes and configures the rate limiter.
useSecurityHeaders()  : $this
Configures and applies security headers to the current response.

Methods

__construct()

APIManager constructor.

public __construct() : mixed

Initializes the APIManager class, loads environment variables, sets up logging, and configures various options.

addHeader()

Adds a header to the response.

public addHeader(string $headerName, string $headerValue) : void
Parameters
$headerName : string

The name of the header to add.

$headerValue : string

The value of the header to add.

checkRateLimit()

Checks the current rate limit status without consuming a token.

public checkRateLimit(string $id) : RateLimit
Parameters
$id : string

The rate limiter ID.

Return values
RateLimit

The current rate limit status.

decodeJSON()

Decodes a JSON string into a PHP array with error handling.

public decodeJSON(string $json) : array<string|int, mixed>

This method decodes JSON and throws an exception if the JSON is invalid.

Parameters
$json : string

The JSON string to decode.

Tags
throws
RuntimeException

If the JSON string is invalid.

Return values
array<string|int, mixed>

The decoded JSON as a PHP array.

encodeJson()

Encodes a PHP array into a JSON string with error handling.

public encodeJson(array<string|int, mixed> $data) : string

This method encodes data as JSON and throws an exception if encoding fails.

Parameters
$data : array<string|int, mixed>

The data to encode as JSON.

Tags
throws
RuntimeException

If the data cannot be encoded as JSON.

Return values
string

The encoded JSON string.

errorLog()

Adds a log message, similar to PHP's error_log function.

public errorLog(string|array<string|int, mixed>|Throwable $logData[, string $level = 'error' ]) : $this
Parameters
$logData : string|array<string|int, mixed>|Throwable

Log data, either as a string message, an array with level and message, or an exception.

$level : string = 'error'

(optional) The log level (e.g., 'error', 'warning', 'critical'). Default is 'error'.

Return values
$this

expectParameters()

Validates and sanitizes the expected parameters from a given source (e.g., JSON, XML, POST, GET, REQUEST).

public expectParameters(string $uses, array<string|int, array<string|int, mixed>> $parameters[, bool $handleResponse = true ]) : array<string|int, mixed>|b
Parameters
$uses : string

The source of the parameters (e.g., JSON, XML, POST, GET, REQUEST).

$parameters : array<string|int, array<string|int, mixed>>

The array of parameter rules to validate and sanitize.

Each parameter rule array should contain the following keys:

  • 'mandatory' (bool): Whether the parameter is required (default: true).
  • 'requires' (string): The key in the input data to validate.
  • 'name' (string): The name of the parameter (default: value of 'requires').
  • 'format' (int|string|null): The validation format (FILTER_VALIDATE constant or regex string, optional).
  • 'strictFormat' (bool): Whether to strictly enforce the format (default: true).
  • 'sanitize' (bool): Whether to sanitize the input (default: true).
  • 'descriptor' (string): A human-readable name for the parameter (default: value of 'name').
  • 'maxLength' (int|null): The maximum length allowed for the input (optional).
  • 'options' (array): Additional options for filters (e.g., ['regexp' => 'regex pattern'], default: empty array).
$handleResponse : bool = true

Determines whether to call handleContinuance() after adding errors.

Tags
example

$validatedParams = $this->expectParameters('POST', [ [ 'mandatory' => true, 'requires' => 'sessionId', 'name' => 'sessionId', 'format' => FILTER_VALIDATE_REGEXP, 'strictFormat' => true, 'sanitize' => true, 'descriptor' => 'Session ID', 'maxLength' => 32, 'options' => ['regexp' => '/^[a-f0-9]{32}$/i'] ] ], true);

Return values
array<string|int, mixed>|b

The sanitized and validated parameters.

getClientIp()

Securely retrieve the client's IP address.

public getClientIp() : string|null

This method checks multiple headers that may contain the client IP, but validates them to ensure they are not spoofed. The method is hardened to avoid common pitfalls such as trusting unvalidated headers and supports environments behind proxies.

Return values
string|null

The validated client IP address or null if it cannot be determined.

getCsrfTokenManager()

Retrieves the initialized CSRF token manager.

public getCsrfTokenManager() : CsrfTokenManager|null

This method returns the instance of the CSRF token manager, if it has been initialized.

Return values
CsrfTokenManager|null

The CSRF token manager instance or null if not initialized.

getJSONPayload()

Retrieves JSON payload from the request body and decodes it into a PHP array.

public getJSONPayload([bool $requirePayload = false ]) : array<string|int, mixed>
Parameters
$requirePayload : bool = false

Whether to require a non-empty JSON payload.

Tags
throws
RuntimeException

If the JSON payload is invalid or empty.

Return values
array<string|int, mixed>

The decoded JSON payload.

getRateLimitRemainingAttempts()

Gets the number of remaining attempts before the rate limit is reached.

public getRateLimitRemainingAttempts(string $id) : int
Parameters
$id : string

The rate limiter ID.

Return values
int

The number of remaining attempts.

getRateLimitStatus()

Gets the current rate limit status.

public getRateLimitStatus(string $id) : array<string|int, mixed>
Parameters
$id : string

The rate limiter ID.

Return values
array<string|int, mixed>

The rate limit status (remaining attempts, reset time, etc.).

getSanitizedGET()

Retrieves sanitized input from the $_GET superglobal.

public getSanitizedGET(string $key) : string|null
Parameters
$key : string

The key to retrieve from the $_GET array.

Return values
string|null

The sanitized input or null if the key does not exist.

getSanitizedPOST()

Retrieves sanitized input from the $_POST superglobal.

public getSanitizedPOST(string $key) : string|null
Parameters
$key : string

The key to retrieve from the $_POST array.

Return values
string|null

The sanitized input or null if the key does not exist.

handleError()

Custom error handler for the APIManager.

public handleError(int $errno, string $errstr, string $errfile, int $errline) : void

This method is triggered automatically when a PHP error occurs. It logs the error based on its severity and may throw an ErrorException for critical errors (e.g., E_ERROR).

Parameters
$errno : int

The level of the error raised.

$errstr : string

The error message.

$errfile : string

The filename that the error was raised in.

$errline : int

The line number the error was raised at.

Tags
throws
ErrorException

If the error is of type E_ERROR or similar critical errors.

handleException()

Custom exception handler for the APIManager.

public handleException(Throwable $throwable) : void

This method is triggered automatically when an unhandled exception occurs. It logs the exception details, including the request method and URI, and sends a 500 HTTP response with a JSON error message.

Parameters
$throwable : Throwable

The exception that was thrown.

handleShutdown()

Handles fatal errors by logging them and sending a 500 response.

public handleShutdown() : void

This method is registered as a shutdown function to handle fatal errors.

isJson()

Checks if a given string is a valid JSON.

public isJson(string $string) : bool
Parameters
$string : string

The string to check.

Return values
bool

True if the string is a valid JSON, false otherwise.

removeHeader()

Removes a header from the response.

public removeHeader(string $headerName) : void
Parameters
$headerName : string

The name of the header to remove.

requireFile()

Securely requires a file.

public requireFile(string $filePath[, bool $force = false ]) : void
Parameters
$filePath : string

The path to the file to be required. Use "@/path/to/file" to reference the document root, or provide an absolute path.

$force : bool = false

Allow the require operation to proceed even if outside of the document root (only works if ENFORCE_SAFE_REQUIRES is not enabled).

Tags
throws
RuntimeException

If the file is outside of the document root and ENFORCE_SAFE_REQUIRES is enabled, or if the file does not exist.

requireOnceFile()

Securely requires_once a file.

public requireOnceFile(string $filePath[, bool $force = false ]) : void
Parameters
$filePath : string

The path to the file to be required_once. Use "@/path/to/file" to reference the document root, or provide an absolute path.

$force : bool = false

Allow the require_once operation to proceed even if outside of the document root (only works if ENFORCE_SAFE_REQUIRES is not enabled).

Tags
throws
RuntimeException

If the file is outside of the document root and ENFORCE_SAFE_REQUIRES is enabled, or if the file does not exist.

resetRateLimit()

Resets the rate limiter for a specific ID.

public resetRateLimit(string $id) : self
Parameters
$id : string

The rate limiter ID.

Return values
self

sanitizeInput()

Sanitizes, trims, and optionally truncates a string.

public sanitizeInput(mixed $input[, int|null $maxLength = null ]) : string|null

Returns null if the input is empty after sanitization.

This method ensures that input data is safe for processing by trimming whitespace, removing invalid UTF-8 characters, and truncating the string if necessary.

Parameters
$input : mixed

The data to sanitize and process. Can be any type that can be cast to a string.

$maxLength : int|null = null

Optional maximum length for truncation. Must be a positive integer if provided.

Tags
throws
InvalidArgumentException

if $maxLength is not null and not a positive integer.

throws
RuntimeException

if the mbstring extension is required but not available.

throws
InvalidArgumentException

if the input data is not valid UTF-8 or exceeds the allowed maximum length.

example

// Sanitize input with a maximum length of 100 characters $sanitized = $apiManager->sanitizeInput($userInput, 100);

Return values
string|null

Returns the sanitized and processed string, or null if the string is empty after sanitization.

setRateLimitStorage()

Sets the storage backend for the rate limiter.

public setRateLimitStorage(object $storage) : self
Parameters
$storage : object

The storage backend (e.g., RedisStorage, InMemoryStorage).

Return values
self

setResponseContentType()

Sets the response Content-Type header.

public static setResponseContentType(string $contentType) : void
Parameters
$contentType : string

The content type to set (e.g., 'text/html', 'application/json').

useCORS()

Initializes and configures CORS handling.

public useCORS([array<string|int, mixed> $options = [] ]) : self
Parameters
$options : array<string|int, mixed> = []

CORS options.

Return values
self

useCsrfManager()

Initializes the CSRF token manager.

public useCsrfManager() : self
Return values
self

useHTTP()

Creates and returns an HTTP instance with the provided configuration.

public useHTTP([array<string|int, mixed> $config = [] ]) : HTTP
Parameters
$config : array<string|int, mixed> = []

Configuration options such as 'base_uri', 'headers', etc.

Tags
throws
InvalidArgumentException

If the configuration is invalid

example

$apiManager = new APIManager(); $http = $apiManager->useHTTP(['base_uri' => 'https://foo.com/api/', 'headers' => [...]]); $response = $http->request('GET', 'test'); $cookies = $http->cookieJar();

Return values
HTTP

An instance of the HTTP class

useRateLimiter()

Initializes and configures the rate limiter.

public useRateLimiter([array<string|int, mixed> $config = [] ]) : self
Parameters
$config : array<string|int, mixed> = []

Rate limiter configuration options.

Return values
self

useSecurityHeaders()

Configures and applies security headers to the current response.

public useSecurityHeaders([array<string|int, mixed> $customHeaders = [] ]) : $this

This method merges custom security headers with default security headers and applies them to the response. It ensures that critical security policies, such as Content Security Policy (CSP) and XSS protection, are in place.

Parameters
$customHeaders : array<string|int, mixed> = []

Custom security headers to apply. The array should be formatted as ['Header-Name' => 'Header-Value'].

Tags
example

$apiManager->useSecurityHeaders([ 'Content-Security-Policy' => "default-src 'self'; script-src 'nonce-random123';", 'Strict-Transport-Security' => 'max-age=31536000; includeSubDomains' ]);

Return values
$this

The current instance of APIManager for method chaining.


        
On this page

Search results