Luminova Framework

PHP Luminova: Runtime Utility Class

Last updated: 2026-11-28 20:57:12

Luminova built-in development server, leveraging PHP's development server functionality. This is useful for development and testing your application in a controlled environment.

The Runtime class is the central utility hub for the Luminova framework and application runtime. It provides framework-level static helper methods to simplify common runtime, environment, and platform checks, along with a lightweight in-memory shared storage registry that can be accessed across the application codebase.

All methods are static, so there's no need to instantiate the class.

NoteThe shared storage provided by this class is runtime-only, comparable in concept to Swift's UserDefaults or Android/Java SharedPreferences, but not persistent:

  • Data is lost at the end of each request.
  • Values are not shared across processes or workers.
  • Nothing is written to disk.

Usage Examples

use Luminova\Runtime;

Runtime::set('THEME', true);

$context = Runtime::get('THEME', false);

if (Runtime::has('THEME')) {
    // Key exists...
}

Runtime::remove('THEME');
Runtime::clear();

Class Definition

  • Full namespace: \Luminova\Runtime
  • This class is a Final class

Constants

ConstantValueDescription
QUERY_DEBUGluminova.b.query.debugEnable or store query debug information.
ALTER_DROP_COLUMNSluminova.b.db.alter_drop_columnsAllow dropping columns during table alteration.
CHECK_ALTER_TABLEluminova.b.db.check_alter_tableEnable validation before running ALTER TABLE operations.
MIGRATION_SUCCESSluminova.b.migration.successFlag indicating a successful migration execution.
ALTER_SUCCESSluminova.b.alter.successFlag indicating a successful table alteration.
DROP_TRANSACTIONluminova.O.db.transactionStore database transaction object.
QUERY_PROFILINGluminova.a.db.query.profilingStore query execution profiling data.
CLASS_METADATAluminova.a.class.metadataStore routed class metadata used during runtime.
TEMPLATE_CONTEXTluminova.s.template.contextStore rendered template context ID.

Methods

isEnv

Determine whether the application is running in the specified runtime.

The comparison is case-insensitive.

public static function isEnv(string $name): bool

Parameters:

ParameterTypeDescription
$namestringRuntime name to check.

Return:

bool - Return true if the current runtime matches, otherwise false.

Example:

if (Runtime::isEnv('docker')) {
    // Running inside a Docker container.
}

isLocal

Determine whether the current request is from a local environment.

This is a heuristic check based on:

  • Local hostnames (localhost, 127.0.0.1, ::1).
  • Private / loopback IP ranges (e.g., 127.x.x.x, 10.x.x.x, 192.168.x.x, 172.16.x.x to 172.31.x.x).

The result is cached after the first call.

public static function isLocal(): bool

Return:

bool - Return true if the request appears to originate from a local environment.

Note:This does NOT guarantee environment type (dev/prod). It only detects local network characteristics.

Example:

if (Runtime::isLocal()) {
    // Skip strict CORS checks for local development.
}

isDocker

Determine whether the application is running in a Docker environment.

This is a convenience wrapper around self::isContainer() that checks specifically for the Docker runtime.

public static function isDocker(): bool

Return:

bool - Return true if Docker is detected, otherwise false.

Example:

if (Runtime::isDocker()) {
    // Use container-friendly file paths.
}

isContainer

Determine whether the application is running in a supported runtime environment.

When no runtime is specified, checks whether any supported runtime is detected. When a runtime is specified, checks only that runtime. The php alias is treated as novakit.

Supported runtimes include docker, kubernetes, containerd, podman, and novakit.

public static function isContainer(?string $runtime = null): bool

Parameters:

ParameterTypeDescription
$runtime?stringRuntime name to check, or null to check for any supported runtime.

Return:

bool - Return true if the requested runtime is detected, otherwise false.

Example:

if (Runtime::isContainer('kubernetes')) {
    // Running inside a Kubernetes pod.
}

if (Runtime::isContainer()) {
    // Running inside any supported container runtime.
}

isOutsideContainer

Determine whether the application is running outside a detected runtime environment.

Checks if any supported container or runtime environment is detected.

public static function isOutsideContainer(): bool

Return:

bool - Return true if no supported runtime is detected, otherwise false.

Example:

