Luminova Framework

PHP Luminova: Built-in Global Helper Functions

Last updated: 2026-01-17 19:40:29

Luminova built-in global functions provide reusable helper utilities available across the application to simplify common tasks and improve productivity.

Global functions are procedural helpers provided by Luminova to solve common tasks in your application. They are available everywhere in your code because they are defined in the global scope and loaded automatically at runtime.

Why Use Global Helpers?

  1. Avoid RepetitionWrite a function once and reuse it anywhere in your project. No need to duplicate logic across files.

  2. Speed Up DevelopmentHelpers handle common tasks like formatting, file paths, or date checks, letting you focus on your core logic.

  3. Improve ReadabilityReplace long or complex logic with short, clear function calls to make your code easier to read and maintain.

For developer-defined Custom Functions and Constants, see the relevant documentation.


Non-Namespace Access Functions

These functions are global and do not use a namespace.Calling them with a namespace (e.g., Luminova\Funcs\function_name()) will result in a "function not found" error.

Correct usage:

// Correct
env('app.name');

// Incorrect - will throw an error
Luminova\Funcs\env('app.name'); // function does not exist

env

Get Environment Variables.

Retrieve environment variable values from the registered environment, combining $_ENV, $_SERVER, and getenv(). Returns a typed value or a default if the key is not found.

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

Parameters:

ParameterTypeDescription
$keystringThe environment variable key to retrieve.
$defaultmixedOptional default value if the key is not found.

Return Value:

mixed — Value of the environment key or the default.

Example:

$appName = env('app.name', 'Luminova'); // returns 'Luminova' if key is missing

If a variable is stored as foo = [1, 2, 4] in .env, env('foo') will return it as an array.

See Also: Environment Variables


setenv

Set Environment Variables.

Set or update an environment variable at runtime. Optionally, persist the value in the .env file.

function setenv(string $key, string $value, bool $persist = false): bool

Parameters:

ParameterTypeDescription
$keystringThe key of the environment variable.
$valuestringThe value to assign.
$persistboolIf true, writes/updates the value in the .env file (default: false).

Return Value:

booltrue if the variable was set successfully, false otherwise.

Examples:

// Set for current runtime only
setenv('FOO_KEY', 'foo value');

// Set and persist to .env file
setenv('FOO_KEY', 'foo value', persist: true);

// Add/update disabled entry (prefixed with ;)
setenv(';FOO_KEY', 'foo value', persist: true);

By default, setenv only affects the current runtime.To permanently save the value in your .env file, pass true as the third argument.A more efficient way is to use the NovaKit Command:

php novakit env:add --key="my_new_key" --value="my key value"

Namespaced Access Functions

The below Luminova helper functions are defined inside the Luminova\Funcs namespace. To use them, you must either import them explicitly or call them with the full namespace.

Examples:

// Import a single function (recommended)
use function Luminova\Funcs\response;

// Import multiple functions at once
use function Luminova\Funcs\{
    response,
    asset,
    href,
    root
};

// Call a namespaced function directly without import
Luminova\Funcs\root('path', 'file.txt');

Tip:

Only import the functions you need.Avoid using wildcard imports (use function Luminova\Funcs\*) as they can clutter your code and may not work in all PHP versions.

This keeps your code clean, readable, and avoids potential naming conflicts.


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.

This helper does not pass arguments to the application constructor.Application creation and configuration are handled internally by the kernel.

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\ApplicationOptional application instance to replace the shared one.

Return Value:

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

Examples:

Get shared application instance:

use function Luminova\Funcs\app;

$app = app();

Create a new application instance:

use function Luminova\Funcs\app;

$app = app(shared: false);

// Same as
$app = new App\Application();

Replace shared instance of application:

use function Luminova\Funcs\app;

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

// Same as
$app = App\Application::setInstance(new App\Application());

See Also

See Core Application, documentation for more usages.

Note:

Avoid re-initializing application class if possible, always use the app function or grab the shared instance of your application by Application::getInstance()


request

Retrieve an HTTP request object.

This function returns a shared or new instance of the HTTP request handler for accessing headers, query parameters, body data, and other request-specific information.

function request(bool $shared = true): RequestInterface

Parameters:

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

Return Value:

Luminova\Interface\RequestInterface<Psr\Http\Message\RequestInterface> - Returns instance of HTTP request object.

See Also

See HTTP Incoming Request documentation for http request methods and usages.


session

Return session data if key is present, otherwise return the session class instance.

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

Parameters:

ParameterTypeDescription
$keystring|nullOptional key to retrieve the data (default: null).
$sharedboolWhether to use shared instance (default: true).
$managerSessionManagerInterface|nullThe session manager interface to use (default: SessionManager).

Return Value:

Luminova\Sessions\Session|mixed - Return the session data if key is provided, otherwise the instance of session class.

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 shared instance (default: false).

Return Value:

Cookie - Return new cookie instance.

See Also

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


func

Safely call a PHP function with arguments.

This helper:

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

Parameters:

ParameterTypeDescription
$functionstringName of the function to call.
$argumentsmixedArguments to pass to the function.

Return Value:

mixed - Return the result of the executed function.

Example:

Call the set_time_limit function dynamically:

use function Luminova\Func\func;

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

factory

To initialize a class available in factory and returns a shared instance of the class.Optionally you can pass NULL to context parameter in other to return factory instance instead.

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>|Factory|null - Return instance of factory class, instance of class called, otherwise 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
  • fileManager - Returns instance of Luminova\Storage\FileManager
  • validate - Returns instance of Luminova\Security\Validation
  • response - Returns instance of Luminova\Template\Response
  • services - Returns instance of App\Config\Services
  • request - Returns instance of Luminova\Http\Request
  • notification - Returns instance of Luminova\Notifications\Firebase\Notification
  • caller - Returns instance of Luminova\Application\Caller
  • escaper - Returns instance of Luminova\Utility\Escape

Example

This example shows how to initialize session class instance with a new constructor argument using factory.

use function Luminova\Funcs\factory;

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

See Also

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


service

Service on the other hand focus more on your business logic, It allows you to returns a shared instance of a class registered in your service bootstrap method. To return an instance of service pass null as the service parameter.

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 class (default: true).
$serializeboolWhether to serialize and store class object as cache (default: false).
$argumentsmixedAdditional parameters to pass to class constructor.

Return Value:

class-object<\T>|Services|null - Return service class instance or instance of called class.

Throws:

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


remove_service

Delete a service or clear all services.

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

Parameters:

ParameterTypeDescription
$serviceclass-string<\T>|stringThe class name or alias, to delete and clear it cached.

Return Value:

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

If NULL is passed all cached and serialized services will be cleared.


layout

PHP Template layout helper class, to extend, inherit and import layout sections while using default template engine.

function layout(string $file): Luminova\Template\Layout

Parameters:

ParameterTypeDescription
$filestringLayout filename without the extension path.

Return Value:

Luminova\Template\Layout - Returns the layout class instance.

Throws:

See Also

Template Layout - See the documentation for default PHP template layout methods and usages.

All layouts must be stored in resources/Views/layout/ directory.Examples: layout('foo') or layout('foo/bar/baz')


response

Create a view response object.

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

function response(int $status = 200, ?array $headers = null, bool $shared = true): ViewResponseInterface

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\ViewResponseInterface - Return instance of view response object.

Example:

Send a JSON response:

use function Luminova\Funcs\response;

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

See Also

For more information see View Response Class documentation for and usage examples.


response

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: Attempt to detect content from $header (Content-Type) or $message (body).
function abort(
    int $status = 500, 
    string|array|object|null $message = null, 
    array $headers = [], 
    ?string $type = null
): never 

Parameters:

ParameterTypeDescription
$statusintHTTP status code (default: 200 OK).
$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: json, xml, text, or html (default: null).

Throws:

Example:

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>', type: 'html'); // Sends HTML.

redirect

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: Attempt to detect content from $header (Content-Type) or $message (body).
function redirect(string $uri, ?string $method = null, int $status = 302): void

Parameters:

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

Examples:

Basic redirect (302 Found):

use function Luminova\Funcs\redirect;

redirect('/home');

// Redirect with 301 (Moved Permanently):
redirect(uri: '/new-url', status: 301);

// Redirect using 'Refresh' header (useful for IIS):
redirect('/dashboard', 'refresh');

back

Redirect the user to the previous page.

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

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

Parameters:

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

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 view helper does not render 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.
$statusintTemplate content type (default: View::HTML).

Return Value:

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

Using the View Helper in HTTP Context:

The view helper can be called directly from HTTP controllers or route context files when using method-based routing. It’s used to render templates easily within your application.

Context:

// Route files
/route/*.php

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

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

Examples:

Render and send output:

use function Luminova\Funcs\view;

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

Return rendered contents:

use function Luminova\Funcs\view;

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

Note:

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


shared

Temporarily stores and retrieves values within the same scope.

It allows you to set and get shared values. It uses a static array to store the shared preference, which persists across multiple calls to the function within the same script 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 return if key not found (default: NULL).

Return Value:

mixed - Returns the value associated with the key, or default value if the key does not exist.


browser

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

This function inspects the user agent string and returns browser informationin the format you choose.

Return formats:

  • 'array' → associative array of browser info.
  • 'object' → stdClass object with browser info.
  • 'instance' → the UserAgent instance itself.
function browser(?string $userAgent = null, string $return = 'object', bool $shared = true): mixed

Parameters:

ParameterTypeDescription
$userAgentstring|nullOptionally parse user agent string to analyze (default: null).
$returnboolThe return type (default: object).
- Return Types: [array, object, instance]
$sharedboolIf true, reuse a static UserAgent instance (default: true).

Return Value:

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

See Also

See HTTP UserAgent Object documentation for browser user-agent methods and usages.


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.

If $view is null or empty, the base path is returned.

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

Parameters:

ParameterTypeDescription
$uristring|nullThe route, view name, or file path. (default: null).
$absoluteboolWhether to return an absolute URL, using APP_URL (default: false).
$depthintDirectory depth used for relative URLs (default: 0).

Return Value:

string - Returns the generated URL.

If an absolute URL is requested, concatenates the base URL (APP_URL) with the view path.If a relative URL is requested, it concatenates it with the view path.

Examples:

use function Luminova\Funcs\href;

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

asset

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

Builds a relative or absolute URL pointing to an asset such as CSS, JavaScript, images, or other public files.

If $filename is null or empty, the base assets/ path is returned.

function asset(?string $filename = null, bool $absolute = false, int $depth = 0): 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).
$depthintDirectory depth used for relative URLs (default: 0).

Return Value:

string - Return the generated URL to the assets file or base assets folder if no filename is provided.

Examples:

use function Luminova\Funcs\asset;

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

Note:If $absolute is true, the absolute URL is returned, otherwise a relative URL is returned.


root

Resolve the application root directory with optional appended path.

This function helps ensure all paths are built relative to the application’s root directory.It attempts to locate the root by checking for a .env file in APP_ROOT, the parent directory, or by walking up the directory tree.

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

Parameters:

ParameterTypeDescription
$pathstring|nullOptional subdirectory path to point from project root (e.g., writeable/logs).
$filenamestring|nullOptional filename to append after the path (e.g., debug.log).

Return Value:

string - Returns the absolute path to the root directory, with optional path and filename appended.

Examples;

use function Luminova\Funcs\root;

$logPath = root('writeable/logs', 'debug.log');

// Returns: /your-app-root/writeable/logs/debug.log

Navigate backward into another project root.

use function Luminova\Funcs\root;

$logPath = root('../example.com/writeable/logs', 'debug.log');

// Returns: /path/to/www/../example.com/writeable/logs/debug.log

Note:If you pass a filename as $path instead of using $filename, it will treat it as a folderand may produce /root/file.txt/ — which is usually unintended.


path

Resolves system and application path.

This function resolves application paths based on names and ensure separator are normalized to based on environment unix or windows specific style.

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.
  • services - Application cached services directory.
function path(string $file): string

Parameters:

ParameterTypeDescription
$filestring|nullThe path name to resolves.

Return Value:

string - Return full directory path, windows, unix or windows style path.

See Also

See FileSystem Helper, documentation for more usages.


import

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

This function makes it easier to load files from common project folders without typing full paths.

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), you can change this behavior with the function options.

You can also pass an associative array of variables to make available inside the imported file. The array keys become variable names.

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 = false, 
    bool $once = true, 
    bool $require = true, 
    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: false).
$onceboolIf true, load the file only once using *_once (default: true).
$requireboolIf true, use require/require_once, otherwise use include/include_once (default: true).
$scopearray<string,mixed>Optional associative array of variables to extract into the file scope.
(Keys become variable names).
$promiseboolOptionally use import with promise resolver (default: false).

Return Value:

mixed - Return any result of the imported file, or null if not found and $throw is false.

Throws:

Examples:

Import using scheme (recommended):

use function Luminova\Funcs\import;

// Resolves to: root('app', 'Config/settings.php')
import('app:Config/settings.php');

Import with global scope variables:

use function Luminova\Funcs\import;

import('view:profile.php', scope: [
   'id' => 1234
]);

// /resources/Views/profile.php
echo $id; // 1234

Import packages (composer vendor):

use function Luminova\Funcs\import;

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

Import using direct file path:

use function Luminova\Funcs\import;

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

Force exception when file is missing:

use function Luminova\Funcs\import;

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

Use include instead of require:

use function Luminova\Funcs\import;

import('system:Bootstrap/init.php', require: false);

Allow multiple imports of same file:

use function Luminova\Funcs\import;

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

Promise Examples:

Promise-style:

use function Luminova\Funcs\import;

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

Scope + promise:

use function Luminova\Funcs\import;

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

If file missing:

use function Luminova\Funcs\import;

import('view:missing', promise: true)
    ->then(fn() => echo "Loaded")     // skipped
    ->catch(fn($e) => echo $e->getMessage());

import_lib

Import a custom library from the libraries/libs directory.

This function simplifies loading external libraries stored under /libraries/libs/.

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 - Returns true if the library was successfully loaded, false otherwise.

Throws:

Example:

You must place your external libraries in libraries/libs/ directory in other to use file import.

use function Luminova\Funcs\import;

import_lib('Foo/Bar/Baz');

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

function_exists_cached

Checks if a function exists and caches the result to avoid repeated checks.

This function uses a static cache to store whether a function exists or not.

If the function's existence has been checked before, the cached result is returned.Otherwise, it checks the function's existence using function_exists() and caches the result, improving performance by avoiding repeated function existence checks.

function function_exists_cached(string $function): bool

Parameters:

ParameterTypeDescription
$functionstringThe name of the function to check for existence.

Return Value:

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


class_exists_cached

Checks if a class exists and caches the result for improved performance.

This function maintains a static cache to remember whether a class has been previously checked.

It first checks the cache to see if the class's existence was determined before. If not, it uses class_exists() to perform the check and then stores the result in the cache. This avoids redundant checks and speeds up subsequent requests.

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

Parameters:

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

Return Value:

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


logger

Logs 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 the Logger::dispatch() method for synchronous or asynchronous handling.

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

Parameters:

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

Log levels

  • emergency - Log urgent errors requiring immediate attention.
  • alert - Log important alert messages.
  • critical - Log critical issues that may disrupt application functionality.
  • error - Log minor errors.
  • warning - Log warning messages.
  • notice - Log messages that require attention but are not urgent.
  • info - Log general information.
  • debug - Log messages for debugging purposes.
  • exception - Log exception messages.
  • php_errors - Log PHP-related errors.
  • metrics - Log performance metrics for APIs.

Throws:

Note:It uses the configured preferred PSR logger class if define in App\Config\Preference, otherwise it will use default Luminova\Logger\NovaLogger.

All non-external log destination are located in /writeable/log/.Each log level has it own file name (e.g, warning.log).


locale

Set application locale or return current application local.

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

Parameters:

ParameterTypeDescription
$locale?stringOptional locale to set.

Return Value:

string|bool - Return true if locale is specified and set, otherwise return previous locale.


uuid

Generate a random UUID string.

This function generates a UUID string of the specified version such as 1, 2, 3, 4, or 5.

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

Parameters:

ParameterTypeDescription
$versionintThe version of the UUID to generate (default: 4)..
$namespacestring|nullThe namespace for versions 3 and 5.
$namestring|nullThe name for versions 3 and 5.

Return Value:

string -Return the generated UUID string.

Throws:

Note:To check if UUID is valid use Common Helpers


escape

The escape function safely escapes a string or an array of strings for the specified output context.

It helps prevent cross-site scripting (XSS) and other injection attacks by applying the correct escaping rules based on where the data will be used.

Supported contexts:

  • html – Escape for HTML output
  • js – Escape for JavaScript strings
  • css – Escape for CSS values
  • url – Escape for URLs
  • attr – Escape for HTML attributes
  • raw – No escaping, output as-is
function escape(
    string|array $input, 
    string $context = 'html', 
    ?string $encoding = 'utf-8'
): array|string

Parameters:

ParameterTypeDescription
$inputstring|array|nullThe string or array of strings to be escaped.
$contextstringThe escaper context in which the escaping should be performed (default:'html').
$encodingstring|nullThe escape character encoding to use (default: 'utf-8').

Throws:

Return Value:

array|string - Return the escaped string or array of strings.

Examples:

Always choose the correct context for your output to ensure safety and prevent vulnerabilities.

use function Luminova\Funcs\escape;

// Escape HTML content
echo escape('<script>alert("xss")</script>'); 
// Output: &lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;

// Escape URL
$url = escape('https://example.com/?q=<script>', 'url'); 
// Output: https%3A%2F%2Fexample.com%2F%3Fq%3D%3Cscript%3E

Array Input

Escaping an associative array:

Each key defines the context for its corresponding value.

use function Luminova\Funcs\escape;

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

$escaped = escape($data);
print_r($escaped);

/* Output:
[
    'html' => '&lt;b&gt;Bold&lt;/b&gt;',
    'js'   => 'alert(\"xss\")',
    'url'  => 'https%3A%2F%2Fexample.com%2F%3Fq%3D%3Cscript%3E'
]
*/

