Luminova Framework

PHP Luminova: Global Utility Helper Functions

Last updated: 2024-08-28 21:43:23

Global helper functions are collections of procedural functions that provide commonly used functionality across different parts of your application enhancing code reusability and productivity.

Global helper functions are procedural functions that provide commonly used functionality across different parts of your application. They are typically defined at the global scope, making them easily accessible from anywhere within the codebase.

Code Reusability

By encapsulating commonly used operations into helper functions, developers can avoid repetitive code and promote code reuse.

Productivity

Helper functions can significantly improve development efficiency by providing pre-built solutions to common problems. Instead of reinventing the wheel each time a similar task needs to be performed.

Abstraction of Complexity

Helper functions abstract away the complexity of certain operations, making the code-base more readable and maintainable. By encapsulating logics within well-named functions, developers can focus on the high-level functionality of their code without getting bogged down in implementation details.


Functions

app

Get application container class shared instance or new instance if not shared.

function app(): \App\Application

Return Value:

\App\Application - Return application shared instance.

See Also

Core Application - See the documentation for base application methods and usages.

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


request

Get the HTTP request object.

function request(bool $shared = true): ?\Luminova\Http\Request

Parameters:

ParameterTypeDescription
$sharedboolReturn a shared instance (default: true).

Return Value:

class-object<Request>||null - Return request object or null.

See Also

HTTP Request - See the 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).
$sharedboolWeather to use shared instance (default: true).
$managerclass-object<\SessionManagerInterface>|nullThe session manager interface to use (default: SessionManager).

Return Value:

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

See Also

Session Manager - See the documentation for session methods.


Create and return a cookie instance.

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

Parameters:

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

Return Value:

Cookie - Return new cookie instance.

See Also

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


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|null $context = null, bool $shared = true, mixed ...$arguments): ?object

Parameters:

ParameterTypeDescription
$contextstring|nullThe factory context name, e.g: session. (default: null).
$sharedboolWeather 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\Base\CoreFunction
  • 'modules' - Returns instance of \Luminova\Library\Modules
  • 'language' - Returns instance of \Luminova\Languages\Translator
  • 'logger' - Returns instance of \Luminova\Logger\Logger
  • 'fileManager' - Returns instance of \Luminova\Storages\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\Functions\Escape

Example

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

<?php 
$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(class-string<\T>|string|null $service = null, bool $shared = true, bool $serialize = false, mixed ...$arguments): ?object

Parameters:

ParameterTypeDescription
$serviceclass-string<\T>|string|nullThe service class name or alias.
$sharedboolWeather to return a shared instance of class (default: true).
$serializeboolWeather 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(class-string<\T>|string|null  $service = null): bool

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

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.


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

Initiate a view response object and render any response content.It allows you to render content of any format in view or download content within the view controller.

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

Parameters:

ParameterTypeDescription
$statusintHTTP status code (default: 200 OK)
$headersarray<string,mixed>|nullAdditional response headers (default: null).
$encodeboolEnable content encoding like gzip, deflate (default: true).
$sharedboolWeather to return shared instance (default: true).

Return Value:

ViewResponse - Return vew response object.

See Also

View Response - Also checkout the documentation for view response methods and usages.


func

Return instance a specific context if specified, otherwise get the instance anonymous class which extended CoreFunction.

function func(string|null $context = null, mixed ...$arguments): mixed

Parameters:

ParameterTypeDescription
$contextstring|nullThe context to return it's instance (default: null).
$argumentsmixed[, mixed $... ] Optional initialization arguments based on context.

Supported contexts:

  • ip - Return instance of Luminova\Functions\IP.
  • document - Return instance of Luminova\Functions\IP.
  • tor - Return instance of Luminova\Functions\Tor,
  • math - Return instance of Luminova\Functions\Maths.

Return Value:

class-object<CoreFunction>|class-object<\T>|mixed - Returns an instance of Functions, object, string, or boolean value depending on the context.