if (Runtime::isOutsideContainer()) {
    // Running directly on bare metal or a VM.
}

name

Get the name of the current runtime environment.

The runtime name is resolved from the RUNTIME_ENV environment variable. This allows the runtime to be explicitly identified when automatic container detection cannot determine the environment.

public static function name(): ?string

Return:

string|null - Return the runtime name, or null if none is defined.

Example:

$runtime = Runtime::name();

// e.g., "docker", "podman", "kubernetes", or null

The value may be set through any container configuration mechanism that exposes environment variables to the application, including Docker, Docker Compose, Podman, Kubernetes, or a container orchestration platform.

Setting the runtime name:

Docker:

ENV RUNTIME_ENV=docker

Docker Compose:

services:
  app:
    environment:
      RUNTIME_ENV: docker

Podman:

podman run -e RUNTIME_ENV=podman my-app

Kubernetes:

env:
  - name: RUNTIME_ENV
    value: kubernetes

Any container configuration that exposes RUNTIME_ENV to PHP can be used:

RUNTIME_ENV=<runtime-name>

For example:

RUNTIME_ENV=docker
RUNTIME_ENV=podman
RUNTIME_ENV=kubernetes
RUNTIME_ENV=ecs
RUNTIME_ENV=custom-runtime

This is useful when the runtime cannot be reliably detected from container-specific files or /proc/1/cgroup.


isCommand

Determine whether the application is running in CLI (Command-Line Interface) mode.

Uses the PHP SAPI and common CLI indicators to distinguish command-line execution from web requests.

public static function isCommand(): bool

Return:

bool - Return true if running in CLI mode, otherwise false.

Example:

if (Runtime::isCommand()) {
    // Running via CLI/novakit.
}

isHmvc

Determine whether HMVC mode is enabled.

The env(feature.app.hmvc) configuration value is read once and cached for subsequent calls.

public static function isHmvc(): bool

Return:

bool - Return true if HMVC mode is enabled, otherwise false.

Example:

if (Runtime::isHmvc()) {
    // Resolve controllers using the HMVC module structure.
}

isPlatform

Determine whether the application is running on a specific platform.

Supports common operating system families, BSD variants, Solaris, and common AWS and Azure runtime environments. Custom platform names are matched against the operating system name returned by php_uname().

Supported Platform Values:

  • mac — macOS.
  • windows — Windows.
  • linux — Linux.
  • freebsd — FreeBSD.
  • openbsd — OpenBSD.
  • bsd — Any BSD-based operating system.
  • solaris — Solaris.
  • aws — AWS runtime environment.
  • azure — Azure runtime environment.

Custom platform names are also supported and are matched case-insensitively against the current operating system name.

public static function isPlatform(string ...$names): bool

Parameters:

ParameterTypeDescription
$namesstringPlatform name to check, such as windows, linux, mac, aws, or azure.

Return:

bool - Return true if the current platform matches the specified name, otherwise false.

Example:

Runtime::isPlatform('windows');
Runtime::isPlatform('linux');
Runtime::isPlatform('mac');
Runtime::isPlatform('aws');
Runtime::isPlatform('azure');

isFunctionDisabled

Check whether a PHP function is disabled by the server configuration.

Reads the configured disabled function list and checks if the specified function is unavailable due to PHP's disable_functions setting.

public static function isFunctionDisabled(string $function): bool

Parameters:

ParameterTypeDescription
$functionstringThe PHP function name to check.

Return:

bool - Return true if the function is disabled, otherwise false.

Example:

if (Runtime::isFunctionDisabled('exec')) {
    // Fall back to an alternative implementation.
}

disabledFunctions

Returns the list of disabled PHP functions (via the disable_functions directive).

For a single lookup, use isFunctionDisabled(). For repeated lookups, request the associative map and test for keys.

public static function disabledFunctions(bool $flipValue = false): array

Parameters:

ParameterTypeDescription
$flipValueboolRequest an associative lookup keyed by function name (default false).

Return:

array<int,string>|array<string,int|true> - Returns function names or a lookup map keyed by function name.

Example:

$disabled = Runtime::disabledFunctions(true);

if (isset($disabled['exec'])) {
    // "exec" is disabled on this server.
}

tryFunction

Call a PHP function if it exists and is not disabled.