Escaping an indexed array:

All values use the default context (html) unless another context is specified.

use function Luminova\Funcs\escape;

$data = [
    '<b>Bold</b>',
    '<script>alert("xss")</script>'
];

$escaped = escape($data);
print_r($escaped);

/* Output:
[
    '&lt;b&gt;Bold&lt;/b&gt;',
    '&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;'
]
*/

See Input Escaper, documentation for more escape context.


sanitize

Sanitizes user input to remove invalid or unsafe characters.

This function sanitizes user input by strictly removing unsafe characters to protect against invalid characters and ensure it conforms to the expected type.

function sanitize(string $input, string $type = '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: '' blank).
If null, input is validated only and exception is thrown when failed.

Return Value:

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

Throws:

Note:For 'default', HTML tags (including content) are fully removed.This method ensures secure input handling to prevent unsafe content.

See Input Sanitization Utility, documentation for various supported types to enforce allowed characters or formats.


strict

Strictly sanitizes input according to the specified type.

Unlike sanitize(), strict() will always throw an exception if input contains invalid characters instead of replacing them. This ensures the input fully conforms to the expected format.

function strict(string $input, string $type = 'default'): string

Parameters:

ParameterTypeDescription
$inputstringThe string to validate strictly.
$typestringThe expected data type (e.g., int, email, username).

Return Value:

string - Return sanitized string.

Throws:

Use Case:

Use strict() when you require full compliance with input rules and want to preventany implicit replacements. This is ideal for sensitive fields like email, usernames, passwords, or UUIDs.

See Input Sanitization Utility, documentation for supported types.


lang

Translate multiple languages with support for nested arrays.

function lang(string $lookup, ?string $default = null, ?string $locale = null, array $placeholders = []): string

Parameters:

ParameterTypeDescription
$lookupstringThe key to lookup in the translation files.
$defaultstring|nullThe default fallback translation if not found.
$localestring|nullThe locale to use for translation (optional).
$placeholdersarrayMatching placeholders for translation.

Return Value:string - Return the translated text.

Throws:

To create a language translations you need to define it in /app/Languages/.

The file name format should be like Example.en.php, where the Example is the context and en is the locale.

See Also

Translations - See the documentation for translation methods and usages.

Example.en.php

return [
    'error' => 'Error your example encountered error',
    'users' => [
        'notFound' => 'Username "{username}" does not exist.',
        'password' => 'Error your password {0} doesn\'t match with {1}'
    ]
];

Assuming your application locale is already set to EN.

echo Luminova\Funcs\lang('Example.error'); // Error your example encountered error
echo Luminova\Funcs\lang('Example.error.users.notFound', null, null, [
    'username' => "peterujah"
]); 
// Username "peterujah" does not exist.
echo Luminova\Funcs\lang('Example.error.users.password', null, null, [
    '12345@199',
    "12345@123"
]); 
// Error your password 12345@199 doesn't match with 12345@123

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 - Returns the configuration array or the default value.

Throws:

Examples:

Configuration File:

// app/Config/SomeConfig.php
<?php
return [
    'option' => ['foo', 'bar'], 
    'status' => 1
];

Loading Configuration:

use function Luminova\Funcs\configs;

$config = configs('SomeConfig');

NoteThe configuration file must return an array.


cache

Initialize or retrieve a new instance of the cache class.

function cache(string $driver, ?string $storage = null, ?string $persistentIdOrSubfolder = null): Luminova\Base\Cache

Parameters:

ParameterTypeDescription
$driverstringThe cache driver to return instance of [filesystem or memcached](default: filesystem).
$storagestring|nullThe name of the cache storage. If null, you must call the setStorage method later (default: null).
$persistentIdOrSubfolderstring|nullOptional persistent id or subfolder for storage (default: null):

Persistent Id Or Subfolder Param

  • For Memcached: A unique persistent connection ID. If null, the default ID from environment variables is used, or default if not set.
  • For Filesystem Cache: A subdirectory within the cache directory. If null, defaults to the base cache directory.

Return Value:

Luminova\Base\Cache - Return new instance of instance of FileCache or MemoryCache cache based on specified driver.

Throws:


write_content

Write or append string contents or stream to file.

This function is an alternative for file_put_contents, it uses SplFileObject to write contents to file.

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

Parameters:

ParameterTypeDescription
$filenamestringPath to the file to write contents.
$contentstring|resourceThe contents to write to the file, either as a string or a stream resource.
$flagintThe value of flags can be combination of flags, joined with the binary OR (|) operator.
FILE_APPEND, LOCK_EX, FILE_USE_INCLUDE_PATH, FILE_APPEND, LOCK_NB, LOCK_SH, LOCK_UN
$contextresource[optional] A valid context resource created with stream_context_create.

Return Value:

boo - Return true if successful, otherwise false on failure.

Throws:

See Also

File Manager - Also checkout the documentation for file manager methods and usages.


get_content

Reads the content of a file with options for specifying the length of data to read and the starting offset.This function is an alternative for file_get_contents, it uses SplFileObject to open the file and read its contents.It can handle reading a specific number of bytes from a given offset in the file.

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

Parameters:

ParameterTypeDescription
$filenamestringThe path to the file to be read..
$lengthintThe maximum number of bytes to read, if set to 0, it read 8192 bytes at a time (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).
$contextresourceA context resource created with stream_context_create() (default: null)..

Return Value:

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

Throws:


make_dir

Attempts to create the directory specified by pathname if it does not exist.

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

Parameters:

ParameterTypeDescription
$pathstringThe path of the directory to create.
$permissionsint|nullOptional. The permissions for the directory. Defaults to null.
$recursiveboolOptional. Whether to create directories recursively. Defaults to true.

Return Value:

bool - Return true if files already existed or was created successfully, otherwise false.

Throws:

See Also

File Manager - Also checkout the documentation for file manager methods and usages.


get_temp_file

Retrieves the path for temporary files or generates a unique temporary file name.

This function can return either the path to a temporary directory or a unique temporary filename with an optional specified extension. If local is set to true, it will create the directory in the local writable path. If extension is provided, the returned filename will have that extension.

function get_temp_file(?string $prefix = null, ?string $extension = null, bool $local = false): string|false

Parameters:

ParameterTypeDescription
$prefixstring|nullOptional prefix for the temporary filename or a new sub-directory.
$extensionstring|nullOptional file extension for the temporary filename.
$localboolIndicates whether to use a local writable path (default: false).

Return Value:

string|false - Returns the path of the temporary directory, a unique temporary filename with the specified extension, or false on failure.


validate

Validate user input fields or get a validation instance.

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 on each filter on input field.

Return Value:

InputValidationInterface - Return validation instance if NULL is passed on $inputs or $rules.

See Also

Input Validations - Also checkout the documentation for input validation methods and usages.

Sample Usages

Assuming you have a post or get request like below:

    $inputs = [
        'name' => 'Peter',
        'email' => '[email protected]',
    ];

Configure validation rules as below:

$rules = [
   'name' => 'require|alphanumeric|max(50)',
   'email' => 'require|email'
];
$messages = [
   'name' => [
      'require' => 'Name is required',
      'alphanumeric' => 'Invalid name character',
      'max' => 'Invalid name cannot be more than 50 character'
   ],
   'email' => [
      'require' => 'Email is required',
      'email' => 'Invalid email address "{value}"'
   ]
];

// Validating request against rules.
$validation = Luminova\Funcs\validate($inputs, $rules, $messages);

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

start_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 start_url(?string $route = null, bool $relative = false): string

Parameters:

ParameterTypeDescription
$routestringOptional 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), with optionally pointing to a route or path.

