PHP Luminova: Global Namespaced Helper Functions
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()orsetenv(), see Global Functions & Polyfills.
Usage
Import Functions (Recommended)
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 foundNotes:
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): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$path | string|null | Optional subdirectory relative to the application root (e.g., writeable/logs). |
$filename | string|null | Optional filename to append after the path (e.g., debug.log). |
$normalize | bool | When 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 = trueonly 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.logapp
Get the application instance.
Returns the current shared application instance or creates a new one.
- When
$sharedis true (default), the shared application instance is returned. - When
$sharedis false, a new application instance is created via the kernel. - If
$newis provided, it replaces the current shared application instance.
function app(bool $shared = true, ?Application $new = null): Luminova\Foundation\Core\ApplicationParameters:
| Parameter | Type | Description |
|---|---|---|
$shared | bool | Whether to return the shared instance (default: true). |
$new | Luminova\Foundation\Core\Application|null | Optional 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): objectParameters:
| Parameter | Type | Description |
|---|---|---|
$service | string|null | The service identifier, or null to return the kernel instance. |
$shared | bool | Whether to reuse a shared instance when supported (default: true). |
$arguments | mixed | Arguments 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): RequestInterfaceParameters:
| Parameter | Type | Description |
|---|---|---|
$shared | bool | Whether 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\ResponseParameters:
| Parameter | Type | Description |
|---|---|---|
$status | int | HTTP status code (default: 200 OK). |
$headers | array<string,mixed>|null | Optional response headers (default: null). |
$shared | bool | Whether 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): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$userAgent | string|null | Optional user agent string to analyze (default: current UA). |
$return | string | Return type: 'array', 'object', or 'instance' (default: 'object'). |
$shared | bool | If 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
browscapINI setting is configured and$returnis not'instance', this function usesget_browser()first, falling back toUserAgent::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
Viewinstance so you can chain rendering or return template content.
function view(string $template, string $type = View::HTML): Luminova\Template\ViewParameters:
| Parameter | Type | Description |
|---|---|---|
$template | string | Template file name or identifier. |
$type | string | Template 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/*.phpExamples:
use function Luminova\Funcs\view;
return view('index')
->render(['name' => 'Peter'], 200);
return view('index')
->contents(['name' => 'Peter'], 200);Note:Use the
viewglobal 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): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$uri | string|null | The route, view name, or file path (default: null). |
$absolute | bool | Whether to return an absolute URL using APP_URL (default: false). |
$depth | int|null | Directory 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
Generate a URL to a file in the public assets/ directory.
function asset(?string $filename = null, bool $absolute = false, ?int $depth = null): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$filename | string|null | The asset path or filename (e.g., css/app.css). |
$absolute | bool | Whether to return an absolute URL using APP_URL (default: false). |
$depth | int|null | Directory 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
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.nullor unrecognized: Detect content from$messageand render it.
function abort(
int $status = 500,
string|array|object|null $message = null,
array $headers = [],
?string $type = null
): neverParameters:
| Parameter | Type | Description |
|---|---|---|
$status | int | HTTP status code (default: 500). |
$message | string|array|object|null | Optional message string, array (JSON), or object to return. |
$headers | array<string,mixed> | Optional HTTP headers to include in the response. |
$type | string|null | Optional forced response type: xml, text, or html (default: null). |
Return Value:
never - This function does not return; it ends the request.
Throws:
- \Luminova\Exceptions\ResponseException - If an error occurs while sending the abort response.
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): neverParameters:
| Parameter | Type | Description |
|---|---|---|
$uri | string | Target URL to redirect to. |
$method | string|null | Redirection method: 'refresh' or null for standard (default: null). |
$status | int | HTTP 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): neverParameters:
| Parameter | Type | Description |
|---|---|---|
$fallback | string|null | URI to redirect to if no referer is found. |
$method | string|null | Redirection method ('refresh' or null for standard, default: null). |
$status | int | HTTP status code for the redirect (default: 302). |
Return Value:
never
ask
Ask a question using the configured AI model.
This helper provides two behaviors:
- If
$promptis provided, the message is sent immediately and the response is returned as an array. - If
$promptisnull, 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|arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$prompt | string|null | Optional message to send to the AI model. |
$model | Luminova\AI\Model|object|string | Model enum, client object, or model name (default: gpt-4.1-mini). |
$options | array<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:
- \Luminova\Exceptions\AIException - If an error occurs.
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\AwaitableParameters:
| Parameter | Type | Description |
|---|---|---|
$task | (callable():mixed) | The task to run asynchronously. |
$detach | bool | If true, the task runs in a detached background process. |
Return Value:
Luminova\Interface\Awaitable - Return an awaitable Future representing the task.
Throws:
- \Luminova\Exceptions\InvalidArgumentException - If the task type is invalid.
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 = []): ?intParameters:
| Parameter | Type | Description |
|---|---|---|
$task | (callable(array $args):mixed) | The task to execute. |
$arguments | array<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): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$task | Luminova\Interface\Awaitable | The awaitable task to run. |
$timeout | int | Maximum wait time in seconds (0 = unlimited). |
$delay | float | Delay in seconds between execution checks (default: 0.1). |
Return Value:
mixed - Return the value returned by the task once it completes.
Throws:
- \Luminova\Exceptions\RuntimeException - If the task does not complete within the specified timeout.
\Throwable- If the task itself throws an exception during execution.
See Also
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 toroot/app/*package: Resolves toroot/system/plugins/*view: Resolves toroot/resources/Views/*system: Resolves toroot/system/*public: Resolves toroot/public/*writeable: Resolves toroot/writeable/*libraries: Resolves toroot/libraries/*resources: Resolves toroot/resources/*routes: Resolves toroot/routes/*bootstrap: Resolves toroot/bootstrap/*bin: Resolves toroot/bin/*node: Resolves toroot/node/*
function import(
string $path,
bool $throw = true,
bool $once = true,
bool $useRequire = false,
array $scope = [],
bool $promise = false
): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$path | string | File path or scheme-based path to import (e.g., app:Config/file.php). |
$throw | bool | If true, throw an exception when the file doesn't exist (default: true). |
$once | bool | If true, load the file only once using *_once (default: true). |
$useRequire | bool | Use require instead of include (default: false). |
$scope | array<string,mixed> | Optional associative array of variables to extract into the file scope (keys become variable names). |
$promise | bool | Optionally 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:
- \Luminova\Exceptions\RuntimeException - If the file doesn't exist and
$throwistrue. - \Luminova\Exceptions\InvalidArgumentException - If
$scopeis not empty and not an associative array (list array given).
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 = []): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$destination | string | The destination to send the log to (e.g., a log level, email, or URL endpoint). |
$message | string | The message to log. |
$context | array | Optional 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:
- \Luminova\Exceptions\InvalidArgumentException - If the target is invalid or logging fails.
Note:Uses the preferred PSR logger class defined in
App\Config\Preference, otherwise falls back toLuminova\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|boolParameters:
| Parameter | Type | Description |
|---|---|---|
$locale | string|null | The locale to set, or null to return the current locale. |
$persist | bool | Whether 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): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$version | int | Version of the UUID to generate: 1, 3, 4, 5, or 7 (default: 4). |
$namespace | string|null | The namespace for versions 3 and 5 (e.g., dns, url, oid, x500, or a custom UUID). |
$name | string|null | The name for versions 3 and 5. |
$time | int|null | Optional 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:
- \Luminova\Exceptions\InvalidArgumentException - If the version is unsupported, the namespace/name is missing for v3/v5, the namespace is invalid, or the timestamp is invalid for v1/v7.
See Also
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(): stringReturn Value:
string - Return a 26-character ULID string.
See Also
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|stringParameters:
| Parameter | Type | Description |
|---|---|---|
$input | array|string | The string or array to escape. |
$context | string | The default escape context (default: 'html'). |
$encoding | string | The character encoding to use (default: 'utf-8'). |
Return Value:
array|string - Return the escaped string or array.
Throws:
- \Luminova\Exceptions\InvalidArgumentException - If the encoding is empty, invalid, or unsupported.
- \Luminova\Exceptions\BadMethodCallException - If an unsupported escape context is specified.
Examples:
use function Luminova\Funcs\escape;
echo escape('<script>alert("xss")</script>');
// <script>alert("xss")</script>
$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 = ''): ?stringParameters:
| Parameter | Type | Description |
|---|---|---|
$input | string | The input string to be sanitized. |
$type | string | The expected data type (e.g., int, email, username). |
$replacer | string|null | Replacement 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:
- \Luminova\Exceptions\InvalidArgumentException - If the input contains disallowed characters and
$replaceris set tonull.
Note:For
'default', HTML tags (including their content) are fully removed.
See Also
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): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$input | string | The string to validate strictly. |
$type | string | The expected data type (default: Util::SANITIZE_DEFAULT). |
Return Value:
string - Return the sanitized string.
Throws:
- \Luminova\Exceptions\InvalidArgumentException - If the input contains invalid characters for the specified type.
See Also
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 = []): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$lookup | string | The language lookup key (e.g., App.error.foo.bar). |
$default | string|null | Optional fallback message if not found. |
$locale | string|null | Optional translation locale. If null, the current application locale is used. |
$placeholders | array<string|int,string|int> | Optional placeholder replacements. |
Return Value:
string - Return the translated message.
Throws:
- \Luminova\Exceptions\NotFoundException - If the translation is not found and no default is provided.
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): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$function | callable-string | Name of the function to call. |
$arguments | mixed | Arguments to pass to the function. |
Return Value:
mixed - Return the result of the executed function.
Throws:
- \Luminova\Exceptions\RuntimeException - If the function is disabled or does not exist.
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): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string | The key to identify the value. |
$value | mixed | The value to store (optional). |
$default | mixed | The 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|MemoryCacheParameters:
| Parameter | Type | Description |
|---|---|---|
$driver | string | The cache driver to use: filecache, redis, or memcached (default: filecache). |
$storage | string|null | The name of the cache storage. If null, setStorage() must be called later (default: null). |
$persistentId | string|null | Optional 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:
- \Luminova\Exceptions\ClassException - If an unsupported driver is specified.
- \Luminova\Exceptions\CacheException - If there is an issue initializing the cache.
- \Luminova\Exceptions\InvalidArgumentException - If an invalid subdirectory is provided for the filesystem cache.
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\InputValidationInterfaceParameters:
| Parameter | Type | Description |
|---|---|---|
$inputs | array|null | Input fields to validate (e.g., $_POST, $_GET, or $this->request->getBody()). |
$rules | array|null | Validation filter rules to apply on each input field. |
$messages | array | Validation 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): ?arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$filename | string | The configuration name without extension (e.g., Storage). |
$default | array|null | The value returned when the file does not exist (default: null). |
Return Value:
array|null - Return the configuration array or the default value.
Throws:
- \Luminova\Exceptions\UnexpectedValueException - If the loaded file does not return an array.
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
): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string|null | Session key to retrieve, or null to return the session instance. |
$shared | bool | Whether to reuse the shared session instance (default: true). |
$manager | SessionManagerInterface|null | Session 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.
cookie
Create and return a cookie instance.
function cookie(string $name, string $value = '', array $options = [], bool $shared = false): Luminova\Cookies\CookieParameters:
| Parameter | Type | Description |
|---|---|---|
$name | string | The name of the cookie. |
$value | string | The value of the cookie. |
$options | array | Options to be passed to the cookie. |
$shared | bool | Use 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): ?objectParameters:
| Parameter | Type | Description |
|---|---|---|
$context | string|null | The factory context name, e.g., session (default: null). |
$shared | bool | Whether to return a shared instance (default: true). |
$arguments | mixed | Optional 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:
- \Luminova\Exceptions\LuminovaException - Throws if the factory context does not exist or an error occurs.
Available Factory Context Names
task- Returns instance ofLuminova\Time\Tasksession- Returns instance ofLuminova\Sessions\Sessioncookie- Returns instance ofLuminova\Cookies\Cookiefunctions- Returns instance ofLuminova\Foundation\Core\Functionsmodules- Returns instance ofLuminova\Library\Moduleslanguage- Returns instance ofLuminova\Components\Languages\Translatorescaper- Returns instance ofLuminova\Security\Escapernetwork- Returns instance ofLuminova\Http\Networkfilesystem- Returns instance ofLuminova\Storage\Filesystemvalidate- Returns instance ofLuminova\Security\Validationresponse- Returns instance ofLuminova\Template\Responserequest- Returns instance ofLuminova\Http\Requestservice- Returns instance ofLuminova\Foundation\Module\Servicenotification- Returns instance ofLuminova\Notifications\Firebase\Notificationcaller- Returns instance ofLuminova\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
): ?objectParameters:
| Parameter | Type | Description |
|---|---|---|
$service | class-string<\T>|string|null | The service class name or alias. |
$shared | bool | Whether to return a shared instance of the class (default: true). |
$serialize | bool | Whether to serialize and store the class object as cache (default: false). |
$arguments | mixed | Additional 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:
- \Luminova\Exceptions\LuminovaException - Throws if the service does not exist or an error occurs.
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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$service | class-string<\T>|string|null | The 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
nullis 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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$library | string | The library path or name (e.g., Foo/Bar/Baz or Foo/Bar/Baz.php). |
$throw | bool | If 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:
- \Luminova\Exceptions\RuntimeException - If the file is missing and
$throwistrue.
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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$closeSession | bool | Whether to close the active session before finishing the response (default: true). |
$ignoreUserAbort | bool | Whether 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()orlitespeed_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): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$route | string|null | Optional route URI path to append to the start URL (default: null). |
$relative | bool | If 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: /aboutabsolute_url
Convert an application-relative path to an absolute URL.
function absolute_url(string $path): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$path | string | The path to create an absolute URL from. |
Return Value:
string - Return the absolute URL of the specified path.
See Also
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): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$path | string | The 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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$status | int | HTTP 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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$os | string | Platform 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(): boolReturn 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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$value | mixed | The 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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$ip | string|null | The IP address to check, or null to use the current IP address. |
$expiration | int | Expiration 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:
- \Luminova\Exceptions\FileException - If an error occurs reading or writing the exit-node cache directory.
is_utf8
Check if a given string is valid UTF-8.
function is_utf8(string $input): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$input | string | The 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
Countableobjects
function is_empty(mixed ...$values): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$values | mixed | One 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)[]); // trueNote: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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$array | array | The array to check. |
$recursive | bool | Whether to check all levels deeply (default: false). |
$strict | bool | Whether 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); // trueNote: 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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$array | array | The 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([]); // falseis_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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$value | mixed | The value to inspect. |
$testOnly | bool | Whether to check the format only, without unserializing (default: false). |
$allowClass | bool | Whether 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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$input | string | The 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|nullParameters:
| Parameter | Type | Description |
|---|---|---|
$ipInfo | bool | If true, returns detailed IP information instead of just the IP (default: false). |
$metadata | array | Optional 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): ?stringParameters:
| Parameter | Type | Description |
|---|---|---|
$version | string|null | Optional 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): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$name | string | The 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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$path | string | Directory path to create. |
$permissions | int|null | Unix permission mode. If null, uses App\Config\Security::$dirPermissions. |
$recursive | bool | Whether 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:
- \Luminova\Exceptions\RuntimeException - If the parent path is not readable.
- \Luminova\Exceptions\FileException - If the directory cannot be created.
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): ?stringParameters:
| Parameter | Type | Description |
|---|---|---|
$prefix | string|null | Optional subdirectory name to create inside the selected temporary storage path. |
$fromLocal | bool | Whether 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
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): ?stringParameters:
| Parameter | Type | Description |
|---|---|---|
$filename | string|null | Optional filename prefix. When given without $extension, the extension is derived from $filename. |
$extension | string|null | Optional file extension without a leading dot. |
$fromLocal | bool | Whether 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
get_class_name
Get the class basename from a namespace or class object.
function get_class_name(string|object $from, bool $validate = false): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$from | string|object | The namespace or class object. |
$validate | bool | Whether 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|boolParameters:
| Parameter | Type | Description |
|---|---|---|
$input | string | File path or raw binary string to extract the MIME type from. |
$magicDatabase | string|null | Optional path to a custom magic database (e.g., \path\custom.mgc). |
$customDatabase | string|null | Optional 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:
- \Luminova\Exceptions\RuntimeException - If a database file is not readable or an error occurs reading it.
- \Luminova\Exceptions\InvalidArgumentException - If the extension or MIME type is invalid.
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|boolParameters:
| Parameter | Type | Description |
|---|---|---|
$filename | string | The path to the file to read. |
$length | int | Maximum number of bytes to read, 0 reads in 8192-byte chunks (default: 0). |
$offset | int | The starting position in the file to begin reading from (default: 0). |
$useInclude | bool | If true, the file will be searched in the include path (default: false). |
$context | resource|null | Optional stream context created with stream_context_create(). |
$delay | int | Delay 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:
- \Luminova\Exceptions\FileException - If unable to open or read the file.
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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$filename | string | Path to the file to write to. |
$content | string|resource | Data to write, either as a string or a stream resource. |
$flags | int | Bitwise flags, e.g., FILE_APPEND \| LOCK_EX (default: 0). |
$context | resource|null | Optional stream context created with stream_context_create(). |
Return Value:
bool - Return true on success, false on failure.
Throws:
- \Luminova\Exceptions\FileException - If the file cannot be written.
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
$resultis exactlyfalse, or is an integer equal to1, the result is treated as a failure: returns1when$returnIntistrue, orfalseotherwise. - Otherwise the result is treated as a success: returns
(int) $resultwhen$returnIntistrue(e.g.,null/voidcasts to0,truecasts to1), ortrueotherwise.
function status_code(mixed $result = null, bool $returnInt = true): bool|intParameters:
| Parameter | Type | Description |
|---|---|---|
$result | mixed | The response from the callback function, controller, or command. |
$returnInt | bool | Whether 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'): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$input | array<string|int,mixed> | The array to escape. |
$context | string | The default escape context (default: 'html'). |
$encoding | string | The character encoding to use (default: 'utf-8'). |
Return Value:
array<string|int,mixed> - Return the escaped array.
Throws:
- \Luminova\Exceptions\InvalidArgumentException - If the encoding is empty, invalid, or unsupported.
- \Luminova\Exceptions\BadMethodCallException - If an unsupported escape context is specified.
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): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$array | array | Input array. |
$withCounts | bool | Whether to return occurrence counts instead of values (default: false). |
$preserveKeys | bool | Whether 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): objectParameters:
| Parameter | Type | Description |
|---|---|---|
$from | object | The input collection (an object of objects/arrays). |
$property | string|int|null | The key or property to extract from each item (default: null). |
$index | string|int|null | Optional 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|objectParameters:
| Parameter | Type | Description |
|---|---|---|
$from | array|object | The input collection (array of arrays/objects, or an object). |
$property | string|int|null | The key or property to extract from each item. |
$index | string|int|null | Optional 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
to_array
Recursively convert an object, string-list, or mixed value to an array.
function to_array(mixed $input): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$input | mixed | The 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|boolParameters:
| Parameter | Type | Description |
|---|---|---|
$input | array|string | Input 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|boolParameters:
| Parameter | Type | Description |
|---|---|---|
$list | string | The 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 = []): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$list | string | The string list to check. |
$array | array | The 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']); // truearray_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): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$items | array | List of values, or an array of associative arrays. |
$key | string|null | Key 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
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): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$items | array | List of values, or an array of associative arrays. |
$key | string|null | Key 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_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): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$array | array | The array to merge into. |
$arrays | array | One 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): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$array | array | The 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): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$default | array | The default options array. |
$new | array | The 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): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$results | mixed | (by reference) The results variable to merge or append the response into. |
$response | mixed | The response to merge with results. Can be an array, string, or other type. |
$preserveNested | bool | Whether 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): intParameters:
| Parameter | Type | Description |
|---|---|---|
$content | string | The content to calculate the length for. |
$charset | string|null | The 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): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$input | string | The input string to convert. |
$toLower | bool | Whether 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-worlDcamel_case
Convert a string to camelCase.
function camel_case(string $input): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$input | string | The 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'); // helloWorldpascal_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): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$input | string | The 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'); // HelloWorldsnake_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): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$input | string | The 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_worlduppercase_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): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$input | string | The 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_BazMore 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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$string | string | The 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|boolParameters:
| Parameter | Type | Description |
|---|---|---|
$input | string | The string to scan. |
$start | string | The opening delimiter to match (single character). |
$end | string | The closing delimiter to match (single character). |
$offset | int | Position to start searching from (default: 0). |
Return Value:
int|bool - Return the matching closing delimiter position, or false if not found.
Throws:
- \Luminova\Exceptions\InvalidArgumentException - If
$startor$endis not a single character.
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): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$text | string|null | A 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): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$text | string|null | A 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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$class | string | Fully 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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$class | string | The name of the class to check. |
$autoload | bool | Whether 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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$function | string | The name of the function to check. |
Return Value:
bool - Return true if the function exists, false otherwise.