PHP Luminova: Built-in Global Helper Functions
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?
Avoid RepetitionWrite a function once and reuse it anywhere in your project. No need to duplicate logic across files.
Speed Up DevelopmentHelpers handle common tasks like formatting, file paths, or date checks, letting you focus on your core logic.
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 existenv
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): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string | The environment variable key to retrieve. |
$default | mixed | Optional 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 missingIf 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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string | The key of the environment variable. |
$value | string | The value to assign. |
$persist | bool | If true, writes/updates the value in the .env file (default: false). |
Return Value:
bool — true 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,
setenvonly affects the current runtime.To permanently save the value in your.envfile, passtrueas 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
$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.
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\ApplicationParameters:
| Parameter | Type | Description |
|---|---|---|
$shared | bool | Whether to return the shared instance (default: true). |
$new | Luminova\Foundation\Core\Application | Optional 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
appfunction or grab the shared instance of your application byApplication::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): RequestInterfaceParameters:
| Parameter | Type | Description |
|---|---|---|
$shared | bool | Whether 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
): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string|null | Optional key to retrieve the data (default: null). |
$shared | bool | Whether to use shared instance (default: true). |
$manager | SessionManagerInterface | The 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.
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 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): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$function | 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.
- \Luminova\Exceptions\RuntimeException - If the function is disabled or does not exist.
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): ?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>|Factory|null - Return instance of factory class, instance of class called, otherwise null.
Throws:
- \Luminova\Exceptions\AppException - Throws an exception if factory context does not exist or 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\TranslatorfileManager- Returns instance ofLuminova\Storage\FileManagervalidate- Returns instance ofLuminova\Security\Validationresponse- Returns instance ofLuminova\Template\Responseservices- Returns instance ofApp\Config\Servicesrequest- Returns instance ofLuminova\Http\Requestnotification- Returns instance ofLuminova\Notifications\Firebase\Notificationcaller- Returns instance ofLuminova\Application\Callerescaper- Returns instance ofLuminova\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
): ?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 class (default: true). |
$serialize | bool | Whether to serialize and store class object as cache (default: false). |
$arguments | mixed | Additional parameters to pass to class constructor. |
Return Value:
class-object<\T>|Services|null - Return service class instance or instance of called class.
Throws:
\Luminova\Exceptions\AppException - Throws an exception if service does not exist or error occurs.
See Also
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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$service | class-string<\T>|string | The 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
NULLis 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\LayoutParameters:
| Parameter | Type | Description |
|---|---|---|
$file | string | Layout filename without the extension path. |
Return Value:
Luminova\Template\Layout - Returns the layout class instance.
Throws:
- \Luminova\Exceptions\RuntimeException -Throws if layout file is not found.
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')orlayout('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): ViewResponseInterfaceParameters:
| 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\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.nullor 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:
| Parameter | Type | Description |
|---|---|---|
$status | int | HTTP status code (default: 200 OK). |
$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: json, xml, text, or html (default: null). |
Throws:
- \Luminova\Exceptions\RuntimeException - If error occur while sending abort response.
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.nullor unrecognized: Attempt to detect content from $header (Content-Type) or $message (body).
function redirect(string $uri, ?string $method = null, int $status = 302): voidParameters:
| 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). |
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): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$fallback | string|null | RI to redirect to if no referer is found. |
$method | string\null | Redirection method (refresh or null for standard as default: null). |
$status | int | HTTP 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\ViewParameters:
| Parameter | Type | Description |
|---|---|---|
$template | string | Template file name or identifier. |
$status | int | Template 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/*.phpExamples:
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
viewglobal 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): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string | The key to identify the value. |
$value | mixed | The value to store (optional). |
$default | mixed | The 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'→ theUserAgentinstance itself.
function browser(?string $userAgent = null, string $return = 'object', bool $shared = true): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$userAgent | string|null | Optionally parse user agent string to analyze (default: null). |
$return | bool | The return type (default: object).- Return Types: [ array, object, instance] |
$shared | bool | If 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): 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 | Directory 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): 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 | Directory 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
$absoluteis 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): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$path | string|null | Optional subdirectory path to point from project root (e.g., writeable/logs). |
$filename | string|null | Optional 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.logNavigate 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.logNote:If you pass a filename as
$pathinstead 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): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$file | string|null | The 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 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 = false,
bool $once = true,
bool $require = true,
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: false). |
$once | bool | If true, load the file only once using *_once (default: true). |
$require | bool | If true, use require/require_once, otherwise use include/include_once (default: true). |
$scope | array<string,mixed> | Optional associative array of variables to extract into the file scope. (Keys become variable names). |
$promise | bool | Optionally 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:
- \Luminova\Exceptions\RuntimeException - If file doesn't exist and
$throwis true. - \Luminova\Exceptions\InvalidArgumentException - If
$scopeis not empty and not an associative array (list array given).
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; // 1234Import 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): 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 - Returns true if the library was successfully loaded, false otherwise.
Throws:
- \Luminova\Exceptions\RuntimeException - If the file is missing and $throw is true.
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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$function | string | The 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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$class | string | The name of the class to check for existence. |
$autoload | bool | Whether 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 = []): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$destination | string | The destination to send log (e.g, Log level, email, or URL endpoint). |
$message | string | The message to log. |
$context | array | Optional 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 forAPIs.
Throws:
- \Luminova\Exceptions\InvalidArgumentException -If the target is invalid or logging fails.
Note:It uses the configured preferred PSR logger class if define in
App\Config\Preference, otherwise it will use defaultLuminova\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|boolParameters:
| Parameter | Type | Description |
|---|---|---|
$locale | ?string | Optional 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:
| Parameter | Type | Description |
|---|---|---|
$version | int | The version of the UUID to generate (default: 4).. |
$namespace | string|null | The namespace for versions 3 and 5. |
$name | string|null | The name for versions 3 and 5. |
Return Value:
string -Return the generated UUID string.
Throws:
- \Luminova\Exceptions\InvalidArgumentException - f the namespace or name is not provided for versions 3 or 5.
Note:To check if
UUIDis 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 outputjs– Escape for JavaScript stringscss– Escape for CSS valuesurl– Escape for URLsattr– Escape for HTML attributesraw– No escaping, output as-is
function escape(
string|array $input,
string $context = 'html',
?string $encoding = 'utf-8'
): array|stringParameters:
| Parameter | Type | Description |
|---|---|---|
$input | string|array|null | The string or array of strings to be escaped. |
$context | string | The escaper context in which the escaping should be performed (default:'html'). |
$encoding | string|null | The escape character encoding to use (default: 'utf-8'). |
Throws:
- \Luminova\Exceptions\InvalidArgumentException - When an invalid, blank encoding is provided or unsupported encoding or empty string is provided.
- \Luminova\Exceptions\BadMethodCallException - When an invalid context is called.
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: <script>alert("xss")</script>
// Escape URL
$url = escape('https://example.com/?q=<script>', 'url');
// Output: https%3A%2F%2Fexample.com%2F%3Fq%3D%3Cscript%3EArray 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' => '<b>Bold</b>',
'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:
[
'<b>Bold</b>',
'<script>alert("xss")</script>'
]
*/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 = ''): ?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: '' 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:
- \Luminova\Exceptions\InvalidArgumentException - If input contains disallowed characters and
$replacementis set tonull.
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'): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$input | string | The string to validate strictly. |
$type | string | The expected data type (e.g., int, email, username). |
Return Value:
string - Return sanitized string.
Throws:
- \Luminova\Exceptions\InvalidArgumentException - If the input contains invalid characters for the specified type.
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 = []): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$lookup | string | The key to lookup in the translation files. |
$default | string|null | The default fallback translation if not found. |
$locale | string|null | The locale to use for translation (optional). |
$placeholders | array | Matching placeholders for translation. |
Return Value:string - Return the translated text.
Throws:
- \Luminova\Exceptions\NotFoundException - If translation is not found and no default is provided.
To create a language translations you need to define it in
/app/Languages/.The file name format should be like
Example.en.php, where theExampleis the context andenis 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 errorecho 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@123configs
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 - Returns the configuration array or the default value.
Throws:
- \Luminova\Exceptions\UnexpectedValueException - If loaded file does not return an array.
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\CacheParameters:
| Parameter | Type | Description |
|---|---|---|
$driver | string | The cache driver to return instance of [filesystem or memcached](default: filesystem). |
$storage | string|null | The name of the cache storage. If null, you must call the setStorage method later (default: null). |
$persistentIdOrSubfolder | string|null | Optional 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
defaultif 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:
- \Luminova\Exceptions\ClassException - If 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.
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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$filename | string | Path to the file to write contents. |
$content | string|resource | The contents to write to the file, either as a string or a stream resource. |
$flag | int | The 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 |
$context | resource | [optional] A valid context resource created with stream_context_create. |
Return Value:
boo - Return true if successful, otherwise false on failure.
Throws:
- \Luminova\Exceptions\FileException - If unable to write file.
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:
| Parameter | Type | Description |
|---|---|---|
$filename | string | The path to the file to be read.. |
$length | int | The maximum number of bytes to read, if set to 0, it read 8192 bytes at a time (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 | A 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:
- \Luminova\Exceptions\FileException - If unable to write file.
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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$path | string | The path of the directory to create. |
$permissions | int|null | Optional. The permissions for the directory. Defaults to null. |
$recursive | bool | Optional. Whether to create directories recursively. Defaults to true. |
Return Value:
bool - Return true if files already existed or was created successfully, otherwise false.
Throws:
- \Luminova\Exceptions\FileException - If unable to create directory.
- \Luminova\Exceptions\RuntimeException - If the path is not readable.
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|falseParameters:
| Parameter | Type | Description |
|---|---|---|
$prefix | string|null | Optional prefix for the temporary filename or a new sub-directory. |
$extension | string|null | Optional file extension for the temporary filename. |
$local | bool | Indicates 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\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 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): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$route | string | 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), 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: /aboutAssuming 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): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$path | string | The 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|nullParameters:
| Parameter | Type | Description |
|---|---|---|
$ipInfo | bool | If true, returns IP address information; otherwise, returns the IP address. |
$options | array | Additional 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): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$from | string|class-object | The 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|falseParameters:
| Parameter | Type | Description |
|---|---|---|
$input | string | File path or raw binary string to extract mime from. |
$magicDatabase | string|null | Optional 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): objectParameters:
| Parameter | Type | Description |
|---|---|---|
$from | array|object | The input collection of (objects or iterable object). |
$property | null|string|int | The key or property to extract from each item. |
$index | null|string|int | Optional. 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:
| Parameter | Type | Description |
|---|---|---|
$from | array|object | The input collection (array of arrays/objects or iterable object). |
$property | null|string|int | The key or property to extract from each item. |
$index | null|string|int | Optional. 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): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$path | string | The 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): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$input | mixed | The 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|falseParameters:
| Parameter | Type | Description |
|---|---|---|
$input | array|string | Input 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): 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.
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): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
...$array | array | The 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): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$array1 | array<string|int,mixed> | The array to merge into, passed by reference. |
$array2 | array<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
resultsis null, it assignsresponseto it. - If
resultsis an array andpreserveNestedis true, it adds theresponseas a nested element ifresponseis an array, or appendsresponsedirectly otherwise. - If
resultsis an array andpreserveNestedis false, it mergesresultsandresponsedirectly whenresponseis an array. - If
resultsis not an array (like a string or scalar), it convertsresultsinto an array and merges or appends theresponsebased on thepreserveNestedflag.
public array_merge_result(mixed &$results, mixed $response, bool $preserveNested = true): voidParameters:
| Parameter | Type | Description |
|---|---|---|
&$results | mixed | The results variable to which the response will be merged or appended to, passed by reference. |
$response | mixed | The response variable to merge with results. It can be an array, string, or other types. |
$preserveNested | bool | Optional. 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): intParameters:
| Parameter | Type | Description |
|---|---|---|
$content | string | The content to calculate length for. |
$charset | string|null | The 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): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$input | string | The input string to convert. |
$lower | bool | Whether 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-worlDcamel_case
Convert a string to camel case.
function camel_case(string $input): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$input | string | The 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'); // helloWoldpascal_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:
echo pascal_case('hello world'); // HelloWold
echo pascal_case('hello-world'); // HelloWoldwhich_php
Find the PHP script executable path.
function which_php(): ?stringReturn 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|boolParameters:
| Parameter | Type | Description |
|---|---|---|
$result | mixed | response from callback function or controller |
$returnInt | bool | Return type (default: int) |
Return Value:
int|bool - Return the status code int or bool.
If passed result is
boolean(false),integer(1) orNULL, the method will returnSTATUS_ERROR.If passed result is
boolean(true),integer(0),VOIDor any other values, the method will returnSTATUS_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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$status | int | The 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): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$text | string|null | A 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): stringThis is useful when you want to display text in an HTML textarea while preserving the original line breaks.
Parameters:
| Parameter | Type | Description |
|---|---|---|
$text | string|null | A 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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$string | string | The 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_BazMore 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_Bazhas_uppercase
Checks if a given string contains an uppercase letter.
function has_uppercase(string $string): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$string | string | The 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|falseParameters:
| Parameter | Type | Description |
|---|---|---|
$list | string | The 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
listorListifiertypically 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 = []): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$list | string | The string list to check. |
$array | array | The 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']); // trueIf 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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$input | string | The 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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$os | string | The 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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$ip | string|null | The 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
0and'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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$values | mixed | One 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)[]); // trueNote: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:
| Parameter | Type | Description |
|---|---|---|
$array | array | The array to check. |
$recursive | bool | Whether to check recursively (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:
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); // trueNote: 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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$array | array | The 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([]); // falseis_command
Check if the application is running in command-line interface CLI mode.
function is_command(): boolReturn 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(): boolReturn Value:
bool - Returns true if the application is running on the development server, false otherwise.
This function utilizes server variable
SERVER_NAMEto check the server name matches any of127.0.0.1::1localhost.Additionally it checks a custom Luminova server variable
NOVAKIT_EXECUTION_ENVwhich is set when using builtinPHPdevelopment server.
is_blob
Determine whether the type of a variable is blob.
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 blob, false otherwise.
is_utf8
Determine weather a given string is UTF-8 encoded.
function is_utf8(string $input): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$input | string | The string to check for UTF-8 encoding. |
Return Value:
bool - Returns true if the string is UTF-8 encoded, false otherwise.