Returns null when the function is unavailable due to being undefined or disabled by PHP configuration.

public static function tryFunction(string $function, mixed ...$arguments): mixed

Parameters:

ParameterTypeDescription
$functionstringFunction name to call.
$argumentsmixedArguments passed to the function.

Return:

mixed - Return the function result, or null if the function is unavailable.

Example:

$result = Runtime::tryFunction('set_time_limit', 300);

if ($result === null) {
    echo 'Function is unavailable.';
}

isCallable

Check whether the given value is callable or represents a callable reference.

In addition to standard PHP callables, two-element arrays are accepted as callable references even when the target cannot currently be called. When $strict is enabled, the referenced class and method must exist.

public static function isCallable(mixed $input, bool $strict = false): bool

Parameters:

ParameterTypeDescription
$inputmixedThe value to check (string, array, closure, object, etc.).
$strictboolIf true, array callables are valid only if the referenced class exists.

Return:

bool - Return true if the value is callable or a valid callable reference, otherwise false.


setEncoding

Set the internal multibyte encoding.

On success, the applied encoding is also stored under the app.mb.encoding environment key.

public static function setEncoding(string $encoding): bool

Parameters:

ParameterTypeDescription
$encodingstringThe default internal encoding.

Return:

bool - Return false if encoding is empty or mb_internal_encoding is unavailable, otherwise true.

Example:

Runtime::setEncoding('UTF-8');

permission

Check whether a file or directory has the required access permissions.

Checks each requested permission and returns true only when allpermissions are available. When a permission check fails, this methodreturns false by default. If $silent is false, it logs the failurein production and throws a FileException.

Permissions may be specified using shorthand (r, w, x) or readablenames (read, write, execute). Multiple permissions can be combinedusing underscores, plus signs, or commas, and their order is not significant.

public static function permission(
    string $permission = 'rw',
    ?string $file = null,
    bool $silent = true
): bool

Parameters:

ParameterTypeDescription
$permissionstringThe access permission or combination of permissions to check (default 'rw').
$file?stringThe file or directory path to check. If null, defaults to the application's writeable directory.
$silentboolWhether to suppress the exception and return false when a required permission is unavailable. (default: true).

Return:

bool - Return true if all required permissions are available, otherwise false.

Throws:

  • Luminova\Exceptions\FileException - If the file does not have the required permissions, $silent is false, and the failure could not be logged (i.e. not in production, or logging failed to dispatch).

hasPermission

Check whether a file or directory has the specified access permissions.

Supports read, write, and execute permissions individually or in combination. Permissions can be specified using shorthand (r, w, x) or readable names (read, write, execute). Multiple permissions may be separated by underscores, plus signs, or commas, and their order is not significant. Unlike self::permission(), this method never throws and simply returns the check result.

Supported permissions:

  • r or read - Read access.
  • w or write - Write access.
  • x or execute - Execute access.
  • rw or read_write - Read and write access.
  • rx or read_execute - Read and execute access.
  • wx or write_execute - Write and execute access.
  • rwx or read_write_execute - Read, write, and execute access.
public static function hasPermission(
    string $permission,
    string $file
): bool

Parameters:

ParameterTypeDescription
$permissionstringThe access permission or combination of permissions to check.
$filestringThe file or directory path to check.

Return:

bool - Return true if all requested permissions are available, otherwise false.

Example:

Runtime::hasPermission('read', $file);
Runtime::hasPermission('read_write', $file);
Runtime::hasPermission('write+read', $file);
Runtime::hasPermission('execute,read,write', $file);
Runtime::hasPermission('rwx', $file);

setTimezone

Sets the default PHP timezone.

If the specified timezone is already active, no changes are made and true is returned. The timezone may be provided as a DateTimeZone instance or a valid timezone identifier. On success, the applied timezone is also stored under the app.timezone environment key.

public static function setTimezone(DateTimeZone|string $timezone): bool

Parameters:

ParameterTypeDescription
$timezoneDateTimeZone&#124;stringThe timezone to set.

Return:

bool - Return true on success, or false if the timezone is empty, invalid, or date_default_timezone_set() is unavailable.

Example:

$timezone = 'UTC';

Runtime::setTimezone($timezone);
echo date_default_timezone_get(); // UTC