This function will include hostname port (e.g, example.com:8080) if port available.And ensure URL always start from front controller.

Examples

echo Luminova\Funcs\start_url('about', relative: true); 

// On Development: /my-project-path/public/about
// In Production: /about

Assuming your application path is like: /Some/Path/To/htdocs/my-project-path/public/.

echo Luminova\Funcs\start_url('about', relative: false);

// Output

// On Development:
// - `https://localhost:8080/about`
// - `https://localhost/my-project-path/public/about`
// - `https://localhost/public/about`

// In Production:
// - `https://example.com:8080/about`
// - `https://example.com/about`

It returns depending on your development environment.


absolute_url

Convert an application-relative path to an absolute URL.

This function converts a given application path to its corresponding absolute URL.

function absolute_url(string $path): string

Parameters:

ParameterTypeDescription
$pathstringThe path to create absolute URL from.

Return Value:

string - Return the absolute URL of the specified path.

Examples:

Assuming your project path is: /Path/To/htdocs/project-path/public/.And assets path like: assets/files/foo.text.

On Development:

echo Luminova\Funcs\absolute_url('/Path/To/htdocs/project-path/public/assets/files/foo.text');

//Output: http://localhost/project-base/public/assets/files/foo.text.

In Production:

echo Luminova\Funcs\absolute_url('/var/www/example.com/public/assets/files/foo.text');