Throws:

See Also

Core Functions - Learn more about the Luminova's CoreFunction documentation.


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 the information about user's browser, based on the user-agent string.

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

Parameters:

ParameterTypeDescription
$user_agentstring|nullThe user agent string to analyze.
$returnboolSet the return type, if instance return userAgent class object otherwise return array or json object.
- Return Types: [array, object, instance]
$sharedboolAllow shared instance creation (default: true).

Return Value:

array<string,mixed>|object<string,mixed>|UserAgent|false - An array, object containing browser information or user-agent class instance.

See Also

User Agents - See the documentation for browser user-agent methods and usages.


href

Create a hyperlink to another view or file.This function creates a link to a view or file, ensuring the base starts from your application's public document root.

function href(?string $view = null, bool $absolute = false): string 

Parameters:

ParameterTypeDescription
$viewstring|nullThe view path or file to create the link for (default: null).
If null, an empty string is used.
$absoluteboolWhether to use an absolute URL (default: false).

Return Value:

string - Return link of view, If $absolute is true, the absolute URL is returned; otherwise, a relative URL is returned.

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.


asset

Create a link to a file in the assets folder.This function generates a URL to a file within the assets folder, ensuring the base starts from your application's public document root.

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

Parameters:

ParameterTypeDescription
$filenamestring|nullThe filename or path within the assets folder (default: null).
If null, an empty string is used.
$absoluteboolWhether to use an absolute URL (default: false).

Return Value:

string - Return asset link of view, If $absolute is true, the absolute URL is returned; otherwise, a relative URL is returned.


root

Get the application root directory of your project anywhere, optionally pass a path to append the the root directory, all return path will be converted to unix or windows directory separator style.

function root(?string $suffix = null): string

Parameters:

ParameterTypeDescription
$suffixstring|nullOptional suffix to prepend to the root directory.

Return Value:

string - Return application document root, and optional appended suffix.


path

Get system or application path, compatible with unix or windows directory separator style.

function path(string $file): string

Parameters:

ParameterTypeDescription
$filestring|nullThe path file name to return.
Possible values: 'app', 'system', 'plugins', 'library', 'controllers', 'writeable', 'logs', 'caches',
'public', 'assets', 'views', 'routes', 'languages', 'services'.

Return Value:

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

See Also

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


env

Get environment variable value from registered ENV variables, its a wrapper that combines both $_ENV, $_SERVER and getenv, with an additional feature to ensure the accuracy of the return type and default value if the key was not found in the environment.

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

Parameters:

ParameterTypeDescription
$keystringThe environment variable key to retrieve..
$defaultmixedOptional default value to return if the key is not found (default: null).

Return Value:

mixed - Return the value of the specified environment key or default value if not found.

See Also

Environment Variables - Learn more from documentation about Luminova's env variable keys.

If your variable value is like: foo = [1, 2, 4], this function will return an array representation of the value.


setenv

Set an environment variable if it doesn't already exist.

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

Parameters:

ParameterTypeDescription
$keystringThe key of the environment variable.
$valuestringThe value of the environment variable.
$append_to_envboolWeather to save or update the value in .env file (default: false).

Return Value:

bool - Return true on success, otherwise false on failure.

By default when you set an environment variable, it doesn't permanently stored in other to access it in entire code-base.

If you wish to write the key and value in your environment variables file .env, then you must specify the third argument true.

More efficient method of doing this is by utilizing the NovaKit Command to write the key and value to env file. using command php novakit env:add --key="my_new_key" --value="my key value".


import

Import a custom library into your project.

function  import(string $library): bool

Parameters:

ParameterTypeDescription
$librarystringThe name of the library.

Throws:

Return Value:

bool - Return true if the library was successfully imported.

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


logger

To log a message with a given log level.This function uses your prefered psr logger class if define otherwise it will use default NovaLogger.

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

Parameters:

ParameterTypeDescription
$levelstringThe log level.
$messagestringThe log message.
$contextarrayAdditional context data (optional).

