Luminova Framework

PHP Luminova: Global Namespaced Helper Functions

Last updated: 2026-08-29 16:44:39

Luminova provides a collection of globally available helper functionsunder the `Luminova\Funcs` namespace for common application tasks.

The Namespaced Global Functions are procedural helpers provided by Luminova for handling common tasks across your application.

They are defined under the Luminova\Funcs namespace and are loaded automatically at runtime.Unlike standard global helpers, they require explicit import or full namespace usage.


Why Use Namespaced Helpers?

  • Avoid Repetition: Define logic once and reuse it anywhere—no need to duplicate code across files.
  • Faster Development: Handle common tasks like paths, URLs, and formatting with simple function calls.
  • Better Readability: Replace long logic with short, clear helpers that are easier to read and maintain.

For user-defined helpers, see User-Defined Functions & Constants.For non-namespaced helpers like env() or setenv(), see Global Functions & Polyfills.


Usage

use function Luminova\Funcs\root;

root('public');

Import multiple functions:

use function Luminova\Funcs\{
    response,
    asset,
    href,
    root
};

Best Practice:

Import only the functions you need.Avoid wildcard imports (use function Luminova\Funcs\*), they reduce clarity and may cause conflicts.


Use Full Namespace

Luminova\Funcs\root('path', 'file.txt');

Incorrect Usage

Trying to access function without namespace.

root('path', 'file.txt'); // function not found

Notes:

These functions are not available globally by defaultYou must either:

import them using use function, orcall them with the full namespace


Functions

root

Resolve the application root directory with optional appended path and filename.

This function helps ensure all paths are built relative to the application's APP_ROOT.

function root(?string $path = null, ?string $filename = null, bool $normalize = false): string

Parameters:

ParameterTypeDescription
$pathstring|nullOptional subdirectory relative to the application root (e.g., writeable/logs).
$filenamestring|nullOptional filename to append after the path (e.g., debug.log).
$normalizeboolWhen true, converts the final path to OS-specific separators for filesystem use (default: false uses /).

Return Value:

string - Return a normalized absolute path based on APP_ROOT, with optional path and filename appended.

Note:Input separators (\ and /) are automatically normalized.The function does not validate whether the path exists.Use $normalize = true only for direct filesystem access.

Examples:

use function Luminova\Funcs\root;

$file = root('writeable/logs', 'debug.log');
// /var/www/app/writeable/logs/debug.log

$file = root('writeable/logs', 'debug.log', true);
// Linux:   /var/www/app/writeable/logs/debug.log
// Windows: C:\wamp64\www\app\writeable\logs\debug.log

app

Get the application instance.

Returns the current shared application instance or creates a new one.

  • When $shared is true (default), the shared application instance is returned.
  • When $shared is false, a new application instance is created via the kernel.
  • If $new is provided, it replaces the current shared application instance.
function app(bool $shared = true, ?Application $new = null): Luminova\Foundation\Core\Application

Parameters:

ParameterTypeDescription
$sharedboolWhether to return the shared instance (default: true).
$newLuminova\Foundation\Core\Application|nullOptional application instance to replace the shared one.

Return Value:

Luminova\Foundation\Core\Application - Return a shared or newly created application instance.

Examples:

use function Luminova\Funcs\app;

$app = app();

$app = app(shared: false);

app(new: new App\Application());

See Also

See Core Application documentation for more usages.


kernel

Resolve a service from the application kernel, or return the kernel instance itself.

function kernel(?string $service = null, bool $shared = true, mixed ...$arguments): object

Parameters:

ParameterTypeDescription
$servicestring|nullThe service identifier, or null to return the kernel instance.
$sharedboolWhether to reuse a shared instance when supported (default: true).
$argumentsmixedArguments passed to the service resolver.

Return Value:

object - Return the resolved service, or the kernel instance.

See Also

See Luminova::kernel() for the underlying implementation.


request

Retrieve an HTTP request object.

function request(bool $shared = true): RequestInterface

Parameters:

ParameterTypeDescription
$sharedboolWhether to return the shared request instance (default: true).

Return Value:

Luminova\Interface\RequestInterface - Return instance of the HTTP request object.

See Also

See HTTP Incoming Request documentation for request methods and usages.


response

Create a view response object.

Returns a new or shared instance of the view response handler, used to send JSON, HTML, Stream, Download or other content formats back to the client.

function response(int $status = 200, ?array $headers = null, bool $shared = true): Luminova\Template\Response

Parameters:

ParameterTypeDescription
$statusintHTTP status code (default: 200 OK).
$headersarray<string,mixed>|nullOptional response headers (default: null).
$sharedboolWhether to return a shared instance (default: true).

Return Value:

Luminova\Interface\ContentResponseInterface - Return instance of the view response object.

Examples:

use function Luminova\Funcs\response;

response()->json(['status' => 'OK', 'message' => 'Done!']);

response()
    ->compress()
    ->json(['status' => 'OK']);

response()
    ->minify()
    ->html('<body>...</body>');

See Also

See View Response Class documentation for more usage examples.


browser

Get detailed information about the user's browser and device capabilities.

function browser(?string $userAgent = null, string $return = 'object', bool $shared = true): mixed

Parameters:

ParameterTypeDescription
$userAgentstring|nullOptional user agent string to analyze (default: current UA).
$returnstringReturn type: 'array', 'object', or 'instance' (default: 'object').
$sharedboolIf true, reuse a static UserAgent instance when the browscap INI setting is unavailable (default: true).

Return Value:

array<string,mixed>|object{string,mixed}|Luminova\Http\UserAgent|false - Return the parsed browser information, the UserAgent instance, or false if detection fails.

Note:When PHP's browscap INI setting is configured and $return is not 'instance', this function uses get_browser() first, falling back to UserAgent::parse().

See Also

HTTP UserAgent Object documentation for browser user-agent methods.


view

Template view response helper.

Creates or reuses a View instance and prepares it to render the given template using the specified content type.

Note:This helper does not render the template immediately.It returns a View instance so you can chain rendering or return template content.

function view(string $template, string $type = View::HTML): Luminova\Template\View

Parameters:

ParameterTypeDescription
$templatestringTemplate file name or identifier.
$typestringTemplate content type (default: View::HTML).

Return Value:

Luminova\Template\View - Return the prepared view instance for rendering or content output.

Context:

// Route files
/route/*.php

// MVC HTTP controllers
/app/Controllers/Http/*.php

// HMVC Module-specific HTTP controllers
/app/Modules/<Module>/Controllers/Http/*.php

Examples:

use function Luminova\Funcs\view;

return view('index')
    ->render(['name' => 'Peter'], 200);

return view('index')
    ->contents(['name' => 'Peter'], 200);

Note:Use the view global function in HTTP controllers only when necessary.Otherwise always use $this->view() or $this->tpl->view()->render().


href

Generate a URL to a route or file within the application.

Builds either an absolute URL using APP_URL or a relative URL based on the current request depth.

function href(?string $uri = null, bool $absolute = false, ?int $depth = null): string

Parameters:

ParameterTypeDescription
$uristring|nullThe route, view name, or file path (default: null).
$absoluteboolWhether to return an absolute URL using APP_URL (default: false).
$depthint|nullDirectory depth used for relative URLs. When null, the depth is derived from the current request URI (default: null).

Return Value:

string - Return the generated URL.

Examples:

use function Luminova\Funcs\href;

href();                                  // "/"
href('about');                           // "/about"
href('about', depth: 3);                 // "../../../about"
href('admin/dashboard', true);           // "https://example.com/admin/dashboard"

See Also

asset()


asset

Generate a URL to a file in the public assets/ directory.

function asset(?string $filename = null, bool $absolute = false, ?int $depth = null): string

Parameters:

ParameterTypeDescription
$filenamestring|nullThe asset path or filename (e.g., css/app.css).
$absoluteboolWhether to return an absolute URL using APP_URL (default: false).
$depthint|nullDirectory depth used for relative URLs. When null, the depth is derived from the current request URI (default: null).

Return Value:

string - Return the generated URL to the asset file, or the base assets/ path if no filename is provided.

Examples:

use function Luminova\Funcs\asset;

asset('css/style.css');   // "/assets/css/style.css"
asset();                  // "/assets/"
href('css', depth: 3);  // "../../../assets/css"
asset('js/app.js', true); // "https://example.com/assets/js/app.js"

See Also

href()


abort

Immediately terminate the current request with an HTTP error response.

This function halts further execution and returns a response based on the given HTTP status code and optional message.

If $message is:

  • string: Treated as a plain message or rendered view (based on $type).
  • array|object: Returned as a JSON response.
  • null: Sends an empty response with the given status code and headers.

If $type is set, it forces the response format:

  • xml: Abort with an XML response.
  • text: Abort with a plain text response.
  • html: Abort with a raw HTML content.
  • null or unrecognized: Detect content from $message and render it.
function abort(
    int $status = 500,
    string|array|object|null $message = null,
    array $headers = [],
    ?string $type = null
): never

Parameters:

ParameterTypeDescription
$statusintHTTP status code (default: 500).
$messagestring|array|object|nullOptional message string, array (JSON), or object to return.
$headersarray<string,mixed>Optional HTTP headers to include in the response.
$typestring|nullOptional forced response type: xml, text, or html (default: null).

Return Value:

never - This function does not return; it ends the request.

Throws:

Examples:

use function Luminova\Funcs\abort;

abort(404); // Sends 404 with no message.
abort(403, 'Access denied.'); // Sends plain text.
abort(422, ['error' => 'Validation failed']); // Sends JSON.
abort(500, '<h1>Server Error</h1>', [], 'html'); // Sends HTML.

redirect

Redirect the client to a different URI.

Supports both standard Location header and Refresh header-based redirection.

function redirect(string $uri, ?string $method = null, int $status = 302): never

Parameters:

ParameterTypeDescription
$uristringTarget URL to redirect to.
$methodstring|nullRedirection method: 'refresh' or null for standard (default: null).
$statusintHTTP redirect status code (default: 302).

Return Value:

never

Examples:

use function Luminova\Funcs\redirect;

redirect('/home');

redirect(uri: '/new-url', status: 301);

redirect('/dashboard', 'refresh');

back

Redirect the user to the previous page.

Attempts to use the HTTP_REFERER header to go back. If unavailable, falls back to the provided URI or '/' if none is given.

function back(?string $fallback = null, ?string $method = null, int $status = 302): never

Parameters:

ParameterTypeDescription
$fallbackstring|nullURI to redirect to if no referer is found.
$methodstring|nullRedirection method ('refresh' or null for standard, default: null).
$statusintHTTP status code for the redirect (default: 302).

Return Value:

never


ask

Ask a question using the configured AI model.

This helper provides two behaviors:

  1. If $prompt is provided, the message is sent immediately and the response is returned as an array.
  2. If $prompt is null, the configured AI client is returned so additional methods can be chained before sending a request.
function ask(?string $prompt = null, object|string $model = 'gpt-4.1-mini', array $options = []): AIAgentInterface|array

Parameters:

ParameterTypeDescription
$promptstring|nullOptional message to send to the AI model.
$modelLuminova\AI\Model|object|stringModel enum, client object, or model name (default: gpt-4.1-mini).
$optionsarray<string,mixed>Optional request options passed to Agent::message().

Return Value:

Luminova\Interface\AIAgentInterface|Luminova\AI\Client\Anthropic|Luminova\AI\Client\OpenAI|Luminova\AI\Client\Ollama|array - Return the response array when $prompt is provided, otherwise the configured AI client instance.

Throws:

Examples:

use function Luminova\Funcs\ask;

ask('Hello!');

use Luminova\AI\Model;

ask('Explain PHP enums', Model::O3);

ask(model: Model::GPT_4_1)
    ->getAgent()
    ->message('Explain dependency injection in PHP');

See Also:

See AI Client Implementations for more information.


async

Wrap a task in an Awaitable Future for asynchronous execution.

Creates a Future without running the task immediately. The returned Awaitable can later be passed to await() to run and retrieve the result. Supports optional background detachment.

function async(callable $task, bool $detach = false): Luminova\Interface\Awaitable

Parameters:

ParameterTypeDescription
$task(callable():mixed)The task to run asynchronously.
$detachboolIf true, the task runs in a detached background process.

Return Value:

Luminova\Interface\Awaitable - Return an awaitable Future representing the task.

Throws:

Examples:

use function Luminova\Funcs\{async, await};

$future = async(fn() => doSomething());
$result = await($future);

$future = async(fn() => doWork(), detach: true);

See Also

Luminova\Components\Async::async()


background

Execute a callable asynchronously in a detached background worker.

The task starts immediately and does not block the current execution. Any exception thrown while preparing or starting the worker is logged and null is returned.

function background(callable $task, array $arguments = []): ?int

Parameters:

ParameterTypeDescription
$task(callable(array $args):mixed)The task to execute.
$argumentsarray<string,mixed>Optional arguments passed to the worker.

Return Value:

int|null - Return the worker process ID (PID), or null if the task could not be started.

See Also

Luminova\Components\Async::background()


await

Wait for an Awaitable task to finish and return its result.

Strictly accepts an Awaitable object. Blocks execution until the task completes, optionally allowing a delay between ticks and enforcing a maximum timeout.

function await(Awaitable $task, int $timeout = 0, float $delay = 0.1): mixed

Parameters:

ParameterTypeDescription
$taskLuminova\Interface\AwaitableThe awaitable task to run.
$timeoutintMaximum wait time in seconds (0 = unlimited).
$delayfloatDelay in seconds between execution checks (default: 0.1).

Return Value:

mixed - Return the value returned by the task once it completes.

Throws:

See Also

async()


import

Import (include or require) a file using either a physical path or a virtual path scheme.

You can pass:

  • A normal file path like path/to/project/app/Config/main.php, or
  • A virtual path like app:Config/main.php, which automatically maps to the correct folder.

By default the file is loaded only once (*_once), and, by default, include/include_once is used unless $useRequire is enabled.

Supported Schemes:

  • app: Resolves to root/app/*
  • package: Resolves to root/system/plugins/*
  • view: Resolves to root/resources/Views/*
  • system: Resolves to root/system/*
  • public: Resolves to root/public/*
  • writeable: Resolves to root/writeable/*
  • libraries: Resolves to root/libraries/*
  • resources: Resolves to root/resources/*
  • routes: Resolves to root/routes/*
  • bootstrap: Resolves to root/bootstrap/*
  • bin: Resolves to root/bin/*
  • node: Resolves to root/node/*
function import(
    string $path,
    bool $throw = true,
    bool $once = true,
    bool $useRequire = false,
    array $scope = [],
    bool $promise = false
): mixed

Parameters:

ParameterTypeDescription
$pathstringFile path or scheme-based path to import (e.g., app:Config/file.php).
$throwboolIf true, throw an exception when the file doesn't exist (default: true).
$onceboolIf true, load the file only once using *_once (default: true).
$useRequireboolUse require instead of include (default: false).
$scopearray<string,mixed>Optional associative array of variables to extract into the file scope (keys become variable names).
$promiseboolOptionally return a promise resolver instead of the raw value (default: false).

Return Value:

\Luminova\Interface\PromiseInterface|mixed|null - Return any result of the imported file, a promise result, or null when the file is missing and $throw is false.

Throws:

Examples:

use function Luminova\Funcs\import;

import('app:Config/settings.php');

import('view:profile.php', scope: [
   'id' => 1234
]);
// /resources/Views/profile.php
echo $id; // 1234

import('package:brick/math/src/BigNumber.php');

import('app/Config/settings.php');

import('app:Config/missing.php', throw: false);

import('system:Bootstrap/init.php', useRequire: true);

import('routes:api.php', once: false);

Promise Examples:

use function Luminova\Funcs\import;

import('view:template', promise: true)
    ->then(fn(string $html) => print($html))
    ->catch(fn(\Throwable $e) => logger('error', $e->getMessage()));

import('view:dashboard', scope: ['user' => $user], promise: true)
    ->then(fn(string $html) => print($html));

logger

Log a message to a specified target using the configured PSR-compatible logger.

The target can be a log level (info, error, etc.), an email address, or a remote URL. Delegates to Logger::dispatch() for synchronous or asynchronous handling.

function logger(string $destination, string $message, array $context = []): void

Parameters:

ParameterTypeDescription
$destinationstringThe destination to send the log to (e.g., a log level, email, or URL endpoint).
$messagestringThe message to log.
$contextarrayOptional context data to send with the log.

Supported Log Levels:

  • emergency - System is unusable.
  • alert - Immediate action required.
  • critical - Critical conditions.
  • error - Runtime errors.
  • warning - Exceptional but non-critical conditions.
  • notice - Normal but significant events.
  • info - General operational entries.
  • debug - Detailed debugging info.
  • exception - Captures exception messages.
  • php - Logs native PHP errors.

Throws:

Note:Uses the preferred PSR logger class defined in App\Config\Preference, otherwise falls back to Luminova\Logger\NovaLogger.All non-external log destinations are located in /writeable/log/, one file per log level (e.g., warning.log).


locale

Get or set the application locale.

function locale(?string $locale = null, bool $persist = false): string|bool

Parameters:

ParameterTypeDescription
$localestring|nullThe locale to set, or null to return the current locale.
$persistboolWhether to persist the new locale to the .env file (default: false).

Return Value:

string|bool - Return the current application locale if $locale is null, otherwise return true/false depending on whether the new locale was set successfully.

Note:This function is not the same as setlocale(), a PHP built-in for system locale settings. This function is for application-level locale management.

See Also

Luminova\Runtime::setLocale() for a convenient setlocale() wrapper.


uuid

Generate a UUID string of the specified version.

function uuid(int $version = 4, ?string $namespace = null, ?string $name = null, ?int $time = null): string

Parameters:

ParameterTypeDescription
$versionintVersion of the UUID to generate: 1, 3, 4, 5, or 7 (default: 4).
$namespacestring|nullThe namespace for versions 3 and 5 (e.g., dns, url, oid, x500, or a custom UUID).
$namestring|nullThe name for versions 3 and 5.
$timeint|nullOptional timestamp: 100-nanosecond intervals since UUID epoch for v1, or milliseconds since Unix epoch for v7.

Return Value:

string - Return the generated UUID string.

Throws:

See Also

ulid()


ulid

Generate a ULID (Universally Lexicographically Sortable Identifier).

ULID is composed of a 48-bit timestamp (milliseconds since Unix epoch) and 80-bit cryptographically secure randomness, encoded using Crockford Base32.

function ulid(): string

Return Value:

string - Return a 26-character ULID string.

See Also

uuid()


escape

Escape a string or an array of values for the specified output context.

Supported contexts:

  • html - Escape HTML content.
  • attr - Escape HTML attribute values.
  • js - Escape JavaScript strings.
  • css - Escape CSS values.
  • url - Escape URLs.
  • raw - Return the value without escaping.

When an array is provided, all string values are escaped recursively via array_escape().

function escape(array|string $input, string $context = 'html', string $encoding = 'utf-8'): array|string

Parameters:

ParameterTypeDescription
$inputarray|stringThe string or array to escape.
$contextstringThe default escape context (default: 'html').
$encodingstringThe character encoding to use (default: 'utf-8').

Return Value:

array|string - Return the escaped string or array.

Throws:

Examples:

use function Luminova\Funcs\escape;

echo escape('<script>alert("xss")</script>');
// &lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;

$url = escape('https://example.com/?q=<script>', 'url');

See Also

Input Escaper documentation for more escape contexts.


sanitize

Sanitize user input by removing invalid or unsafe characters.

function sanitize(string $input, string $type = Util::SANITIZE_DEFAULT, ?string $replacer = ''): ?string

Parameters:

ParameterTypeDescription
$inputstringThe input string to be sanitized.
$typestringThe expected data type (e.g., int, email, username).
$replacerstring|nullReplacement for disallowed characters (default: ''). If null, input is validated only and an exception is thrown on failure.

Return Value:

string|null - Return the sanitized string, or null if the input cannot be sanitized.

Throws:

Note:For 'default', HTML tags (including their content) are fully removed.

See Also

strict()


strict

Strictly sanitize input according to the specified type.

Unlike sanitize(), strict() will always throw an exception if the input contains invalid characters instead of replacing them.

function strict(string $input, string $type = Util::SANITIZE_DEFAULT): string

Parameters:

ParameterTypeDescription
$inputstringThe string to validate strictly.
$typestringThe expected data type (default: Util::SANITIZE_DEFAULT).

Return Value:

string - Return the sanitized string.

Throws:

See Also

sanitize()


lang

Translate a message based on the current language context.

Placeholder Pattern:

  • Using index: "Error name {0} and email {1}"
  • Using keys: "Error name {name} and email {email}"
function lang(string $lookup, ?string $default = null, ?string $locale = null, array $placeholders = []): string

Parameters:

ParameterTypeDescription
$lookupstringThe language lookup key (e.g., App.error.foo.bar).
$defaultstring|nullOptional fallback message if not found.
$localestring|nullOptional translation locale. If null, the current application locale is used.
$placeholdersarray<string|int,string|int>Optional placeholder replacements.

Return Value:

string - Return the translated message.

Throws:

Examples:

use function Luminova\Funcs\lang;

echo lang('User.error.all', null, 'en', ['Peter', '[email protected]']);

echo lang('User.error.all', null, 'en', [
    'name'  => 'Peter',
    'email' => '[email protected]'
]);

See Also

Translations - See the documentation for translation methods and usages.


func

Safely call a PHP function with arguments.

This helper:

  • Resolves the function from the global namespace first, then the current namespace.
  • Detects functions disabled via PHP disable_functions.
  • Uses function_exists_cached() to avoid repeated existence checks.
function func(string $function, mixed ...$arguments): mixed

Parameters:

ParameterTypeDescription
$functioncallable-stringName of the function to call.
$argumentsmixedArguments to pass to the function.

Return Value:

mixed - Return the result of the executed function.

Throws:

Example:

use function Luminova\Funcs\func;

$limit = func('set_time_limit', 300);

shared

Runtime shared memory store for application-wide values.

Stores and retrieves values in shared memory that are not persisted across requests. Useful for storing configuration, state, or other data that needs to be accessed globally within the current execution.

function shared(string $key, mixed $value = null, mixed $default = null): mixed

Parameters:

ParameterTypeDescription
$keystringThe key to identify the value.
$valuemixedThe value to store (optional).
$defaultmixedThe default value returned if the key is not found (default: null).

Return Value:

mixed - Return the value associated with the key when getting, or the stored value when setting.


cache

Get a cache instance based on the specified driver.

function cache(string $driver = 'filecache', ?string $storage = null, ?string $persistentId = null): FileCache|RedisCache|MemoryCache

Parameters:

ParameterTypeDescription
$driverstringThe cache driver to use: filecache, redis, or memcached (default: filecache).
$storagestring|nullThe name of the cache storage. If null, setStorage() must be called later (default: null).
$persistentIdstring|nullOptional persistent ID (Memcached) or storage subfolder (filesystem cache).

Return Value:

Luminova\Cache\FileCache|Luminova\Cache\RedisCache|Luminova\Cache\MemoryCache - Return an instance of the cache class matching the specified driver.

Throws:

See Also

App\Kernel::getCacheProvider() for more details on cache provider initialization.


validate

Validate user input fields, or get a validation instance.

Regardless of whether $inputs, $rules, or $messages are provided, validate() is invoked on the resolved instance before it is returned.

function validate(?array $inputs = null, ?array $rules = null, array $messages = []): Luminova\Interface\InputValidationInterface

Parameters:

ParameterTypeDescription
$inputsarray|nullInput fields to validate (e.g., $_POST, $_GET, or $this->request->getBody()).
$rulesarray|nullValidation filter rules to apply on each input field.
$messagesarrayValidation error messages to apply per filter/field.

Return Value:

Luminova\Interface\InputValidationInterface - Return the validation instance.

Example:

use function Luminova\Funcs\validate;

$rules = [
   'name' => 'require|alphanumeric|max(50)',
   'email' => 'require|email'
];

$validation = validate($inputs, $rules);

if ($validation->isPassed()) {
   echo 'Success';
} else {
   echo 'Error: ' . $validation->getError();
   var_export($validation->getErrors());
}

See Also

Input Validations documentation for more usages.


configs

Load a configuration array from the app/Config/ directory.

The function loads a config file once, stores it in shared memory, and returns the cached result on later calls. Use this only for configuration files that return an array.

function configs(string $filename, ?array $default = null): ?array

Parameters:

ParameterTypeDescription
$filenamestringThe configuration name without extension (e.g., Storage).
$defaultarray|nullThe value returned when the file does not exist (default: null).

Return Value:

array|null - Return the configuration array or the default value.

Throws:

Example:

// app/Config/SomeConfig.php
return ['option' => ['foo', 'bar'], 'status' => 1];
use function Luminova\Funcs\configs;

$config = configs('SomeConfig');

session

Retrieve a session value or the session instance.

When $key is provided (non-empty), the value associated with the key is returned. When $key is null or empty, the session instance itself is returned.

function session(
   ?string $key = null,
   bool $shared = true,
   ?Luminova\Interface\SessionManagerInterface $manager = null
): mixed

Parameters:

ParameterTypeDescription
$keystring|nullSession key to retrieve, or null to return the session instance.
$sharedboolWhether to reuse the shared session instance (default: true).
$managerSessionManagerInterface|nullSession manager to use, or null to use the default manager.

Return Value:

Luminova\Sessions\Session|mixed - Return the session value when $key is provided, otherwise the session instance.

See Also

Session Manager - See the documentation for session methods.


Create and return a cookie instance.

function cookie(string $name, string $value = '', array $options = [], bool $shared = false): Luminova\Cookies\Cookie

Parameters:

ParameterTypeDescription
$namestringThe name of the cookie.
$valuestringThe value of the cookie.
$optionsarrayOptions to be passed to the cookie.
$sharedboolUse a shared instance (default: false).

Return Value:

Luminova\Cookies\Cookie - Return the cookie instance.

See Also

Client Cookie Manager - See the documentation for client-side cookie methods.


factory

Return a shared instance of a class in the factory, or the factory instance itself if $context is null.

function factory(?string $context = null, bool $shared = true, mixed ...$arguments): ?object

Parameters:

ParameterTypeDescription
$contextstring|nullThe factory context name, e.g., session (default: null).
$sharedboolWhether to return a shared instance (default: true).
$argumentsmixedOptional class constructor initialization arguments.

Return Value:

class-object<\T>|Luminova\Foundation\Module\Factory|null - Return the instance of the factory, the resolved class instance, or null.

Throws:

Available Factory Context Names

  • task - Returns instance of Luminova\Time\Task
  • session - Returns instance of Luminova\Sessions\Session
  • cookie - Returns instance of Luminova\Cookies\Cookie
  • functions - Returns instance of Luminova\Foundation\Core\Functions
  • modules - Returns instance of Luminova\Library\Modules
  • language - Returns instance of Luminova\Components\Languages\Translator
  • escaper - Returns instance of Luminova\Security\Escaper
  • network - Returns instance of Luminova\Http\Network
  • filesystem - Returns instance of Luminova\Storage\Filesystem
  • validate - Returns instance of Luminova\Security\Validation
  • response - Returns instance of Luminova\Template\Response
  • request - Returns instance of Luminova\Http\Request
  • service - Returns instance of Luminova\Foundation\Module\Service
  • notification - Returns instance of Luminova\Notifications\Firebase\Notification
  • caller - Returns instance of Luminova\Foundation\Module\Caller

Example

use function Luminova\Funcs\factory;

$session = factory('session', false, new SessionManager());

See Also

Application Factory - See the documentation for factory methods and usages.


service

Return a shared instance of a class registered in your service bootstrap method, or the service instance itself if $service is null.

function service(
   ?string $service = null,
   bool $shared = true,
   bool $serialize = false,
   mixed ...$arguments
): ?object

Parameters:

ParameterTypeDescription
$serviceclass-string<\T>|string|nullThe service class name or alias.
$sharedboolWhether to return a shared instance of the class (default: true).
$serializeboolWhether to serialize and store the class object as cache (default: false).
$argumentsmixedAdditional parameters passed to the class constructor.

Return Value:

class-object<\T>|Luminova\Foundation\Module\Service|null - Return the service class instance, or the service resolver instance.

Throws:

See Also

Application Service - See the documentation for service methods and usages.


remove_service

Delete a service or clear all cached services.

function remove_service(?string $service = null): bool

Parameters:

ParameterTypeDescription
$serviceclass-string<\T>|string|nullThe class name or alias to delete and clear from cache.

Return Value:

bool - Return true if the service was removed or cleared, false otherwise.

If null is passed, all cached and serialized services are cleared.


import_lib

Import a custom library from the libraries/libs directory.

function import_lib(string $library, bool $throw = false): bool

Parameters:

ParameterTypeDescription
$librarystringThe library path or name (e.g., Foo/Bar/Baz or Foo/Bar/Baz.php).
$throwboolIf true, throws an exception when the library file is not found (default: false).

Return Value:

bool - Return true if the library was successfully loaded, false otherwise.

Throws:

Example:

use function Luminova\Funcs\import_lib;

import_lib('Foo/Bar/Baz');
import_lib('Foo/Bar/Baz.php');

finish_response

Finish the HTTP response immediately while allowing PHP to continue running.

Attempts to terminate the client response as early as possible while letting PHP execute remaining logic (logging, cache writes, async work).

function finish_response(bool $closeSession = true, bool $ignoreUserAbort = true): bool

Parameters:

ParameterTypeDescription
$closeSessionboolWhether to close the active session before finishing the response (default: true).
$ignoreUserAbortboolWhether to ignore client disconnects, non-CLI only (default: true).

Return Value:

bool - Return true if a response flush attempt was made.

Note:This is best-effort only. Web servers and proxies may still terminate execution. Do not rely on this for critical work; use queues or workers instead. Uses fastcgi_finish_request() or litespeed_finish_request() when available, otherwise falls back to flushing output buffers.


base_url

Get the start URL with an optional route path.

Automatically builds a full or relative URL depending on environment and the $relative flag. Includes host and port for development servers when needed.

function base_url(?string $route = null, bool $relative = false): string

Parameters:

ParameterTypeDescription
$routestring|nullOptional route URI path to append to the start URL (default: null).
$relativeboolIf true, returns a relative URL instead of absolute (default: false).

Return Value:

string - Return the constructed URL (absolute or relative), optionally pointing to a route or path.

Examples:

use function Luminova\Funcs\base_url;

echo base_url('about', true);
// On Development: /my-project-path/public/about
// In Production:  /about

absolute_url

Convert an application-relative path to an absolute URL.

function absolute_url(string $path): string

Parameters:

ParameterTypeDescription
$pathstringThe path to create an absolute URL from.

Return Value:

string - Return the absolute URL of the specified path.

See Also

base_url()


display_path

Convert an absolute file path to a safe display path.

Removes leading server-specific path segments and returns a cleaner path starting from the first known system directory.

function display_path(string $path): string

Parameters:

ParameterTypeDescription
$pathstringThe full file path to convert.

Return Value:

string - Return the cleaned path safe for display.

Example:

use function Luminova\Funcs\display_path;

display_path('/var/www/html/example.com/writeable/storage/uploads/file.jpg');
// Returns: 'writeable/storage/uploads/file.jpg'

Useful for error messages, logs, and debug output where full server paths should not be exposed.


http_status_header

Set the HTTP response status code and send the corresponding status message header.

A status code of 0 is treated as the default 200 OK response. Also updates $_SERVER['REDIRECT_STATUS'] for compatibility.

function http_status_header(int $status = 200): bool

Parameters:

ParameterTypeDescription
$statusintHTTP response status code (default: 200).

Return Value:

bool - Return true if the status code was set successfully, false if invalid.


is_platform

Determine whether the application is running on a specific platform.

function is_platform(string $os): bool

Parameters:

ParameterTypeDescription
$osstringPlatform name to check, e.g., windows, linux, mac, aws, azure.

Return Value:

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

Examples:

use function Luminova\Funcs\is_platform;

is_platform('windows');
is_platform('linux');
is_platform('aws');

is_command

Determine whether the application is running in CLI mode.

function is_command(): bool

Return Value:

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


is_blob

Determine whether the given value is a blob (stream resource).

function is_blob(mixed $value): bool

Parameters:

ParameterTypeDescription
$valuemixedThe value to check.

Return Value:

bool - Return true if the value is a stream resource, false otherwise.


is_tor

Check whether the given IP address is a Tor exit node.

function is_tor(?string $ip = null, int $expiration = 2592000): bool

Parameters:

ParameterTypeDescription
$ipstring|nullThe IP address to check, or null to use the current IP address.
$expirationintExpiration time (seconds) for cached Tor exit node data (default: 2592000, 30 days).

Return Value:

bool - Return true if the IP address is a Tor exit node, false otherwise.

Throws:


is_utf8

Check if a given string is valid UTF-8.

function is_utf8(string $input): bool

Parameters:

ParameterTypeDescription
$inputstringThe string to check for UTF-8 encoding.

Return Value:

bool - Return true if the string is UTF-8 encoded, false otherwise.


is_empty

Check whether any given values are considered empty.

Unlike PHP's native empty(), this function treats 0 and '0' as non-empty values, and does not treat negative numbers as empty.

Considered empty:

  • null
  • Empty strings (after trimming)
  • Empty arrays
  • Empty objects (no public properties)
  • Empty Countable objects
function is_empty(mixed ...$values): bool

Parameters:

ParameterTypeDescription
$valuesmixedOne or more values to evaluate.

Return Value:

bool - Return true if any of the values are considered empty, false otherwise. Calling with no arguments returns true.

Example:

use function Luminova\Funcs\is_empty;

is_empty(0);              // false
is_empty('0');             // false
is_empty([1]);             // false
is_empty(-3);              // false
is_empty(null);            // true
is_empty('');              // true
is_empty('   ');           // true
is_empty([]);              // true
is_empty((object)[]);      // true

Note:If you need PHP's native emptiness semantics instead, use empty().


is_nested

Determine whether an array is nested (contains arrays as values).

function is_nested(array $array, bool $recursive = false, bool $strict = false): bool

Parameters:

ParameterTypeDescription
$arrayarrayThe array to check.
$recursiveboolWhether to check all levels deeply (default: false).
$strictboolWhether to require all values to be arrays (default: false).

Return Value:

bool - Return true if a nested array is found, false otherwise.

Examples:

use function Luminova\Funcs\is_nested;

is_nested([1, 2, 3]);                       // false
is_nested([1, [2], 3]);                     // true
is_nested([1, [2], 3], strict: true);       // false
is_nested([[1], [2, [3]]], true);           // true

Note: An empty array is not considered nested and will return false.


is_associative

Check if an array is associative (has non-integer or non-sequential keys).

function is_associative(array $array): bool

Parameters:

ParameterTypeDescription
$arrayarrayThe array to check.

Return Value:

bool - Return true if associative, false if indexed or empty.

Example:

use function Luminova\Funcs\is_associative;

is_associative(['a' => 1, 'b' => 2]); // true
is_associative([0 => 'a', 1 => 'b']); // false
is_associative([]);                   // false

is_serialized

Determine whether a value is a serialized PHP string.

When $testOnly is true, a lightweight pattern check is performed without calling unserialize(). When $testOnly is false, the value is validated by actually calling unserialize() with controlled class handling.

function is_serialized(mixed $value, bool $testOnly = false, bool $allowClass = false): bool

Parameters:

ParameterTypeDescription
$valuemixedThe value to inspect.
$testOnlyboolWhether to check the format only, without unserializing (default: false).
$allowClassboolWhether object instantiation is allowed during unserialization (default: false).

Return Value:

bool - Return true if the value appears to be, or is, a serialized PHP string.


is_list

Check if a string is a valid Luminova listify-formatted string.

function is_list(string $input): bool

Parameters:

ParameterTypeDescription
$inputstringThe string to validate.

Return Value:

bool - Return true if the string is a valid list format, false otherwise.


ip_address

Get the client's IP address or detailed IP information.

function ip_address(bool $ipInfo = false, array $metadata = []): string|object|null

Parameters:

ParameterTypeDescription
$ipInfoboolIf true, returns detailed IP information instead of just the IP (default: false).
$metadataarrayOptional metadata to include with the IP information lookup.

Return Value:

string|object|null - Return the client IP as a string, IP information as an object, or null if no data is available.


which_php

Get the PHP script executable path.

function which_php(?string $version = null): ?string

Parameters:

ParameterTypeDescription
$versionstring|nullOptional PHP version to check for (e.g., '8.0.0').

Return Value:

string|null - Return the PHP executable path, or null.


system_path

Resolve a system or application path.

Available Paths:

  • app - Application root directory.
  • system - Luminova Framework and third-party plugins root directory.
  • plugins - Third-party plugins root directory.
  • library - Custom libraries root directory.
  • controllers - Application controllers directory.
  • writable - Application writable directory.
  • logs - Application logs directory.
  • caches - Application cache directory.
  • public - Application public directory (front controller).
  • assets - Application public assets directory.
  • views - Application template views directory.
  • routes - Application method-based routes directory.
  • languages - Application language pack directory.
  • service - Application cached services directory.
function system_path(string $name): string

Parameters:

ParameterTypeDescription
$namestringThe path name to resolve.

Return Value:

string - Return the full directory path, normalized for the current OS.

See Also

File Manager documentation for more usages.


make_dir

Create a directory if it does not already exist.

Supports recursive creation of nested directories.

function make_dir(string $path, ?int $permissions = null, bool $recursive = true): bool

Parameters:

ParameterTypeDescription
$pathstringDirectory path to create.
$permissionsint|nullUnix permission mode. If null, uses App\Config\Security::$dirPermissions.
$recursiveboolWhether to create parent directories if they do not exist (default: true).

Return Value:

bool - Return true if the directory exists or was created successfully.

Throws:


temp_dir

Create a writable temporary directory.

Attempts to create a temporary directory using an available writable storage location. Unless $fromLocal is enabled, the system temporary directory is preferred over the application writable temp directory. If no prefix is provided and the system temporary directory is used, a sanitized application name is used automatically as the directory prefix.

function temp_dir(?string $prefix = null, bool $fromLocal = false): ?string

Parameters:

ParameterTypeDescription
$prefixstring|nullOptional subdirectory name to create inside the selected temporary storage path.
$fromLocalboolWhether to use only the application writable temp directory instead of the system temporary directory.

Return Value:

string|null - Return the created temporary directory path, or null if no writable storage path is available or creation fails.

See Also

get_temp_file()


get_temp_file

Create a writable temporary file.

Creates a temporary file inside the temporary directory resolved via temp_dir(). The file name can be customized using a filename prefix and extension.

function get_temp_file(?string $filename = null, ?string $extension = null, bool $fromLocal = false): ?string

Parameters:

ParameterTypeDescription
$filenamestring|nullOptional filename prefix. When given without $extension, the extension is derived from $filename.
$extensionstring|nullOptional file extension without a leading dot.
$fromLocalboolWhether to use only the application writable temp directory instead of the system temporary directory.

Return Value:

string|null - Return the created temporary file path, or null if the temporary directory or file cannot be created.

See Also

temp_dir()


get_class_name

Get the class basename from a namespace or class object.

function get_class_name(string|object $from, bool $validate = false): string

Parameters:

ParameterTypeDescription
$fromstring|objectThe namespace or class object.
$validateboolWhether to validate that the class is already loaded (default: false).

Return Value:

string - Return the class basename.

Note: This function is not the same as PHP's get_class() — it returns the base name of a class, not the fully qualified name.


get_mime

Detect the MIME type of a file or raw data.

If the input string is a path to an existing file, \finfo->file() is used; otherwise the input is treated as raw binary and \finfo->buffer() is used. An empty input string returns 'text/plain'.

function get_mime(string $input, ?string $magicDatabase = null, ?string $customDatabase = null): string|bool

Parameters:

ParameterTypeDescription
$inputstringFile path or raw binary string to extract the MIME type from.
$magicDatabasestring|nullOptional path to a custom magic database (e.g., \path\custom.mgc).
$customDatabasestring|nullOptional path to a custom mime database file (e.g., \path\custom.json).

Return Value:

string|bool - Return the detected MIME type, or false if detection fails.

Throws:


get_content

Read file contents with optional offset, length limit, and throttling.

A lightweight wrapper around Filesystem::contents(), providing a drop-in alternative to file_get_contents() with finer control.

function get_content(
   string $filename,
   int $length = 0,
   int $offset = 0,
   bool $useInclude = false,
   mixed $context = null,
   int $delay = 0
): string|bool

Parameters:

ParameterTypeDescription
$filenamestringThe path to the file to read.
$lengthintMaximum number of bytes to read, 0 reads in 8192-byte chunks (default: 0).
$offsetintThe starting position in the file to begin reading from (default: 0).
$useIncludeboolIf true, the file will be searched in the include path (default: false).
$contextresource|nullOptional stream context created with stream_context_create().
$delayintDelay in microseconds between chunk reads, useful for throttling (default: 0).

Return Value:

string|bool - Return the contents of the file as a string, or false on failure.

Throws:


write_content

Write or append data to a file.

A lightweight wrapper around Filesystem::write(), intended as a safer and more flexible alternative to file_put_contents().

function write_content(string $filename, mixed $content, int $flags = 0, mixed $context = null): bool

Parameters:

ParameterTypeDescription
$filenamestringPath to the file to write to.
$contentstring|resourceData to write, either as a string or a stream resource.
$flagsintBitwise flags, e.g., FILE_APPEND \| LOCK_EX (default: 0).
$contextresource|nullOptional stream context created with stream_context_create().

Return Value:

bool - Return true on success, false on failure.

Throws:


status_code

Convert a callback/controller result into a status code.

Given the raw response from a callback, controller, or command handler, this function derives a status value:

  • If $result is exactly false, or is an integer equal to 1, the result is treated as a failure: returns 1 when $returnInt is true, or false otherwise.
  • Otherwise the result is treated as a success: returns (int) $result when $returnInt is true (e.g., null/void casts to 0, true casts to 1), or true otherwise.
function status_code(mixed $result = null, bool $returnInt = true): bool|int

Parameters:

ParameterTypeDescription
$resultmixedThe response from the callback function, controller, or command.
$returnIntboolWhether to return an int or bool (default: int).

Return Value:

bool|int - Return the status response as a boolean or integer value.


array_escape

Recursively escape all string values in an array.

If an array key matches one of the supported context names (html, attr, js, css, url, raw), that context is applied to the corresponding value. Otherwise, the specified default context is used. Nested arrays are processed recursively.

function array_escape(array $input, string $context = 'html', string $encoding = 'utf-8'): array

Parameters:

ParameterTypeDescription
$inputarray<string|int,mixed>The array to escape.
$contextstringThe default escape context (default: 'html').
$encodingstringThe character encoding to use (default: 'utf-8').

Return Value:

array<string|int,mixed> - Return the escaped array.

Throws:

Example:

use function Luminova\Funcs\array_escape;

$escaped = array_escape([
    'html' => '<b>Bold</b>',
    'js'   => 'alert("xss")',
    'url'  => 'https://example.com/?q=<script>'
]);

array_duplicates

Return duplicate values from an array.

function array_duplicates(array $array, bool $withCounts = false, bool $preserveKeys = false): array

Parameters:

ParameterTypeDescription
$arrayarrayInput array.
$withCountsboolWhether to return occurrence counts instead of values (default: false).
$preserveKeysboolWhether to preserve the original array keys of duplicate entries (default: false).

Return Value:

array - Return the duplicate values, an array of value => count, or a key-preserving filtered array, depending on the flags.


object_column

Extract values from a specific column of an object list.

Works like array_column() but for an object. If $property is null, the entire item is returned.

function object_column(object $from, string|int|null $property = null, string|int|null $index = null): object

Parameters:

ParameterTypeDescription
$fromobjectThe input collection (an object of objects/arrays).
$propertystring|int|nullThe key or property to extract from each item (default: null).
$indexstring|int|nullOptional key/property to use as the array index for returned values.

Return Value:

object - Return an object of extracted values. If $index is provided, its resolved value is used as the key.

Example:

use function Luminova\Funcs\object_column;

$objects = (object) [
   (object)['id' => 1, 'name' => 'Foo'],
   (object)['id' => 2, 'name' => 'Bar'],
];

object_column($objects, 'name');       // (object)['Foo', 'Bar']
object_column($objects, 'name', 'id'); // (object)[1 => 'Foo', 2 => 'Bar']

get_column

Extract values from a specific column of an array or object list.

Uses PHP's array_column() or Luminova's object_column() depending on input type. If $property is null, the entire item is returned.

function get_column(array|object $from, string|int|null $property, string|int|null $index = null): array|object

Parameters:

ParameterTypeDescription
$fromarray|objectThe input collection (array of arrays/objects, or an object).
$propertystring|int|nullThe key or property to extract from each item.
$indexstring|int|nullOptional key/property to use as the array index for returned values.

Return Value:

array|object - Return an array of extracted values (for array input) or an object (for object input). If $index is provided, it's used as the keys.

Examples:

use function Luminova\Funcs\get_column;

$arrays = [
   ['id' => 1, 'name' => 'Alice'],
   ['id' => 2, 'name' => 'Bob']
];

get_column($arrays, 'name');       // ['Alice', 'Bob']
get_column($arrays, 'name', 'id'); // [1 => 'Alice', 2 => 'Bob']

See Also

object_column()


to_array

Recursively convert an object, string-list, or mixed value to an array.

function to_array(mixed $input): array

Parameters:

ParameterTypeDescription
$inputmixedThe input to convert (object, array, string-list, or scalar).

Return Value:

array - Return the array representation.

Example:

use function Luminova\Funcs\to_array;

to_array((object)['a' => 1, 'b' => (object)['c' => 2]]);
// ['a' => 1, 'b' => ['c' => 2]]

to_object

Convert an array or a listify-delimited string to a JSON object.

function to_object(array|string $input): object|bool

Parameters:

ParameterTypeDescription
$inputarray|stringInput array, or a listify string (e.g., foo=bar,bar=2,baz=[1;2;3]).

Return Value:

object|bool - Return the JSON object if successful, false on failure.

Example:

use function Luminova\Funcs\to_object;

to_object(['a' => 1, 'b' => 2]);
// (object)['a' => 1, 'b' => 2]

to_object('foo=bar,bar=2,baz=[1;2;3]');
// (object)['foo' => 'bar', 'bar' => 2, 'baz' => [1, 2, 3]]

list_to_array

Convert a valid string list to an array.

function list_to_array(string $list): array|bool

Parameters:

ParameterTypeDescription
$liststringThe string list to convert.

Return Value:

array|bool - Return the parsed array, or false on failure.

Example:

use function Luminova\Funcs\list_to_array;

list_to_array('a,b,c');       // ['a', 'b', 'c']
list_to_array('"a","b","c"'); // ['a', 'b', 'c']

list_in_array

Check if all values in a string list exist in a given array.

function list_in_array(string $list, array $array = []): bool

Parameters:

ParameterTypeDescription
$liststringThe string list to check.
$arrayarrayThe array to search for listify values in.

Return Value:

bool - Return true if all list items exist in the array, false otherwise.

use function Luminova\Funcs\list_in_array;

$list = 'Foo, Bar, Baz';

list_in_array($list, ['Foo', 'Bra']);          // false
list_in_array($list, ['Foo', 'Baz', 'Bar']);   // true

array_min

Get the item with the lowest value for a given key, or the minimum value from a flat numeric list.

If no key is provided, non-numeric values are filtered out and the minimum of the remaining values is returned.

function array_min(array $items, ?string $key = null): mixed

Parameters:

ParameterTypeDescription
$itemsarrayList of values, or an array of associative arrays.
$keystring|nullKey used for comparison in structured arrays.

Return Value:

mixed - Return the lowest item/value, or null if no valid comparison can be made.

Example:

use function Luminova\Funcs\array_min;

$data = [
    ['id' => 1, 'value' => 10],
    ['id' => 2, 'value' => 5],
    ['id' => 3, 'value' => 15],
];

array_min($data, 'value'); // ['id' => 2, 'value' => 5]

See Also

array_max()


array_max

Get the item with the highest value for a given key, or the maximum value from a flat numeric list.

function array_max(array $items, ?string $key = null): mixed

Parameters:

ParameterTypeDescription
$itemsarrayList of values, or an array of associative arrays.
$keystring|nullKey used for comparison in structured arrays.

Return Value:

mixed - Return the highest item/value, or null if no valid comparison can be made.

Example:

use function Luminova\Funcs\array_max;

$data = [
    ['id' => 1, 'value' => 10],
    ['id' => 2, 'value' => 5],
    ['id' => 3, 'value' => 15],
];

array_max($data, 'value'); // ['id' => 3, 'value' => 15]

See Also

array_min()


array_merge_recursive_distinct

Merge arrays recursively, ensuring unique values in nested arrays.

Unlike traditional recursive merging, duplicate keys are replaced rather than appended. When two arrays contain the same key, the value from the later array overwrites the earlier one.

function array_merge_recursive_distinct(array $array, array ...$arrays): array

Parameters:

ParameterTypeDescription
$arrayarrayThe array to merge into.
$arraysarrayOne or more arrays to merge.

Return Value:

array - Return the merged array with unique values.

Example:

use function Luminova\Funcs\array_merge_recursive_distinct;

$array1 = ['a' => 1, 'b' => ['x' => 10, 'y' => 20]];
$array2 = ['b' => ['y' => 30, 'z' => 40], 'c' => 3];

array_merge_recursive_distinct($array1, $array2);
// ['a' => 1, 'b' => ['x' => 10, 'y' => 30, 'z' => 40], 'c' => 3]

array_merge_recursive_replace

Merge multiple arrays recursively.

When two arrays share the same key, values from the later array overwrite those from earlier ones. Numeric keys are appended only if the value doesn't already exist in the array.

function array_merge_recursive_replace(array ...$array): array

Parameters:

ParameterTypeDescription
$arrayarrayThe arrays to merge.

Return Value:

array - Return the merged result array.

Example:

use function Luminova\Funcs\array_merge_recursive_replace;

$array1 = ['a' => 1, 'b' => ['x' => 10, 'y' => 20]];
$array2 = ['b' => ['y' => 30, 'z' => 40], 'c' => 3];

array_merge_recursive_replace($array1, $array2);
// ['a' => 1, 'b' => ['x' => 10, 'y' => 30, 'z' => 40], 'c' => 3]

array_extend_default

Merge two arrays, treating the first as default configuration and the second as new or override values.

Recursively merges nested arrays for keys that exist in both, leaving default values untouched when no corresponding value is found in $new.

function array_extend_default(array $default, array $new): array

Parameters:

ParameterTypeDescription
$defaultarrayThe default options array.
$newarrayThe new options array to merge.

Return Value:

array - Return the merged options array with defaults preserved.

Example:

use function Luminova\Funcs\array_extend_default;

$default = ['a' => 1, 'b' => 2, 'c' => 3];
$new = ['b' => 20, 'd' => 4];

array_extend_default($default, $new);
// ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4]

array_merge_result

Merge a response into the provided results variable, optionally preserving the nested structure of arrays.

function array_merge_result(mixed &$results, mixed $response, bool $preserveNested = true): void

Parameters:

ParameterTypeDescription
$resultsmixed(by reference) The results variable to merge or append the response into.
$responsemixedThe response to merge with results. Can be an array, string, or other type.
$preserveNestedboolWhether to preserve the nested structure of arrays when merging (default: true).

Return Value:

void

Example:

use function Luminova\Funcs\array_merge_result;

$results = ['a' => 1, 'b' => 2];
$response = ['b' => 3, 'c' => 4];

array_merge_result($results, $response, false);
// ['a' => 1, 'b' => 3, 'c' => 4]

string_length

Calculate the length of a string based on the given character set.

function string_length(string $content, ?string $charset = null): int

Parameters:

ParameterTypeDescription
$contentstringThe content to calculate the length for.
$charsetstring|nullThe character set of the content (default: app.mb.encoding env value, or 'utf-8').

Return Value:

int - Return the string length.


kebab_case

Convert a string to kebab-case format.

Replaces all non-letter and non-digit characters with hyphens. Optionally converts the entire string to lowercase.

function kebab_case(string $input, bool $toLower = true): string

Parameters:

ParameterTypeDescription
$inputstringThe input string to convert.
$toLowerboolWhether to convert the result to lowercase (default: true).

Return Value:

string - Return the kebab-cased version of the input string.

Example:

use function Luminova\Funcs\kebab_case;

echo kebab_case('hello world'); // hello-world
echo kebab_case('HelLo-World'); // hello-world
echo kebab_case('HelLo worlD', false); // HelLo-worlD

camel_case

Convert a string to camelCase.

function camel_case(string $input): string

Parameters:

ParameterTypeDescription
$inputstringThe string to convert.

Return Value:

string - Return the string converted to camelCase.

Example:

use function Luminova\Funcs\camel_case;

echo camel_case('hello world');  // helloWorld
echo camel_case('hello-world');  // helloWorld

pascal_case

Convert a string to PascalCase format.

Replaces spaces, underscores, and hyphens with word boundaries, capitalizes each word, and removes all delimiters.

function pascal_case(string $input): string

Parameters:

ParameterTypeDescription
$inputstringThe input string to convert.

Return Value:

string - Return the PascalCase version of the input string.

Example:

use function Luminova\Funcs\pascal_case;

echo pascal_case('hello world'); // HelloWorld
echo pascal_case('hello-world'); // HelloWorld

snake_case

Convert a string to snake_case format.

Converts mixed-case or delimited text into lowercase words separated by underscores. Handles transitions from uppercase to lowercase, as well as spaces, hyphens, dots, and apostrophes.

function snake_case(string $input): string

Parameters:

ParameterTypeDescription
$inputstringThe input string to convert.

Return Value:

string - Return the snake_case version of the input string.

Examples:

use function Luminova\Funcs\snake_case;

echo snake_case('HelloWorld');       // hello_world
echo snake_case('HTMLParser');       // html_parser
echo snake_case('getHTTPResponse');  // get_http_response
echo snake_case('hello world');      // hello_world
echo snake_case('hello-world');      // hello_world

uppercase_words

Capitalize the first letter of each word in a string.

Preserves underscores, hyphens, and spaces as delimiters, and capitalizes the letter that follows each one.

function uppercase_words(string $input): string

Parameters:

ParameterTypeDescription
$inputstringThe input string to convert.

Return Value:

string - Return the input string with the first character of each word capitalized.

Usage Example:

use function Luminova\Funcs\uppercase_words;

echo uppercase_words('foo-bar_baz');
// Foo-Bar_Baz

More Patterns:

$strings = [
   'foo-bar_baz',
   'hello-world_this_is_a_test',
   'example',
   '_leading_and_trailing_',
];

$results = array_map('Luminova\Funcs\uppercase_words', $strings);
echo implode("\n", $results);

Output:

Foo-Bar_Baz
Hello-World_This_Is_A_Test
Example
_Leading_And_Trailing_

has_uppercase

Check if a given string contains an uppercase letter.

function has_uppercase(string $string): bool

Parameters:

ParameterTypeDescription
$stringstringThe string to check.

Return Value:

bool - Return true if the string has an uppercase character, false otherwise.


str_matching_delimiter

Find the matching closing delimiter position in a string.

Scans a string from the given offset and returns the position of the matching closing character for the first opening character found. Nested blocks are handled correctly using depth tracking.

function str_matching_delimiter(string $input, string $start, string $end, int $offset = 0): int|bool

Parameters:

ParameterTypeDescription
$inputstringThe string to scan.
$startstringThe opening delimiter to match (single character).
$endstringThe closing delimiter to match (single character).
$offsetintPosition to start searching from (default: 0).

Return Value:

int|bool - Return the matching closing delimiter position, or false if not found.

Throws:

Examples:

use function Luminova\Funcs\str_matching_delimiter;

$sql = 'WITH users AS (SELECT * FROM users WHERE id IN (1,2,3))';
$end = str_matching_delimiter($sql, '(', ')');

$text = '{ "user": { "name": "John" } }';
$end = str_matching_delimiter($text, '{', '}');

text2html

Convert text characters in a string to HTML entities.

function text2html(?string $text): string

Parameters:

ParameterTypeDescription
$textstring|nullA string containing the text to be processed.

Return Value:

string - Return the processed text with HTML entities, or an empty string for null/empty/whitespace-only input.


nl2html

Convert newlines and related line-break tokens in a string to HTML-safe entity sequences.

Converts \n, \r\n, the literal tokens [br/] and <br/>, and tabs into their corresponding HTML entity sequences. Useful for displaying text inside an HTML <textarea> while preserving the original line breaks.

function nl2html(?string $text): string

Parameters:

ParameterTypeDescription
$textstring|nullA string containing the text to be processed.

Return Value:

string - Return the processed text, or an empty string for null/whitespace-only input.


class_loaded

Determine whether a class has already been loaded.

Unlike class_exists(), this function does not trigger the autoloader.

function class_loaded(string $class): bool

Parameters:

ParameterTypeDescription
$classstringFully qualified class name.

Return Value:

bool - Return true if the class is already loaded, otherwise false.


class_exists_cached

Check if a class exists and cache the result for improved performance.

function class_exists_cached(string $class, bool $autoload = true): bool

Parameters:

ParameterTypeDescription
$classstringThe name of the class to check.
$autoloadboolWhether to check for class existence with autoload (default: true).

Return Value:

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


function_exists_cached

Check if a function exists and cache the result to avoid repeated checks.

function function_exists_cached(string $function): bool

Parameters:

ParameterTypeDescription
$functionstringThe name of the function to check.

Return Value:

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