// Optionally read back the applied value from env
echo env('app.timezone'); // UTC

setExecutionTime

Set the max script execution time, in seconds.

Updates the limit only when increasing it or disabling it (0). Has no effect on Windows. On success, the applied value is also stored under the script.execution.limit environment key.

public static function setExecutionTime(int $seconds): bool

Parameters:

ParameterTypeDescription
$secondsintTime limit in seconds (0 = unlimited).

Return:

bool - Return true on success, false otherwise.

Example:

Runtime::setExecutionTime(300);

setIgnoreUserAbort

Set whether the script should continue running after the client disconnects.

On success, the applied flag is also stored under the script.ignore.abort environment key.

public static function setIgnoreUserAbort(bool $ignore): bool

Parameters:

ParameterTypeDescription
$ignoreboolWhether to ignore or continue on client disconnect.

Return:

bool - Return true on success, or false if ignore_user_abort() is unavailable.

Example:

Runtime::setIgnoreUserAbort(true);

setLocale

Set the default locale for all or specific locale categories.

On success, when $category is LC_ALL, the applied locale is also stored under the app.locale environment key.

public static function setLocale(string $locale, int $category = LC_ALL): bool

Parameters:

ParameterTypeDescription
$localestringThe default application locale to set.
$categoryintThe category affected by the locale setting (e.g., LC_*).

Return:

bool - Return true if the locale was applied, false if $locale is empty or invalid.

Example:

Runtime::setLocale('en_US.UTF-8');
Runtime::setLocale('en_US.UTF-8', LC_TIME);

For request-derived cache identifiers, see AbstractKernel::getRequestCacheId().


Runtime Cache

set

Store a shared value by key.

Saves a value in the shared storage. If both the existing value and the new value are arrays, they are merged using array_replace, with the new values overriding existing ones.

public static function set(string $key, mixed $value): mixed

Parameters:

ParameterTypeDescription
$keystringThe storage key.
$valuemixedThe value to store.

Return:

mixed - Return the stored value.

Example:

use Luminova\Runtime;

Runtime::set('theme', 'dark');
Runtime::set('config', ['debug' => true]);
Runtime::set('config', ['cache' => false]); // merges with existing array

add

Add a value to a shared array entry.

Ensures the storage key exists as an array, then assigns the value at the given index.

public static function add(string $key, string|int $index, mixed $value): mixed

Parameters:

ParameterTypeDescription
$keystringThe storage key.
$indexstring&#124;intThe array index to add the value to.
$valuemixedThe value to store.

Return:

mixed - Return the stored value.

Example:

use Luminova\Runtime;

Runtime::add('routes', 'home', '/');
Runtime::add('routes', 'login', '/login');

get

Get a shared value.

Retrieves a value stored under the specified key. Returns null if the key does not exist.

public static function get(string $key): mixed

Parameters:

ParameterTypeDescription
$keystringThe key to retrieve.

Return:

mixed - Return the stored value or null if not found.

Example:

use Luminova\Runtime;

$theme = Runtime::get('theme') ?? 'light';

has

Check if a key exists in the shared storage.

public static function has(string $key): bool

Parameters:

ParameterTypeDescription
$keystringThe key to check.

Return:

bool - Return true if the key exists, false otherwise.

Example:

use Luminova\Runtime;

if (Runtime::has('theme')) {
    echo Runtime::get('theme');
}

remove

Remove a value from the shared storage.

By default, this method protects Luminova internal keys (see ALL_KEYS) and will not remove framework-owned storage entries. To force removal of a core key, explicitly set $userDefined to false.

public static function remove(string $key, bool $userDefined = true): void

Parameters:

ParameterTypeDescription
$keystringThe storage key to remove.
$userDefinedboolWhether to enforce protection for core keys.

Example:

use Luminova\Runtime;

// Remove a user-defined key
Runtime::remove('theme');

// Force removal of a core key (not recommended)
Runtime::remove(Runtime::CLASS_METADATA, false);

clear

Clear all user-defined values from the shared storage.

Core Luminova keys (see ALL_KEYS) are preserved and cannot be removed by this method. This makes the operation safe to use in long-running processes and framework-level code.

public static function clear(): void

Example:

use Luminova\Runtime;

Runtime::clear();

count