Log levels

  • emergency - Log an emergency errors.
  • alert - Log an alert message .
  • critical - Log a critical errors.
  • error - Log an error message.
  • warning - Log a warning message.
  • notice - Log a notice.
  • info - Log an info message.
  • debug - Log debugging information.
  • exception - Log an exceptions.
  • php_errors - Log PHP errors.

Throws:

All loges are located in /writeable/log/, each log level has it own file name (e.x., warning.log).

To set your own logging handler class, it can be done in App\Config\Preference, your logger must implement PSR logger interface.


locale

Set application locale or return current application local.

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

Parameters:

ParameterTypeDescription
$locale?stringThe locale to set.

Return Value:

string|bool - If locale is passed it will set it and return true, else return previous locale.


uuid

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:

To check if UUID is valid use func()->isUuid(string, version)


escape

Escapes a string or array of strings based on the specified context.

This is particularly useful when dealing with escaping and sanitizing inputs and output to prevent cross-site scripting (XSS) and other injection attacks, the escape context parameter accept values like html, js, css, url, attr, and raw are used to specify the context in which the data is being output. Each context requires different escaping rules to ensure the output is safe.

function escape(string|array $input, string $context = 'html', string|null $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.

Input Argument

  • Associative Array array<string, string>: Use the keys of the array to specify the escape context for each value. Each key-value pair determines the context in which the corresponding value should be escaped.

  • Indexed Array array<int, string>: Apply the default escape context to all values in the array. The default context will be used for escaping each value uniformly.

Supported Context

Context names and a brief explanation of each:

  1. html:

    • Purpose: Escapes characters that could be interpreted as HTML tags or entities. It replaces characters like <, >, and & with their corresponding HTML entities (&lt;, &gt;, &amp;), ensuring that they are displayed as plain text and not interpreted as HTML.
  2. js:

    • Purpose: Escapes characters that have special meanings in JavaScript, such as quotes and backslashes, to prevent injection attacks when inserting data into JavaScript strings or variables.
  3. css:

    • Purpose: Escapes characters that could affect CSS styling or lead to CSS injection attacks, such as special characters in style attributes or css rules.
  4. url:

    • Purpose: Escapes characters that are not valid in URLs or could break URL structure. This ensures that user-provided data included in URLs does not lead to unexpected behavior or vulnerabilities.
  5. attr:

    • Purpose: Escapes characters that could interfere with HTML attributes, such as quotes and angle brackets, to prevent breaking out of the attribute value or introducing additional attributes.
  6. raw:

    • Purpose: No escaping is applied; the data is output as-is. This is used when you are certain that the data is safe and does not need to be sanitized.

strict

Sanitize user input by removing disallowed characters, retaining only those permitted. Unlike the escape function, which encodes characters for safe output, the strict function replaces unwanted characters in the input string with $replacer and returns the sanitized value. This method is particularly useful when you need to enforce strict input validation, ensuring that only expected characters are present.

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

Parameters:

ParameterTypeDescription
$inputstringThe input string to be sanitized.
$typestringThe expected input filter type.
$replacerstringThe symbol to replace disallowed characters with (default: blank string).

Filters Types

  • int: Accepts only integer values.
  • digit: Accepts only digit values including decimals and negatives.
  • key: Accepts only alphanumeric characters, underscores, and dashes.
  • password: Accepts alphanumeric characters, underscores, dashes, and special characters: @, !, *, and _.
  • username: Accepts alphanumeric characters, underscores, dashes, and periods.
  • email: Accepts valid email addresses containing alphanumeric characters, underscores, dashes, periods, and @.
  • url: Accepts valid URLs containing alphanumeric characters, underscores, dashes, periods, question marks, hashtags, ampersands, plus signs, equal signs, colons, slashes, and spaces.
  • money: Accepts only numeric values, including decimals and negative numbers.
  • double: Accepts only numeric values, including decimals.
  • alphabet: Accepts only alphabetical characters (uppercase and lowercase).
  • phone: Accepts only phone numbers containing numeric characters, dashes, and plus signs.
  • name: Accepts names containing letters, digits, spaces, underscores, periods, apostrophes, and hyphens.
  • timezone: Accepts valid timezone strings containing alphanumeric characters, underscores, dashes, commas, colons, plus signs, and spaces.
  • time: Accepts valid time strings containing alphanumeric characters, dashes, colons, and spaces.
  • date: Accepts valid date strings containing alphanumeric characters, dashes, colons, slashes, commas, and spaces.
  • uuid: Accepts valid UUID strings in the format: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX.
  • default: Removes any HTML tags from the input string.

Return Value:

string - Return sanitized string.


lang

Translate multiple languages with support for nested arrays.

function lang(string $lookup, string|null $default = null, string|null $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 - 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.

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

configs

Retrieves the configurations for the specified context.This function can only be use to return configuration array stored in app/Configs/ directory.

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

Parameters:

ParameterTypeDescription
$filenamestringThe configuration filename (without extension).
$defaultarray|nullThe default configuration if file could not be load (default: null).

Return Value:

array|null - Return array of the configurations for the filename, or false if not found.


cache

Initialize or retrieve a new instance of the cache class.

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

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\BaseCache - 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, string|resource  $content, int  $flag, resource $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,  $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|null  $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.


validate

Validate user input fields or get a validation instance.

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

Parameters:

ParameterTypeDescription
$inputsarray|nullInput fields to validate.
@example [$_POST, $_GET or $this->request->getBody()]
$rulesarray|nullValidation filter rules to apply on each input field.
@example ['email' => 'required|email|max|min|length']
$messagesarrayValidation error messages to apply on each filter on input field.
@example [
'email' => [
'required' => 'email is required',
'email' => 'Invalid [value] while validating [rule] on [field]'
]
]

Return Value:

ValidationInterface - 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:

<?php 
    $inputs = [
        'name' => 'Peter',
        'email' => '[email protected]',
    ];
Configure validation rules as below:

```php
$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.

```php
    $validation = validate($inputs, $rules, array $messages);

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

start_url

Get the start URL with an optional suffix and port hostname if available.This function generates the base URL of the application, optionally appending a provided suffix. It includes the port hostname if available.

function start_url(?string $suffix = null): string

Parameters:

ParameterTypeDescription
$suffixstringOptional suffix to append to the start URL (default: null).

Return Value:

string Return the generated start URL of your project.

ExampleIf your application path is like: /Some/Path/To/htdocs/my-project-path/public/.It returns depending on your development environment and suffix if specified:

  • https://localhost:8080
  • https://localhost/my-project-path/public/
  • https://localhost/public
  • https://example.com:8080
  • https://example.com/

If the application is in production (PRODUCTION), it returns the base application URL (APP_URL) with the optional suffix.If not in production, it constructs the URL using the server's hostname and the PROJECT_ID, and appends the optional suffix.


absolute_url

Convert an application-relative path to an absolute URL.This function converts a given application-relative path to its corresponding absolute URL.

function absolute_url(string $path): string

Parameters:

ParameterTypeDescription
$pathstringThe relative path to convert to an absolute URL.

Return Value:

string - Return the absolute URL of the specified path.

Examples:

If on development environment.

<?php 
echo absolute_url('/Applications/XAMPP/htdocs/project-base/public/asset/files/foo.text');
//Output: http://localhost/project-base/public/asset/files/foo.text.

If on projection environment.

<?php 
echo absolute_url('/example.com/www/public/asset/files/foo.text');
//Output: http://example.com/asset/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 $ip_info = false, array $options = []): string|object|null

Parameters:

ParameterTypeDescription
$ip_infoboolIf 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 $ip_info 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 MIME content type of a given file, (e.g text/plain).

function get_mime(string $filename): string|false

Parameters:

ParameterTypeDescription
$filenamestringThe full file path.

Return Value:

string|false - Return the content type in MIME format, otherwise false.


get_column

Return the values from a single column in the input array or an object.

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

Parameters:

ParameterTypeDescription
$fromarray|objectArray or an object to extract column values from.
$propertynull|string|intThe column property key to extract.
$indexnull|string|intAn optional column to use as the index/keys for the returned array.

Return Value:

array - Returns an array of values representing a single column from the input array or object.

This function is a wrapper for PHP array_column, but with additional optimization to handle both object or an array column.


filter_paths

Filter the display path, to remove private directory paths before previewing to users.

function filter_paths(string $path): string

Parameters:

ParameterTypeDescription
$pathstringThe path to be filtered.

Return Value:

string - Return the filtered path.

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

Convert an object to an array.

function to_array(mixed  $input): array

Parameters:

ParameterTypeDescription
$inputmixedThe object to convert to an array.

Return Value:

array - The finalized array representation of the object.


to_object

Convert an array or string list to a JSON object.

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

Parameters:

ParameterTypeDescription
$inputarray|stringThe array or string list to convert.

Return Value:

object|false - Return JSON object, otherwise false.


array_merge_recursive_distinct

Recursively merges two arrays, ensuring unique values in nested arrays.The first array will be updated with values from the second array.

public static 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.


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.

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

Parameters:

ParameterTypeDescription
$inputstringString to convert to kebab cased.
$lowerboolShould convert to lower case (default: true).

Return Value:

string - Return the kebab-cased string.


camel_case

Convert a string to camel case.

function  camel_case(string  $input): string

Parameters:

ParameterTypeDescription
$inputstringThe string to convert

Return Value:

string - Return string. as camel cased.


which_php

Find the PHP script executable path.

function which_php(): string|null

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 $return_int = true): int|bool

Parameters:

ParameterTypeDescription
$resultmixedresponse from callback function or controller
$return_intboolReturn 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|null  $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|null  $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.


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 string list to an array.

function list_to_array(string $list): array|false

Parameters:

ParameterTypeDescription
$liststringThe string list to convert.

Return Value:

array|false - The resulting array or false on failure.

In Luminova, a string list typically consist of comma-separated values, which may or may not be enclosed in quotes.

Examples: Foo, Bar, Baz, "Foo", "bar", "Baz"


list_in_array

Check if string list exists, matched an array.

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

Parameters:

ParameterTypeDescription
$liststringThe string list to check.
$arrayarrayThe array to search for list value.

Return Value:

bool - Return true if the list exists in the array, otherwise false.

<?php
$list = "Foo, Bar, Baz";

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

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

If any of the list value doesn't exist in the array, it will return false.


is_list

Test if a string is in a valid list format.

function is_list(string $input, bool $trim = false): bool

Parameters:

ParameterTypeDescription
$inputstringThe string to check.
$trimboolWhether to trim whitespace around the values.

Return Value:

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


is_platform

Tells which platform your application is running on.

function is_platform(string $os): bool

Parameters:

ParameterTypeDescription
$osstringThe platform name (e.g., 'mac', 'windows', 'linux', 'freebsd', 'openbsd', 'solaris', 'aws', etc.).

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|null $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 values are empty.

function is_empty(mixed  $values): bool

Parameters:

ParameterTypeDescription
$valuesmixedThe values to check.

Return Value:

bool - True if any of the values are empty, false otherwise.

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 a nested array.If recursive is false it only checks one level of depth.

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

Parameters:

ParameterTypeDescription
$arrayarrayThe array to check.
$recursiveboolDetermines whether to check nested array values (default: false).

Return Value:

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

Note:An empty array is considered as none nested array, so it will return false.


is_associative

Determine if an array is associative.

function is_associative(array $array): bool

Parameters:

ParameterTypeDescription
$arrayarrayThe array to check.

Return Value:

bool - True if the array is associative, false otherwise.


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.


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.