//Output: http://example.com/assets/files/foo.text.

ip_address

Retrieve the user's IP address or obtain IP address information using a third-party API service.

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

Parameters:

ParameterTypeDescription
$ipInfoboolIf true, returns IP address information; otherwise, returns the IP address.
$optionsarrayAdditional options to pass with IP information.

Return Value:

string|object|null - The IP address if $ipInfo is false, else return IP address information or null if IP address cannot be determined.

Utilize a third-party API to fetch IP address information. Your API configuration can be done in /app/Config/IPConfig.php.


get_class_name

Get class basename from namespace or class object.

function get_class_name(string|object $from): string

Parameters:

ParameterTypeDescription
$fromstring|class-objectThe namespace or class object.

Return Value:

string - Return the class basename.

Note: This method is not same as PHP get_class, this method return the base name of a class no full qualified class.


get_mime

Detect the MIME type of a file or raw data (e.g text/plain).

If the input string is a path to an existing file, it uses \finfo->file(), otherwise it treats the input as raw binary and uses \finfo->buffer().

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

Parameters:

ParameterTypeDescription
$inputstringFile path or raw binary string to extract mime from.
$magicDatabasestring|nullOptional path to a custom magic database (e.g, \path\custom.magic).

Return Value:

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


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 object or is returned.

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

Parameters:

ParameterTypeDescription
$fromarray|objectThe input collection of (objects or iterable object).
$propertynull|string|intThe key or property to extract from each item.
$indexnull|string|intOptional. A key/property to use as the array index for returned values.

Return Value:

object - Returns an object of extracted values. If $index is provided, it's used as the keys.

Examples:

$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 array_column() or Luminova object_column() to support both arrays and objects as well. If $property is null, the entire object or subarray 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 iterable object).
$propertynull|string|intThe key or property to extract from each item.
$indexnull|string|intOptional. A key/property to use as the array index for returned values.

Return Value:

array|object - Returns an array or object of extracted values. If $index is provided, it's used as the keys.

Examples:

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

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

Object Example:

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

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

filter_paths

Sanitize a file path for user-facing display by removing internal or sensitive directory segments.

This is useful when you want to hide full server paths (e.g., /var/www/html/) from end users.

function filter_paths(string $path): string

Parameters:

ParameterTypeDescription
$pathstringThe raw file system path to sanitize.

Return Value:

string - Return a cleaned and user-safe display path.

Example:

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

// Returns: 'writeable/storage/uploads/file.jpg'

This method is useful when you want to throw an exceptions, use it to remove your server path and return only path which should be seen by users.


to_array

Recursively convert an object (or mixed type) to an array.

function to_array(mixed $input): array

Parameters:

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

Return Value:

array - Return the array representation.

Example:

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

// Array ['a' => 1, 'b' => ['c' => 2]]

to_object

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

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

Parameters:

ParameterTypeDescription
$inputarray|stringInput array or listify string from Luminova\Components\Collections\Listifier (e.g, foo=bar,bar=2,baz=[1;2;3]).

Return Value:

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

Example:

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

// String Listifier

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

array_extend_default

This function is designed to merge two arrays, where the first array ($default) represents default values, and the second array ($new) contains updated or new values. The function recursively merges arrays for keys that exist in both arrays but leaves the default values untouched if 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.

Usage Examples:

use function Luminova\Funcs\array_extend_default;

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

$result = array_extend_default($default, $new);
print_r($result);

Output:

Array
(
   [a] => 1
   [b] => 2
   [c] => 3
   [d] => 4
)

array_merge_recursive_replace