Count the number of keys currently stored.

public static function count(): int

Return:

int - Return the number of stored keys.

Example:

use Luminova\Runtime;

$count = Runtime::count();

isProduction

Determines whether the application is running in production mode.

public static function isProduction(): bool

Return:

bool - Returns true if the application is in production mode, false otherwise.


isStaging

Determines whether the application is running in staging mode.

public static function isStaging(): bool

Return:

bool - Returns true if the application is in staging mode, false otherwise.


isLocalhost

Determine whether the current request is addressed to localhost.

public static function isLocalhost(): bool

Return:

bool - true if the request is addressed to localhost, otherwise false.


memoryLimit

Get the current PHP memory limit in bytes.

public static function memoryLimit(
    int $division = 0,
    int $reserve = 0
): int

Parameters:

ParameterTypeDescription
$divisionintOptional positive division factor used to scale down the memory limit (default 0).
$reserveintOptional minimum memory value in bytes (default 0).

Return:

int - The memory limit in bytes, or 0 when it cannot be determined.


safeMemoryLimit

Calculate a safe memory limit for an operation.

public static function safeMemoryLimit(int $megabytes = 16): int

Parameters:

ParameterTypeDescription
$megabytesintMaximum memory to allow in megabytes.

Return:

int - The safe memory limit in bytes.


getIniValue

Retrieves the value of a PHP configuration directive.

public static function getIniValue(string $name): string

Parameters:

ParameterTypeDescription
$namestringThe PHP configuration directive name.

Return:

string - Returns the directive value.


tryGetIniValue

Attempts to retrieve the value of a PHP configuration directive.

public static function tryGetIniValue(
    string $name,
    string|false $default = false
): string|false

Parameters:

ParameterTypeDescription
$namestringThe PHP configuration directive name.
$defaultstring&#124;falseDefault value returned when the directive cannot be read.

Return:

string|false - Returns the directive value, or the default value on failure.


trySetIniValue

Attempts to set a PHP configuration directive at runtime.

public static function trySetIniValue(string $name, mixed $value): string|false

Parameters:

ParameterTypeDescription
$namestringThe PHP configuration directive name.
$valuemixedThe value to assign.

Return:

string|false - Returns the previous value on success, or false on failure.


getConstantValue

Retrieves the value of a defined PHP constant.

public static function getConstantValue(string $name, mixed $default = null): mixed

Parameters:

ParameterTypeDescription
$namestringThe constant name, including its class or namespace if applicable.
$defaultmixedThe fallback value when the constant is not defined.

Return:

mixed - Returns the constant value if defined, otherwise the default value.


isProfilingEnabled

Determine whether performance profiling is enabled.

public static function isProfilingEnabled(): bool

Return:

bool - true if performance profiling is enabled, otherwise false.


isPhpServer

Identify the built-in PHP server started by Novakit, using the server marker and Novakit version.

public static function isPhpServer(): bool

Return:

bool - Returns true when both the PHP server SAPI and Novakit marker match.


isLocalAddress

Check the first available address from HTTP_HOST, SERVER_NAME, or REMOTE_ADDR. A single port suffix is removed and the result is cached.

public static function isLocalAddress(): bool

Return:

bool - Returns true when the address is an IPv4 address in the 10/8, 172.16/12, or 192.168/16 ranges.


isWsl

Detect Windows Subsystem for Linux using the WSL environment variables or the Linux kernel version string.

public static function isWsl(): bool

Return:

bool - Returns true when a WSL marker is detected on Linux.


isUploadProgressEnabled

Check the PHP session upload progress settings. The result is cached.

public static function isUploadProgressEnabled(): bool

Return:

bool - Returns true when upload progress is enabled and the progress field name is non-empty.


cleanOutputBuffers

Discard or flush PHP output buffers. auto preserves at least one buffer, all clears down to the limit, top discards the top buffer, and flush flushes it. CLI and PHPDBG calls return false.

public static function cleanOutputBuffers(string $mode = 'auto', int $limit = 0): bool

Parameters:

ParameterTypeDescription
$mode'auto'\|'all'\|'top'\|'flush'Buffer handling mode.
$limitintMinimum level to preserve for auto and all. Must be non-negative.

Return:

bool - Returns true if a buffer was cleared or flushed.


