ApiKeyAPCu
extends ApiKeyMemory
in package
Class ApiKeyAPCu: Extends ApiKeyMemory to provide API key storage and retrieval using the APCu cache.
APCu (Alternative PHP Cache User Cache) is an in-memory key-value store for PHP. This class leverages APCu to efficiently store and retrieve API key data, offering potentially faster performance compared to storing keys solely in memory within a single request lifecycle.
Tags
Table of Contents
Properties
- $created : int
- $data : string
- $debug : bool
- A static flag to enable or disable debug output.
- $hashed_public_key : string
- $ip : string
- $label : string
- $public_key : string
- The public key associated with this Key object.
- $ttl : int
- $APP_KEY : string
- $HASH_ALGO : string
- $KEY_LENGTH : int
- $memory : array<string|int, mixed>
Methods
- __construct() : mixed
- Key constructor.
- anatomy() : array<string|int, mixed>
- Analyzes a token and provides its anatomy in relation to a given Key object.
- check() : bool
- Checks if a given API token is valid by retrieving the corresponding key from memory.
- create() : self
- Creates a new Key object with pre-defined hashed public key and data.
- dict() : array<string|int, mixed>
- Returns an associative array representing the Key object's label, IP address, and data.
- file() : string
- Constructs a file path based on a given timestamp and an optional filename.
- file_path() : string
- Generates the specific file path for this instance's data storage.
- hmac() : string
- Computes the HMAC (Hash-based Message Authentication Code) of a given text.
- make() : Key
- Generates a new API key, saves it in memory, and returns the token.
- parse() : array<string|int, mixed>
- Parses a token to extract the public key and the shared key (HMAC of the private key).
- test() : void
- Performs a basic test of the API key functionality using APCu for storage.
- token() : string
- Generates a token by concatenating the public key and the HMAC of the private key.
- valid() : bool
- Validates a given token against the current Key object's private key and application key.
- load() : array<string|int, mixed>|null
- Loads API key data from the APCu cache based on the hashed public key and creation timestamp.
- save() : bool
- Saves a Key object to the APCu cache.
- data() : string
- Manages the internal data of the object, allowing retrieval in hexadecimal format or setting it from a hexadecimal string.
- private_key() : array<string|int, mixed>
- Extracts the private key from the `$data` property.
- random_key() : string
- Generates a random key of the specified length.
Properties
$created
public
int
$created
= 0
$data
public
string
$data
= ''
$debug
A static flag to enable or disable debug output.
public
static bool
$debug
= false
Defaults to false.
Tags
$hashed_public_key
public
string
$hashed_public_key
= ''
$ip
public
string
$ip
$label
public
string
$label
$public_key
The public key associated with this Key object.
public
string
$public_key
Tags
$ttl
public
int
$ttl
= 0
$APP_KEY
private
string
$APP_KEY
$HASH_ALGO
private
string
$HASH_ALGO
= API_KEY_DEFAULT_ALGO
$KEY_LENGTH
private
int
$KEY_LENGTH
= API_KEY_DEFAULT_LENGTH
$memory
private
static array<string|int, mixed>
$memory
= []
A static array that holds the API keys in memory. The keys of this array are the hashed public keys, and the values are arrays representing the key data.
Tags
Methods
__construct()
Key constructor.
public
__construct(string $label, string $ip, string $APP_KEY[, int $KEY_LENGTH = API_KEY_DEFAULT_LENGTH ][, string $HASH_ALGO = API_KEY_DEFAULT_ALGO ][, string $hashed_public_key = '' ][, string $data = '' ][, int $created = 0 ][, int $ttl = 0 ]) : mixed
Initializes a new Key object. If $hashed_public_key
or $data
are not provided,
it generates a new public key, a corresponding hashed public key, and associated data.
Parameters
- $label : string
-
A label for this key.
- $ip : string
-
The IP address associated with this key.
- $APP_KEY : string
-
The application-specific secret key used for hashing. This is required.
- $KEY_LENGTH : int = API_KEY_DEFAULT_LENGTH
-
The length of the generated random keys in bytes. Defaults to API_KEY_DEFAULT_LENGTH.
- $HASH_ALGO : string = API_KEY_DEFAULT_ALGO
-
The hashing algorithm to use for HMAC. Defaults to API_KEY_DEFAULT_ALGO. Must be a supported algorithm by
hash_hmac_algos()
. - $hashed_public_key : string = ''
-
An optional pre-computed hashed public key.
- $data : string = ''
-
Optional pre-existing data associated with the key.
- $created : int = 0
-
Optional pre-existing creation timestamp. If not provided.
- $ttl : int = 0
-
The time-to-live (in seconds) for this key. After this duration, the key is considered expired. A value of 0 indicates that the key never expires. Defaults to 0.
Tags
anatomy()
Analyzes a token and provides its anatomy in relation to a given Key object.
public
static anatomy(string $token, Key $key) : array<string|int, mixed>
Parameters
- $token : string
-
The token to analyze.
- $key : Key
-
The Key object to compare against.
Tags
Return values
array<string|int, mixed> —An associative array containing the token, extracted public key, shared key, the Key object's public key and hashed public key, the Key object's data, and a boolean indicating if the token is valid for the given Key object.
check()
Checks if a given API token is valid by retrieving the corresponding key from memory.
public
static check(string $token[, string $ip = '' ][, string $APP_KEY = APP_KEY ][, int $KEY_LENGTH = API_KEY_DEFAULT_LENGTH ][, string $HASH_ALGO = API_KEY_DEFAULT_ALGO ]) : bool
Parameters
- $token : string
-
The API token to check.
- $ip : string = ''
-
The IP address associated with this key (optional, defaults to '').
- $APP_KEY : string = APP_KEY
-
The application-specific secret key used for signing (defaults to the global APP_KEY constant).
- $KEY_LENGTH : int = API_KEY_DEFAULT_LENGTH
-
The expected length of the public and private keys (defaults to API_KEY_DEFAULT_LENGTH).
- $HASH_ALGO : string = API_KEY_DEFAULT_ALGO
-
The hashing algorithm used (defaults to API_KEY_DEFAULT_ALGO).
Tags
Return values
bool —Returns true if the token is valid, false otherwise.
create()
Creates a new Key object with pre-defined hashed public key and data.
public
static create(string $hashed_public_key, string $data, string $APP_KEY[, string $label = '' ][, string $ip = '' ][, int $ttl = 0 ][, int $created = 0 ][, int $KEY_LENGTH = API_KEY_DEFAULT_LENGTH ][, string $HASH_ALGO = API_KEY_DEFAULT_ALGO ]) : self
This static method is useful for reconstructing a Key object from stored data.
Parameters
- $hashed_public_key : string
-
The pre-computed hashed public key.
- $data : string
-
The pre-existing data associated with the key.
- $APP_KEY : string
-
The application-specific secret key used for hashing.
- $label : string = ''
-
An optional label for this key. Defaults to an empty string.
- $ip : string = ''
-
The IP address associated with this key. Defaults to an empty string.
- $ttl : int = 0
-
The time-to-live (in seconds) for this key. After this duration, the key is considered expired. A value of 0 indicates that the key never expires. Defaults to 0.
- $created : int = 0
-
Optional pre-existing creation timestamp. If not provided.
- $KEY_LENGTH : int = API_KEY_DEFAULT_LENGTH
-
The length of the original random keys in bytes. Defaults to API_KEY_DEFAULT_LENGTH.
- $HASH_ALGO : string = API_KEY_DEFAULT_ALGO
-
The hashing algorithm used for HMAC. Defaults to API_KEY_DEFAULT_ALGO.
Tags
Return values
self —A new Key object initialized with the provided data.
dict()
Returns an associative array representing the Key object's label, IP address, and data.
public
dict() : array<string|int, mixed>
Tags
Return values
array<string|int, mixed> —An associative array with keys 'label', 'ip', and 'data'.
file()
Constructs a file path based on a given timestamp and an optional filename.
public
static file(int $created[, string $file = '' ]) : string
This static method generates a directory structure using the year, month, and day extracted from the provided timestamp. The resulting path can optionally include a filename at the end.
Parameters
- $created : int
-
A timestamp representing the creation date. This timestamp is expected to be an integer with a length of 8 digits (YYYYMMDD format). An assertion will fail if this condition is not met.
- $file : string = ''
-
An optional filename to append to the generated directory path. Defaults to an empty string.
Tags
Return values
string —The generated file path, with directory separators appropriate
for the operating system. The path will be in the format:
YYYY/MM/DD[/filename]
.
file_path()
Generates the specific file path for this instance's data storage.
public
file_path() : string
This method leverages the file()
static method to create a structured file path.
The path is determined by the instance's creation timestamp and a unique
identifier derived from its hashed public key. This strategy ensures a
well-organized and distributed storage system.
Tags
Return values
string —The generated file path. The path is composed of subdirectories representing the year, month, and day of creation, followed by the instance's hashed public key as the filename. The directory separators are platform-specific.
hmac()
Computes the HMAC (Hash-based Message Authentication Code) of a given text.
public
static hmac(string $text, string $APP_KEY[, string $HASH_ALGO = API_KEY_DEFAULT_ALGO ]) : string
Parameters
- $text : string
-
The input string to hash.
- $APP_KEY : string
-
The secret key to use for the HMAC.
- $HASH_ALGO : string = API_KEY_DEFAULT_ALGO
-
The hashing algorithm to use. Defaults to API_KEY_DEFAULT_ALGO.
Tags
Return values
string —The hexadecimal representation of the HMAC.
make()
Generates a new API key, saves it in memory, and returns the token.
public
static make(string $label[, string $ip = '' ][, int $ttl = 0 ][, string $APP_KEY = APP_KEY ][, int $KEY_LENGTH = API_KEY_DEFAULT_LENGTH ][, string $HASH_ALGO = API_KEY_DEFAULT_ALGO ]) : Key
Parameters
- $label : string
-
A descriptive label for the API key.
- $ip : string = ''
-
The IP address associated with this key (optional, defaults to '').
- $ttl : int = 0
-
The time-to-live (in seconds) for this key. After this duration, the key is considered expired. A value of 0 indicates that the key never expires. Defaults to 0.
- $APP_KEY : string = APP_KEY
-
The application-specific secret key used for signing (defaults to the global APP_KEY constant).
- $KEY_LENGTH : int = API_KEY_DEFAULT_LENGTH
-
The desired length of the public and private keys (defaults to API_KEY_DEFAULT_LENGTH).
- $HASH_ALGO : string = API_KEY_DEFAULT_ALGO
-
The hashing algorithm to use (defaults to API_KEY_DEFAULT_ALGO).
Tags
Return values
Key —The generated API token object.
parse()
Parses a token to extract the public key and the shared key (HMAC of the private key).
public
static parse(string $token[, int $KEY_LENGTH = API_KEY_DEFAULT_LENGTH ][, string $HASH_ALGO = API_KEY_DEFAULT_ALGO ]) : array<string|int, mixed>
Parameters
- $token : string
-
The token to parse.
- $KEY_LENGTH : int = API_KEY_DEFAULT_LENGTH
-
The expected length of the public key in bytes. Defaults to API_KEY_DEFAULT_LENGTH.
- $HASH_ALGO : string = API_KEY_DEFAULT_ALGO
-
The hashing algorithm that was used to generate the HMAC. Defaults to API_KEY_DEFAULT_ALGO.
Tags
Return values
array<string|int, mixed> —An array containing the public key (at index 0) and the shared key (at index 1), or an empty array if the token format is invalid or the hash algorithm is unsupported.
test()
Performs a basic test of the API key functionality using APCu for storage.
public
static test([bool $debug = false ]) : void
This method is designed to verify that the API key generation, storage (via APCu), and validation mechanisms are working correctly. It defines a constant for the application key (which would typically be defined elsewhere in a real application), optionally enables debugging output, creates a new API key with specific parameters, and then performs a series of assertions to validate different aspects of the key. These assertions include checking if a key and its token are generated, if the key is valid with the correct token and IP address, if it's invalid with a wrong IP address or an empty/invalid token, and if the time-to-live (TTL) mechanism is working as expected.
Note: This test relies on the APCu extension being enabled and configured in your PHP environment.
Parameters
- $debug : bool = false
-
Optional. If true, enables debugging output using
self::debug()
. Defaults to false.
Tags
token()
Generates a token by concatenating the public key and the HMAC of the private key.
public
token() : string
Tags
Return values
string —The generated token.
valid()
Validates a given token against the current Key object's private key and application key.
public
valid(string $token[, string $ip = '' ]) : bool
Parameters
- $token : string
-
The token to validate.
- $ip : string = ''
-
The IP address associated with this key. Defaults to an empty string.
Tags
Return values
bool —True if the token is valid, false otherwise.
load()
Loads API key data from the APCu cache based on the hashed public key and creation timestamp.
protected
static load(string $hashed_public_key, int $created) : array<string|int, mixed>|null
This method checks if a key exists in the APCu cache using the provided
hashed public key. If it exists, the associated data is fetched and returned.
If the key does not exist, NULL is returned. The $created
timestamp is included
in the method signature for potential future use or consistency with other
storage mechanisms, although it is not directly used in this APCu implementation.
Parameters
- $hashed_public_key : string
-
The hashed public key of the API key to load.
- $created : int
-
The creation timestamp of the API key (not directly used in this implementation).
Return values
array<string|int, mixed>|null —An associative array representing the API key data if found, NULL otherwise.
save()
Saves a Key object to the APCu cache.
protected
static save(Key $key) : bool
The key for storage in APCu is the hashed public key of the API key. The value stored is an associative array representing the key's attributes.
Parameters
- $key : Key
-
The Key object to save.
Return values
bool —True on successful storage, false otherwise.
data()
Manages the internal data of the object, allowing retrieval in hexadecimal format or setting it from a hexadecimal string.
private
data([string $data_hex = '' ]) : string
When called without any arguments, this method decodes the internal base64 encoded data and returns its hexadecimal representation.
When called with a hexadecimal string as an argument, it encodes this string into base64 and updates the internal data of the object. In this case, the method returns an empty string.
Parameters
- $data_hex : string = ''
-
Optional. A hexadecimal string to set as the internal data. Defaults to an empty string, in which case the current data is returned in hexadecimal format.
Tags
Return values
string —The hexadecimal representation of the internal data if no argument is provided. An empty string if a hexadecimal string is provided as an argument.
private_key()
Extracts the private key from the `$data` property.
private
private_key() : array<string|int, mixed>
This function assumes that the $data
property has a specific structure:
random bytes (1 to KEY_LENGTH) + hashed public key + private key + random bytes (1 to KEY_LENGTH).
It extracts the private key based on the position of the $hashed_public_key
.
Tags
Return values
array<string|int, mixed> —The extracted private key with IP.
random_key()
Generates a random key of the specified length.
private
random_key() : string
Tags
Return values
string —A hexadecimal representation of the random key.