This function is designed to merge multiple arrays recursively, but with a replacement strategy. If two arrays have the same key, the values in the second array will overwrite those in the first array. For numeric keys, it appends the values only if they don't already exist in the array.

public array_merge_recursive_replace(array ...$array): array

Parameters:

ParameterTypeDescription
...$arrayarrayThe array arguments to merge.

Return Value:

array - Return the merged result array.

Usage Examples:

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

$result = Luminova\Funcs\array_merge_recursive_replace($array1, $array2);
print_r($result);

Output:

Array
(
   [a] => 1
   [b] => 20
   [c] => 3
   [d] => 4
)

array_merge_recursive_distinct

This function is designed to merge two arrays ($array1 and $array2) in a way that is distinct from PHP's native array_merge_recursive. It avoids combining values under the same key as an array and instead replaces existing values if needed.

public array_merge_recursive_distinct(array &$array1, array &$array2): array

Parameters:

ParameterTypeDescription
$array1array<string|int,mixed>The array to merge into, passed by reference.
$array2array<string|int,mixed>The array to merge from, passed by reference.

Return Value:

array - Return the merged array with unique values.

Usage Examples:

$array1 = ['a' => 1, 'b' => 2];
$array2 = ['b' => 20, 'c' => 3];

$result = Luminova\Funcs\array_merge_recursive_distinct($array1, $array2);
print_r($result);

Output:

Array
(
   [a] => 1
   [b] => 20
   [c] => 3
)

array_merge_result

Merges a response into the provided results variable while optionally preserving the structure of nested arrays.

This function checks the type of the results variable and appropriately merges or appendsthe response based on its type. It supports various scenarios:

  • If results is null, it assigns response to it.
  • If results is an array and preserveNested is true, it adds the response as a nested element if response is an array, or appends response directly otherwise.
  • If results is an array and preserveNested is false, it merges results and response directly when response is an array.
  • If results is not an array (like a string or scalar), it converts results into an array and merges or appends the response based on the preserveNested flag.
public array_merge_result(mixed &$results, mixed $response, bool $preserveNested = true): void

Parameters:

ParameterTypeDescription
&$resultsmixedThe results variable to which the response will be merged or appended to, passed by reference.
$responsemixedThe response variable to merge with results. It can be an array, string, or other types.
$preserveNestedboolOptional. Determines whether to preserve the nested structure of arrays when merging (default: true).

Usage Examples:

$results = null;

// Case 1: Merging a new string response.
$response1 = 'Task 1 completed';
Luminova\Funcs\array_merge_result($results, $response1);

var_export($results);

// Case 2: Merging an array response while preserving the nested structure.
$response2 = ['Task 2 completed'];
Luminova\Funcs\array_merge_result($results, $response2);

var_export($results);

// Case 3: Merging another array response without preserving nested structure.
$response3 = ['Task 3 completed', 'Task 4 completed', (object)[1,2,3]];
Luminova\Funcs\array_merge_result($results, $response3, false);

var_export($results);

Output:

// Case 1: Output
'Task 1 completed'

// Case 2: Output
array (
   0 => 'Task 1 completed',
   1 => array (0 => 'Task 2 completed'),
)

// Case 3: Output
array (
   0 => 'Task 1 completed',
   1 =>  array (0 => 'Task 2 completed'),
   2 => 'Task 3 completed',
   3 => 'Task 4 completed',
   4 => (object) array(
      '0' => 1,
      '1' => 2,
      '2' => 3,
   ),
)

string_length

Calculate string length based on different charsets.

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

Parameters:

ParameterTypeDescription
$contentstringThe content to calculate length for.
$charsetstring|nullThe character set of the content.

Return Value:

int - Returns 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 $lower = true): string

Parameters:

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

Return Value:

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

Example:

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

camel_case

Convert a string to camel case.

function  camel_case(string $input): string

Parameters:

ParameterTypeDescription
$inputstringThe string to convert.

Return Value:

string - Return the string converted to camel case.

Example:

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

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:

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

which_php

Find the PHP script executable path.

function which_php(): ?string

Return Value:

string|null - Return PHP executable path or null.


status_code

Gets request status code from executed command or controller method.

function status_code(mixed $result = null, bool $returnInt = true): int|bool

Parameters:

ParameterTypeDescription
$resultmixedresponse from callback function or controller
$returnIntboolReturn type (default: int)

Return Value:

int|bool - Return the status code int or bool.

If passed result is boolean (false), integer (1) or NULL, the method will return STATUS_ERROR.

If passed result is boolean (true), integer (0), VOID or any other values, the method will return STATUS_SUCCESS.


http_status_header

Sets the HTTP response status code and sends appropriate headers.

This function sets the HTTP status code and sends the corresponding status message header.If the status code is not predefined, it returns false. For predefined status codes, it sends headers including the status message. The function determines the HTTP protocol version based on the server's protocol.

function http_status_header(int $status): bool

Parameters:

ParameterTypeDescription
$statusintThe HTTP status code to set (e.g., 200, 404).

Return Value:

bool - Returns true if the status code is found in the predefined list and headers are set, otherwise false.


text2html

Converts 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 processed text with HTML entities.


nl2html

Converts newline characters in a string to HTML entities.

function  nl2html(?string $text): string