setOutputHandler

Start a PHP output buffer. When compression is enabled, the method uses the supplied handler, the configured handler, or ob_gzhandler.

public static function setOutputHandler(
    bool $clearIfSet = false,
    bool $useCompressionHandler = true,
    ?callable $handler = null,
    int $chunkSize = 0,
    int $flags = PHP_OUTPUT_HANDLER_STDFLAGS
): bool

Parameters:

ParameterTypeDescription
$clearIfSetboolTry to clear existing buffers first.
$useCompressionHandlerboolUse a compression handler when enabled by application settings.
$handlercallable\|nullOptional compression callback.
$chunkSizeintBuffer chunk size in bytes.
$flagsintPHP output-handler flags.

Return:

bool - Returns true when the buffer starts, or false if headers were sent, an existing buffer prevented startup, or startup failed.

Throws:

  • Luminova\Exceptions\InvalidArgumentException - If the configured compression handler is invalid.

lastError

Read the stored error details, falling back to PHP’s most recent error.

public static function lastError(): array

Return:

array{type:int,message:string,file:string,line:int}|array{} - Returns the error details or an empty array.


lastErrorCode

Read the stored error code.

public static function lastErrorCode(string|int $default = E_ERROR): string|int

Parameters:

ParameterTypeDescription
$defaultstring\|intFallback code when no code is stored.

Return:

string|int - Returns the stored code or the fallback.


lastErrorBacktrace

Read the stored backtrace.

public static function lastErrorBacktrace(): array

Return:

array<int,array<string,mixed>> - Returns the backtrace frames or an empty array.


setLastError

Store PHP error details for lastError().

public static function setLastError(array $error): void

Parameters:

ParameterTypeDescription
$errorarray{type:int,message:string,file:string,line:int}Error details to store.

setLastErrorCode

Store the code returned by lastErrorCode().

public static function setLastErrorCode(string|int $code): void

Parameters:

ParameterTypeDescription
$codestring\|intError code to store.

clearLastError

Clear the internal error context and PHP’s last recorded error.

public static function clearLastError(): void

setLastBacktrace

Store a backtrace in the internal error context.

public static function setLastBacktrace(array $backtrace, bool $push = true): void

Parameters:

ParameterTypeDescription
$backtracearray<int,array<string,mixed>>Backtrace frames.
$pushboolPrepend the supplied frames to an existing trace. False replaces it.

setIniValue

Update a PHP INI directive with ini_set().

public static function setIniValue(
    string $name,
    string|int|float|bool|null $value,
    ?string $label = null
): string

Parameters:

ParameterTypeDescription
$namestringINI directive name.
$valuestring\|int\|float\|bool\|nullNew value.
$labelstring\|nullOptional label used in the error message.

Return:

string - Returns the previous value.

Throws:

  • Luminova\Exceptions\RuntimeException - If the setter is unavailable or the change fails.

setMemoryLimit

Set the PHP memory limit in megabytes. Safe mode adjusts the request to respect current memory usage and an existing finite limit.

public static function setMemoryLimit(
    int $megabytes,
    bool $safeMode = true
): bool

Parameters:

ParameterTypeDescription
$megabytesintRequested memory limit in megabytes. Must be positive.
$safeModeboolApply the safe-mode bounds.

Return:

bool - Returns true when the limit is set or the target is already satisfied.


getStaticCacheTypes

Read the configured static cache types. The method removes empty values and duplicates and caches the resulting string.

public static function getStaticCacheTypes(): string

Return:

string - Returns a pipe-delimited configuration string, or an empty string when no types are configured.


profiling

Start or stop framework profiling when enabled. Repeated starts and stops without an active session are ignored.

public static final function profiling(string $mode, ?array $command = null): void

Parameters:

ParameterTypeDescription
$mode'start'\|'stop'Profiling action.
$commandarray<string,mixed>\|nullOptional command metadata passed to the profiler when stopping.

Throws:

  • Luminova\Exceptions\InvalidArgumentException - If profiling is enabled and the action is unsupported.

defineStandardStreams

Define missing PHP standard stream constants. The method attempts to open stdin for reading and stdout and stderr for writing. If PHP cannot open a stream, the corresponding constant receives its stream URI instead.

public static function defineStandardStreams(): void