This is useful when you want to display text in an HTML textarea while preserving the original line breaks.

Parameters:

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

Return Value:

string - Return processed text with HTML entities.


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 $string): bool

Parameters:

ParameterTypeDescription
$stringstringThe input string to convert.

Return Value:

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

Usage Example:

echo Luminova\Funcs\uppercase_words('foo-bar_baz');
// Output: // Foo-Bar_Baz

More Patterns:

$strings = [
   'foo-bar_baz'
   'hello-world_this_is_a_test'
   'example'
   '_leading_and_trailing_'
   '-leading-plus-trailing-'
   'multiple---dashes_and__underscores'
   'foo-bar baz_baz'
];

$results = array_map(['Luminova\Funcs\uppercase_words'], $strings);

// Print the results
echo implode("\n", $results);

Output:

Foo-Bar_Baz
Hello-World_This_Is_A_Test
Example
_Leading_And_Trailing_
-Leading-Plus-Trailing-
Multiple-Dashes_And_Underscores
Foo-Bar Baz_Baz

has_uppercase

Checks if a given string contains an uppercase letter.

function has_uppercase(string $string): bool

Parameters:

ParameterTypeDescription
$stringstringThe string to check uppercase.

Return Value:

bool - Returns true if the string has uppercase, false otherwise.


list_to_array

Convert a valid string list to an array.

The function uses Luminova\Components\Collections\Listifier to convert a string list format into an array.

function list_to_array(string $list): array|false

Parameters:

ParameterTypeDescription
$liststringThe string to convert.

Return Value:

array|false - Returns the parsed array, or false on failure.

Example:

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

In Luminova, a string list or Listifier typically consist of comma-separated values, which may or may not be enclosed in quotes (e.g, Foo, Bar, Baz, "Foo", "bar", "Baz").For more information refer to String List documentation


list_in_array

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

This function converts the list using list_to_array() and verifies all items exist in the 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 - Returns true if all list items exist in the array, false otherwise.

$list = 'Foo, Bar, Baz';

Luminova\Funcs\list_in_array($list, ['Foo', 'Bra']); // false

Luminova\Funcs\list_in_array($list, ['Foo', 'Baz', 'Bar']); // true

If any of the list value doesn't exist in the array, it will return false.For more information refer to String List documentation


is_list

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

Validates that the string matches a recognized list format used by Listifier.

function is_list(string $input): bool

Parameters:

ParameterTypeDescription
$inputstringThe string to validate.

Return Value:

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


is_platform

Tells which operating system platform your application is running on.

Predefine OS Values:

  • mac - For macOS.
  • windows - For Windows OS.
  • linux - For Linux OS.
  • freebsd - For FreeBSD OS.
  • openbsd - For OpenBSD OS.
  • bsd - For BSD OS.
  • solaris - For Solaris OS.
  • aws - For AWS OpsWorks.
  • azure - For Azure environment.
  • etc...
function is_platform(string $os): bool

Parameters:

ParameterTypeDescription
$osstringThe platform name to check.

Return Value:

bool - Return true if the application is running on the specified platform, false otherwise.


is_tor

Determines if the provided IP address corresponds to a Tor exit node.

function is_tor(?string $ip = null): bool

Parameters:

ParameterTypeDescription
$ipstring|nullThe IP address to check. If not provided, the current IP address is used.

Return Value:

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


is_empty

Check if any given values are considered empty.

Unlike PHP's native empty(), this treats 0 and '0' as not empty, but treats negative numbers, null, empty strings, arrays, or objects as empty.

This is a custom emptiness check that:

  • Treats 0 and '0' as not empty
  • Considers null, empty arrays, empty objects, empty strings, and negative numbers as empty
  • Handles Countable objects (e.g., ArrayObject)
function is_empty(mixed  $values): bool

Parameters:

ParameterTypeDescription
$valuesmixedOne or more values to evaluate.

Return Value:

bool - Returns true if any of the values are considered empty; false otherwise.

Example:

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

Note:This function treats 0 as non-empty.If you want different behavior, use the PHP empty() function instead.


is_nested

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

If $recursive is true, it checks all levels deeply; otherwise, it checks only one level.

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

Parameters:

ParameterTypeDescription
$arrayarrayThe array to check.
$recursiveboolWhether to check recursively (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:

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

Note: An empty array is considered as none nested array, so it 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:

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

is_command

Check if the application is running in command-line interface CLI mode.

function is_command(): bool

Return Value:bool - Returns true if the execution was made in CLI mode, false otherwise.


is_dev_server

Check if the application is running locally on any development environment.

function is_dev_server(): bool

Return Value:

bool - Returns true if the application is running on the development server, false otherwise.

This function utilizes server variable SERVER_NAME to check the server name matches any of 127.0.0.1 ::1 localhost.

Additionally it checks a custom Luminova server variable NOVAKIT_EXECUTION_ENV which is set when using builtin PHP development server.


is_blob

Determine whether the type of a variable is blob.

function is_blob(mixed $value): bool

Parameters:

ParameterTypeDescription
$valuemixedThe value to check.

Return Value:

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


is_utf8

Determine weather a given string is UTF-8 encoded.

function is_utf8(string $input): bool

Parameters:

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

Return Value:

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