Oihana PHP System

helpers

Table of Contents

Functions

applyContentHeaders()  : ResponseInterface
Applies the download content headers (`Content-Type`, `Content-Length`, `Content-Disposition`) to a PSR-7 response, toggled by {@see FileResponseOption}.
computeETag()  : string
Computes an HTTP entity tag (`ETag`) validator for a file.
etagMatches()  : bool
Tells whether an `If-None-Match` header value matches a given `ETag`.
filterLanguages()  : array<string, string|null>|null
Filter an array or object of translations according to the given or available languages.
getBodyParam()  : mixed
Retrieves a single parameter from the HTTP request body.
getBodyParams()  : array<string|int, mixed>
Retrieves multiple parameters from the HTTP request body.
getController()  : Controller|null
Retrieves a controller instance from a PSR-11 container if available.
getParam()  : mixed
Retrieves a parameter from the HTTP request, supporting query string, body, or both.
getParamArray()  : array<string|int, mixed>|null
Retrieves a parameter from the HTTP request and ensures it is an array.
getParamBool()  : bool|null
Retrieves a parameter from the HTTP request and converts it to a boolean.
getParamFloat()  : float|null
Retrieves a parameter from the HTTP request and ensures it is a float number.
getParamFloatRange()  : float|null
Retrieves a float parameter from the request and clamps it within a given range.
getParamI18n()  : array<string|int, mixed>|null
Retrieves an i18n parameter from the HTTP request, optionally filtered by allowed languages.
getParamInt()  : int|null
Retrieves a parameter from the HTTP request and ensures it is a int number.
getParamIntRange()  : int|null
Retrieves an integer parameter from the request and clamps it within a given range.
getParamNumberRange()  : int|float|null
Retrieves a numeric parameter from the request and clamps it within a given range.
getParamString()  : string|null
Retrieves a parameter from the HTTP request and ensures it is a string.
getQueryParam()  : mixed
Retrieves a single parameter from the HTTP request query string.
parseRangeHeader()  : array{0: int, 1: int}|false|null
Parses an HTTP `Range` header into a single satisfiable byte interval.
translate()  : mixed
Retrieve the translation for a specific language, with optional fallback to a default language.

Functions

applyContentHeaders()

Applies the download content headers (`Content-Type`, `Content-Length`, `Content-Disposition`) to a PSR-7 response, toggled by {@see FileResponseOption}.

applyContentHeaders(ResponseInterface $response, string $file[, string|null $contentType = null ][, array<string|int, mixed> $options = [] ][, bool $defaultOn = true ]) : ResponseInterface

Shared by the file/archive/image/encryption response helpers so the header logic lives in one place.

Parameters
$response : ResponseInterface

The PSR-7 response to decorate.

$file : string

Path of the file whose size/MIME type back the headers (must exist).

$contentType : string|null = null

The Content-Type to advertise; when null, mime_content_type($file) is used.

$options : array<string|int, mixed> = []

Header switches keyed by FileResponseOption:

  • useContentType (bool) emit Content-Type.
  • useContentLength (bool) emit Content-Length (file size).
  • useContentDisposition (bool) emit Content-Disposition.
  • contentDisposition (string) value to use (defaults to attachment; filename=<basename>).
$defaultOn : bool = true

Default state of the three switches when absent from $options.

Tags
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
ResponseInterface

The response with the requested headers applied.

computeETag()

Computes an HTTP entity tag (`ETag`) validator for a file.

computeETag(string $file[, bool $weak = false ][, bool $hashContent = false ]) : string

By default the tag is derived from the file metadata (mtime-size, in hexadecimal) so no content read is required — this keeps large-file streaming cheap. Pass $hashContent = true to build an exact, byte-level tag from md5_file() instead (reads the whole file).

The returned value is a quoted opaque tag, prefixed with W/ when $weak is true.

Parameters
$file : string

Absolute path of the file (must exist).

$weak : bool = false

Emit a weak validator (W/"...") instead of a strong one.

$hashContent : bool = false

Derive the tag from the file content (md5_file()) instead of its metadata.

Tags
author

Marc Alcaraz (ekameleon)

since
1.0.0
example
computeETag( '/var/data/file.bin' ) ;                       // "<mtime-hex>-<size-hex>" (strong, metadata)
computeETag( '/var/data/file.bin' , weak: true ) ;          // W/"<mtime-hex>-<size-hex>"
computeETag( '/var/data/file.bin' , hashContent: true ) ;   // "<md5>" (strong, exact)
Return values
string

The ETag value, e.g. "18f-3e8" or W/"18f-3e8".

etagMatches()

Tells whether an `If-None-Match` header value matches a given `ETag`.

etagMatches(string $header, string $etag) : bool

Implements the RFC 7232 §3.2 semantics used for If-None-Match:

  • * matches any current representation;
  • otherwise the header is a comma-separated list of entity tags, compared with the weak comparison function — the W/ prefix is ignored on both sides, so W/"x" and "x" are considered a match.
Parameters
$header : string

The raw If-None-Match header value.

$etag : string

The current ETag of the resource (as produced by computeETag()).

Tags
author

Marc Alcaraz (ekameleon)

since
1.0.0
example
etagMatches( '*'             , '"abc"' ) ; // true  (matches any representation)
etagMatches( '"abc", "def"'  , '"abc"' ) ; // true  (present in the list)
etagMatches( 'W/"abc"'       , '"abc"' ) ; // true  (weak comparison)
etagMatches( '"xyz"'         , '"abc"' ) ; // false (no match)
etagMatches( ''              , '"abc"' ) ; // false (no precondition)
Return values
bool

true when the precondition matches (the caller should answer 304 Not Modified).

filterLanguages()

Filter an array or object of translations according to the given or available languages.

filterLanguages(mixed $fields[, array<string|int, string>|null $languages = null ][, callable|null $sanitize = null ]) : array<string, string|null>|null

This helper transforms an input array/object from the client to prepare a multilingual (i18n) property. It keeps only string or null values, allows optional transformation or sanitization via a callback.

Note: this helper is permissive on input shape — invalid inputs (string, scalar, etc.) silently return null rather than throwing. Callers that need to reject invalid shapes (e.g. to return a 422) must validate the raw input upstream before calling this helper.

Parameters
$fields : mixed

Input translations (array<string,string|null> or object). Any other shape (string, scalar, …) is treated as invalid and ignored — the function returns null. Type validation must be done upstream by callers.

$languages : array<string|int, string>|null = null

Optional array of languages to filter the i18n definitions. If null, no filtering is applied.

$sanitize : callable|null = null

Optional callback to transform or sanitize each value. Signature: fn(string|null $value, string $lang): string|null

Tags
example
$translations =
[
    'fr' => 'Bonjour <span style="color:red">monde</span>',
    'en' => 'Hello <span style="color:red">world</span>',
    'de' => 42, // ignored because not string/null
    'es' => null
];

// Basic filtering for 'fr' and 'en'
$filtered = filterLanguages($translations, ['fr', 'en']);
// [
//     'fr' => 'Bonjour <span style="color:red">monde</span>',
//     'en' => 'Hello <span style="color:red">world</span>'
// ]

// Filtering with HTML sanitization
$sanitized = filterLanguages($translations, ['fr', 'en'], function($value, $lang) {
if (is_string($value)) {
return preg_replace('/(<[^>]+) style=".*?"/i', '$1', $value);
}
return $value;
});
// [
//     'fr' => 'Bonjour <span>monde</span>',
//     'en' => 'Hello <span>world</span>'
// ]

// Filtering with custom transformation: uppercase strings
$upper = filterLanguages($translations, ['fr', 'en'], fn($v, $lang) => is_string($v) ? strtoupper($v) : $v);
// [
//     'fr' => 'BONJOUR <SPAN STYLE="COLOR:RED">MONDE</SPAN>',
//     'en' => 'HELLO <SPAN STYLE="COLOR:RED">WORLD</SPAN>'
// ]
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
array<string, string|null>|null

Filtered translations matching the languages, or null if input is empty.

getBodyParam()

Retrieves a single parameter from the HTTP request body.

getBodyParam(ServerRequestInterface|null $request, string $name) : mixed

This helper extracts a value from the parsed request body ($request->getParsedBody()), supporting dot notation for nested structures (e.g. 'user.address.city').

The body is internally normalized into a fully associative array using toAssociativeArray(), ensuring compatibility with both array and stdClass-based JSON payloads.

It internally uses hasKeyValue() and getKeyValue() from the oihana\core\accessors namespace.

If the request is null, or if the specified parameter does not exist, the function returns null.

Parameters
$request : ServerRequestInterface|null

The PSR-7 server request instance.

$name : string

The parameter name or nested key path (e.g. 'geo.latitude').

Tags
example

Retrieve a flat parameter:

// POST body: ['name' => 'Alice']
echo getBodyParam($request, 'name'); // 'Alice'

Retrieve a nested parameter using dot notation:

// POST body: ['geo' => ['latitude' => 42.5, 'longitude' => 1.5]]
echo getBodyParam($request, 'geo.latitude'); // '42.5'

Handle missing keys or null request:

echo getBodyParam(null, 'foo');            // null
echo getBodyParam($request, 'not.exists'); // null
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
mixed

The parameter value if found, or null otherwise.

getBodyParams()

Retrieves multiple parameters from the HTTP request body.

getBodyParams(ServerRequestInterface|null $request[, array<string|int, mixed> $names = [] ]) : array<string|int, mixed>

This helper extracts one or more values from the parsed request body ($request->getParsedBody()), supporting dot notation for nested structures (e.g. 'user.address.city').

Each requested key from $names is resolved recursively via hasKeyValue() and getKeyValue(), and reassembled into a new associative array using setKeyValue(). The request body is first normalized into a pure associative array using toAssociativeArray(), ensuring compatibility with both array and stdClass payloads.

If the request is null, the function returns null. If none of the requested keys exist, an empty array is returned.

Parameters
$request : ServerRequestInterface|null

The PSR-7 server request instance. If null, no extraction is performed.

$names : array<string|int, mixed> = []

A list of parameter names (keys or dot-notated paths) to extract.

Tags
example

Retrieve multiple flat parameters:

// POST body: ['name' => 'Alice', 'age' => 30]
$params = getBodyParams($request, ['name', 'age']);
// ['name' => 'Alice', 'age' => 30]

Retrieve nested parameters with dot notation:

// POST body: ['user' => ['profile' => ['email' => 'a@b.c', 'active' => true]]]
$params = getBodyParams($request, ['user.profile.email', 'user.profile.active']);
// ['user' => ['profile' => ['email' => 'a@b.c', 'active' => true]]]

Handle missing keys or null request:

getBodyParams(null, ['foo', 'bar']);  // []
getBodyParams($request, ['unknown']); // []
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
array<string|int, mixed>

An associative array of extracted values. Nested keys are preserved according to dot notation.

getController()

Retrieves a controller instance from a PSR-11 container if available.

getController([array<string|int, mixed>|string|null|Controller $definition = null ][, ContainerInterface|null $container = null ][, Controller|null $default = null ]) : Controller|null

This function attempts to fetch a controller by its identifier ($id) from the given container. If the container is provided and contains the specified entry, it is resolved and returned if it is an instance of Controller. Otherwise, the optional $default controller is returned.

Parameters
$definition : array<string|int, mixed>|string|null|Controller = null

The controller definition within the container.

$container : ContainerInterface|null = null

The PSR-11 container to fetch the controller from (optional).

$default : Controller|null = null

A fallback controller to return if the container does not provide one (optional).

Tags
throws
ContainerExceptionInterface

If an error occurs while retrieving the controller from the container.

NotFoundExceptionInterface

If the controller identifier does not exist in the container.

Return values
Controller|null

The resolved controller instance or the provided default value, or null if none found.

getParam()

Retrieves a parameter from the HTTP request, supporting query string, body, or both.

getParam(ServerRequestInterface|null $request, string $name[, array<string|int, mixed> $default = [] ][, string|null $strategy = HttpParamStrategy::BOTH ][, bool $throwable = false ]) : mixed

This helper searches for the requested parameter $name in the request according to the specified $strategy:

  • HttpParamStrategy::QUERY → only query string parameters.
  • HttpParamStrategy::BODY → only parsed body parameters.
  • HttpParamStrategy::BOTH → query string first, then body.

Nested keys are supported via dot notation (e.g., 'user.profile.email'). Body parameters are normalized to an associative array using toAssociativeArray().

If the parameter is not found:

  • Returns the corresponding value in $default[$name] if present.
  • Returns null if no default is provided.
  • Throws DI\NotFoundException if $throwable is true.
Parameters
$request : ServerRequestInterface|null

The PSR-7 server request instance.

$name : string

The parameter name or dot-notated path.

$default : array<string|int, mixed> = []

Optional default values as an associative array.

$strategy : string|null = HttpParamStrategy::BOTH

One of HttpParamStrategy::QUERY|BODY|BOTH. Default: BOTH.

$throwable : bool = false

Whether to throw a NotFoundException if parameter is missing. Default: false.

Tags
throws
NotFoundException

If $throwable is true and the parameter is not found.

author

Marc Alcaraz (ekameleon)

since
1.0.0
example
// Query parameter only
$request = ...; // ?name=Alice
getParam($request, 'name', [], HttpParamStrategy::QUERY);

// Body parameter only
$request = ...; // ['user' => ['email' => 'a@b.c']]
getParam($request, 'user.email', [], HttpParamStrategy::BODY);

// Both sources, with fallback
getParam($request, 'foo', ['foo' => 'default'], HttpParamStrategy::BOTH);

// Throw exception if missing
getParam($request, 'bar', [], HttpParamStrategy::BOTH, true);
Return values
mixed

The parameter value if found, otherwise the default value or null.

getParamArray()

Retrieves a parameter from the HTTP request and ensures it is an array.

getParamArray(ServerRequestInterface|null $request, string $name[, array<string|int, mixed> $args = [] ][, array<string|int, mixed>|null $defaultValue = null ][, string|null $strategy = HttpParamStrategy::BOTH ][, bool $throwable = false ]) : array<string|int, mixed>|null

This helper calls getParam() and checks the returned value:

  • If the value is an array, it is returned.
  • Otherwise, the $defaultValue is returned.
  • If $throwable is true, a NotFoundException may be thrown by getParam().
Parameters
$request : ServerRequestInterface|null

The PSR-7 server request instance.

$name : string

The parameter name or dot-notated path.

$args : array<string|int, mixed> = []

Optional default values passed to getParam().

$defaultValue : array<string|int, mixed>|null = null

Value returned if the parameter is missing or not an array. Default is null.

$strategy : string|null = HttpParamStrategy::BOTH

Which source to search: HttpParamStrategy::BOTH|QUERY|BODY. Default is BOTH.

$throwable : bool = false

Whether to throw a NotFoundException if parameter is missing. Default false.

Tags
throws
NotFoundException

If $throwable is true and the parameter is not found.

example
// Query string: ?filters[status]=active&filters[roles][]=admin
$filters = getParamArray($request, 'filters', [], ['status' => 'all']);
// Body: ['user' => ['roles' => ['editor', 'admin']]]
$roles = getParamArray($request, 'user.roles', [], []);
// Non-array value, returns default
$tags = getParamArray($request, 'tags', [], ['default']);
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
array<string|int, mixed>|null

The parameter value if it is an array, otherwise $defaultValue or null.

getParamBool()

Retrieves a parameter from the HTTP request and converts it to a boolean.

getParamBool(ServerRequestInterface|null $request, string $name[, array<string|int, mixed> $args = [] ][, bool|null $defaultValue = null ][, string|null $strategy = HttpParamStrategy::BOTH ][, bool $throwable = false ]) : bool|null

This helper calls getParam() and converts the returned value to a PHP boolean according to standard boolean representations:

  • true/false (boolean)
  • "true" / "false" (string)
  • "1" / "0" (string)
  • "yes" / "no" (string)
  • "on" / "off" (string)
  • 1 / 0 (integer)

If the value cannot be interpreted as a boolean, the provided $defaultValue is returned. If $request is null or the parameter is missing, $defaultValue is returned unless $throwable is set to true, in which case a NotFoundException is thrown.

Parameters
$request : ServerRequestInterface|null

The PSR-7 server request instance.

$name : string

The parameter name or dot-notated path.

$args : array<string|int, mixed> = []

Optional defaults passed to getParam().

$defaultValue : bool|null = null

Value returned if the parameter is missing or not a boolean. Default is null.

$strategy : string|null = HttpParamStrategy::BOTH

Source to search: HttpParamStrategy::BOTH|QUERY|BODY. Default is BOTH.

$throwable : bool = false

Whether to throw NotFoundException if parameter is missing. Default false.

Tags
throws
NotFoundException

If $throwable is true and the parameter is not found.

example
// Query string: ?active=true
$active = getParamBool($request, 'active', [], false);

// Body parameters: ['enabled' => '0']
$enabled = getParamBool($request, 'enabled', [], true);

// Missing parameter with default fallback
$flag = getParamBool($request, 'flag', [], true);

// Throw exception if parameter missing
$required = getParamBool($request, 'required', [], null, HttpParamStrategy::BOTH, true);
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
bool|null

The boolean value of the parameter, or $defaultValue/null if not found or unrecognized.

getParamFloat()

Retrieves a parameter from the HTTP request and ensures it is a float number.

getParamFloat(ServerRequestInterface|null $request, string $name[, array<string|int, mixed> $args = [] ][, float|null $defaultValue = null ][, string|null $strategy = HttpParamStrategy::BOTH ][, bool $throwable = false ]) : float|null

This helper calls getParam() and converts the returned value to a float if set.

  • If the value is null or missing, the $defaultValue is returned.
  • If $throwable is true, a NotFoundException may be thrown by getParam().
Parameters
$request : ServerRequestInterface|null

The PSR-7 server request instance.

$name : string

The parameter name or dot-notated path.

$args : array<string|int, mixed> = []

Optional default values passed to getParam().

$defaultValue : float|null = null

Value returned if the parameter is missing or not set. Default is null.

$strategy : string|null = HttpParamStrategy::BOTH

Which source to search: HttpParamStrategy::BOTH|QUERY|BODY. Default is BOTH.

$throwable : bool = false

Whether to throw a NotFoundException if parameter is missing. Default false.

Tags
throws
NotFoundException

If $throwable is true and the parameter is not found.

example
// Query string: ?price=19.95
$price = getParamFloat($request, 'price', [], 0.0); // 19.95

// Body: ['discount' => '5.5']
$discount = getParamFloat($request, 'discount', [], null); // 5.5

// Missing parameter, uses default
$tax = getParamFloat($request, 'tax', [], 1.0); // 1.0
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
float|null

The parameter value cast to float if present, otherwise $defaultValue or null.

getParamFloatRange()

Retrieves a float parameter from the request and clamps it within a given range.

getParamFloatRange(ServerRequestInterface|null $request, string $name, float $min, float $max[, float|null $defaultValue = null ][, array<string|int, mixed> $args = [] ][, string|null $strategy = HttpParamStrategy::BOTH ][, bool $throwable = false ]) : float|null

Wrapper around getParamNumberRange() that ensures float return type.

Parameters
$request : ServerRequestInterface|null

The PSR-7 server request instance. Can be null.

$name : string

The parameter name or dot-notated path.

$min : float

Minimum allowed float value.

$max : float

Maximum allowed float value.

$defaultValue : float|null = null

Value returned if the parameter is missing or not numeric. Default null.

$args : array<string|int, mixed> = []

Optional defaults passed to getParam().

$strategy : string|null = HttpParamStrategy::BOTH

Which source to search: HttpParamStrategy::BOTH|QUERY|BODY. Default BOTH.

$throwable : bool = false

Whether to throw NotFoundException if the parameter is missing. Default false.

Tags
throws
NotFoundException

If $throwable is true and the parameter is not found in the request.

NotFoundException
example
$discount = getParamFloatRange($request, 'discount', 0.0, 100.0, 0.0);
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
float|null

The float value clamped to [$min, $max], or $defaultValue/null if missing or invalid.

getParamI18n()

Retrieves an i18n parameter from the HTTP request, optionally filtered by allowed languages.

getParamI18n(ServerRequestInterface|null $request, string $name[, array<string|int, mixed> $default = [] ][, array<string|int, string>|null $languages = null ][, callable|null $sanitize = null ][, string|null $strategy = HttpParamStrategy::BOTH ][, bool $throwable = false ]) : array<string|int, mixed>|null

This helper retrieves a parameter $name from the PSR-7 $request, supporting query string, body, or both (HttpParamStrategy). The parameter can be an array or object of translations (e.g., ['fr' => 'Bonjour', 'en' => 'Hello']). It then filters the values according to $languages and optionally applies a $sanitize callback on each value.

Nested keys in the request are supported via dot notation (e.g., 'user.profile.email').

If the parameter is not found:

  • Returns $default[$name] if present.
  • Returns null if no default is provided.
  • Throws NotFoundException if $throwable is true.
Parameters
$request : ServerRequestInterface|null

The PSR-7 server request instance.

$name : string

The parameter name or dot-notated path.

$default : array<string|int, mixed> = []

Optional default values as an associative array.

$languages : array<string|int, string>|null = null

Optional array of languages to filter the i18n definitions. If null, no filtering is applied.

$sanitize : callable|null = null

Optional callback to transform or sanitize each value. Signature: fn(string|null $value, string $lang): string|null

$strategy : string|null = HttpParamStrategy::BOTH

One of HttpParamStrategy::QUERY|BODY|BOTH. Default: BOTH.

$throwable : bool = false

Whether to throw a NotFoundException if parameter is missing. Default: false.

Tags
throws
NotFoundException

If $throwable is true and the parameter is not found.

example
$request = ...; // PSR-7 request with body/query

// Retrieve translations for 'description' filtered to 'fr' and 'en'
$translations = getParamI18n
(
     $request ,
     'description' ,
     ['description' => ['fr' => 'Default FR', 'en' => 'Default EN']],
     ['fr', 'en'],
     fn($v,$lang) => is_string($v) ? strtoupper($v) : $v
);
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
array<string|int, mixed>|null

The i18n value if found, otherwise the default value or null.

getParamInt()

Retrieves a parameter from the HTTP request and ensures it is a int number.

getParamInt(ServerRequestInterface|null $request, string $name[, array<string|int, mixed> $args = [] ][, int|null $defaultValue = null ][, string|null $strategy = HttpParamStrategy::BOTH ][, bool $throwable = false ]) : int|null

This helper calls getParam() and converts the returned value to a int if set.

  • If the value is null or missing, the $defaultValue is returned.
  • If $throwable is true, a NotFoundException may be thrown by getParam().
Parameters
$request : ServerRequestInterface|null

The PSR-7 server request instance.

$name : string

The parameter name or dot-notated path.

$args : array<string|int, mixed> = []

Optional default values passed to getParam().

$defaultValue : int|null = null

Value returned if the parameter is missing or not set. Default is null.

$strategy : string|null = HttpParamStrategy::BOTH

Which source to search: HttpParamStrategy::BOTH|QUERY|BODY. Default is BOTH.

$throwable : bool = false

Whether to throw a NotFoundException if parameter is missing. Default false.

Tags
throws
NotFoundException

If $throwable is true and the parameter is not found.

example
// Query string: ?age=19
$price = getParamInt($request, 'age', [], 0); // 19

// Body: ['age' => '5']
$discount = getParamInt($request, 'age', [], null); // 5

// Missing parameter, uses default
$tax = getParamInt($request, 'age', [], 1); // 1
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
int|null

The parameter value cast to int if present, otherwise $defaultValue or null.

getParamIntRange()

Retrieves an integer parameter from the request and clamps it within a given range.

getParamIntRange(ServerRequestInterface|null $request, string $name, int $min, int $max[, int|null $defaultValue = null ][, array<string|int, mixed> $args = [] ][, string|null $strategy = HttpParamStrategy::BOTH ][, bool $throwable = false ]) : int|null

Wrapper around getParamNumberRange() that ensures integer return type.

Parameters
$request : ServerRequestInterface|null

The PSR-7 server request instance. Can be null.

$name : string

The parameter name or dot-notated path.

$min : int

Minimum allowed integer value.

$max : int

Maximum allowed integer value.

$defaultValue : int|null = null

Value returned if the parameter is missing or not numeric. Default null.

$args : array<string|int, mixed> = []

Optional defaults passed to getParam().

$strategy : string|null = HttpParamStrategy::BOTH

Which source to search: HttpParamStrategy::BOTH|QUERY|BODY. Default BOTH.

$throwable : bool = false

Whether to throw NotFoundException if the parameter is missing. Default false.

Tags
throws
NotFoundException

If $throwable is true and the parameter is not found in the request.

example
$quantity = getParamIntRange($request, 'quantity', 1, 10, 5);
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
int|null

The integer value clamped to [$min, $max], or $defaultValue/null if missing or invalid.

getParamNumberRange()

Retrieves a numeric parameter from the request and clamps it within a given range.

getParamNumberRange(ServerRequestInterface|null $request, string $name, int|float $min, int|float $max[, int|float|null $defaultValue = null ][, array<string|int, mixed> $args = [] ][, string|null $strategy = HttpParamStrategy::BOTH ][, bool $throwable = false ]) : int|float|null

This helper calls getParam() and:

  • Converts the value to int or float.
  • Returns $defaultValue if the parameter is missing or not numeric.
  • Clamps the value between $min and $max.
  • Can throw NotFoundException if $throwable is true and parameter is missing.
Parameters
$request : ServerRequestInterface|null

The PSR-7 request instance.

$name : string

Parameter name or dot-notated path.

$min : int|float

Minimum allowed value.

$max : int|float

Maximum allowed value.

$defaultValue : int|float|null = null

Value returned if missing or invalid. Default null.

$args : array<string|int, mixed> = []

Optional defaults passed to getParam().

$strategy : string|null = HttpParamStrategy::BOTH

Source to search: BOTH, QUERY, BODY. Default BOTH.

$throwable : bool = false

Whether to throw NotFoundException if missing. Default false.

Tags
throws
NotFoundException

If $throwable is true and the parameter is not found.

example
// Query: ?price=15
$price = getParamNumberRange($request, 'price', 0, 100, 10); // 15

// Body: ['discount' => 150]
$discount = getParamNumberRange($request, 'discount', 0, 100, 0); // 100 (clamped)

// Missing value
$tax = getParamNumberRange($request, 'tax', 0, 50, 5); // 5 (default)
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
int|float|null

The numeric value clamped to the range [$min, $max], or $defaultValue/null if missing or invalid.

getParamString()

Retrieves a parameter from the HTTP request and ensures it is a string.

getParamString(ServerRequestInterface|null $request, string $name[, array<string|int, mixed> $args = [] ][, string|null $defaultValue = null ][, string|null $strategy = HttpParamStrategy::BOTH ][, bool $throwable = false ]) : string|null

This helper calls getParam() and converts the returned value to a string if set.

  • If the value is null or missing, the $defaultValue is returned.
  • If $throwable is true, a NotFoundException may be thrown by getParam().
Parameters
$request : ServerRequestInterface|null

The PSR-7 server request instance.

$name : string

The parameter name or dot-notated path.

$args : array<string|int, mixed> = []

Optional default values passed to getParam().

$defaultValue : string|null = null

Value returned if the parameter is missing or null. Default is null.

$strategy : string|null = HttpParamStrategy::BOTH

Which source to search: HttpParamStrategy::BOTH|QUERY|BODY. Default is BOTH.

$throwable : bool = false

Whether to throw a NotFoundException if parameter is missing. Default false.

Tags
throws
NotFoundException

If $throwable is true and the parameter is not found.

example
// Query string: ?name=Alice
$name = getParamString($request, 'name'); // "Alice"

// Body: ['title' => 'Manager']
$title = getParamString($request, 'title', [], 'Default'); // "Manager"

// Missing parameter, uses default
$nickname = getParamString($request, 'nickname', [], 'Guest'); // "Guest"
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
string|null

The parameter value cast to string if present, otherwise $defaultValue or null.

getQueryParam()

Retrieves a single parameter from the HTTP request query string.

getQueryParam(ServerRequestInterface|null $request, string $name) : mixed

This helper extracts a value from the query parameters ($request->getQueryParams()), supporting dot notation for nested structures (e.g. 'filter.page').

It internally uses hasKeyValue() and getKeyValue() from the oihana\core\accessors namespace.

If the request is null, or if the specified parameter does not exist, the function returns null.

Parameters
$request : ServerRequestInterface|null

The PSR-7 server request instance. If null, no extraction is performed.

$name : string

The query parameter name or nested key path (e.g. 'filter.page').

Tags
example

Retrieve a flat parameter:

// URL: /api/users?name=Alice&age=30
echo getQueryParam($request, 'name'); // 'Alice'
echo getQueryParam($request, 'age');  // '30'

Retrieve a nested parameter using dot notation:

// URL: /api/users?filter[page]=2&filter[limit]=10
echo getQueryParam($request, 'filter.page');  // '2'
echo getQueryParam($request, 'filter.limit'); // '10'

Handle missing keys or null request:

getQueryParam(null, 'foo');            // null
getQueryParam($request, 'not.exists'); // null
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
mixed

The parameter value if found, or null otherwise.

parseRangeHeader()

Parses an HTTP `Range` header into a single satisfiable byte interval.

parseRangeHeader(string $rangeHeader, int $fileSize) : array{0: int, 1: int}|false|null

Supports the common single-range forms: bytes=0-499, bytes=500- (open-ended) and bytes=-500 (suffix / last N bytes). Multi-range requests are intentionally not honored and resolve to null (the caller should serve the full content).

Parameters
$rangeHeader : string

The raw Range header value.

$fileSize : int

The total size of the file in bytes.

Tags
author

Marc Alcaraz (ekameleon)

since
1.0.0
example
parseRangeHeader( 'bytes=0-4'    , 11 ) ; // [0, 4]   -> 206
parseRangeHeader( 'bytes=6-'     , 11 ) ; // [6, 10]  -> 206 (open-ended)
parseRangeHeader( 'bytes=-5'     , 11 ) ; // [6, 10]  -> 206 (last 5 bytes)
parseRangeHeader( 'bytes=0-9999' , 11 ) ; // [0, 10]  -> 206 (end clamped)
parseRangeHeader( 'bytes=99-'    , 11 ) ; // false    -> 416 (unsatisfiable)
parseRangeHeader( 'bytes=0-2,5-' , 11 ) ; // null     -> 200 (multi-range ignored)
parseRangeHeader( ''             , 11 ) ; // null     -> 200 (no range)
Return values
array{0: int, 1: int}|false|null
  • [start, end] (inclusive, clamped) for a satisfiable single range → 206;
  • false when a range is present but unsatisfiable → 416;
  • null when there is no usable single range (absent / malformed / multi-range) → full 200.

translate()

Retrieve the translation for a specific language, with optional fallback to a default language.

translate(array<string, mixed>|object|null $fields[, string|null $lang = null ][, string|null $default = null ]) : mixed

This version is safer: if the requested language and the fallback are missing, it returns null instead of returning the full array/object.

Example usage:

$translations =
[
    'fr' => 'Bonjour',
    'en' => 'Hello',
    'es' => 'Hola'
];

translate( $translations , 'en' );        // 'Hello'
translate( $translations , 'de' , 'fr' ); // 'Bonjour' (fallback)
translate( $translations , 'it' , 'de' ); // null
translate( $translations );               // ['fr' => 'Bonjour', 'en' => 'Hello', 'es' => 'Hola']

$translationsObj = (object) $translations ;
translate( $translationsObj , null ) ; // (object) ['fr' => 'Bonjour', 'en' => 'Hello', 'es' => 'Hola']
Parameters
$fields : array<string, mixed>|object|null

Array or object of translations keyed by language codes.

$lang : string|null = null

Desired language code. If null, returns all translations.

$default : string|null = null

Optional fallback language code if $lang is missing.

Tags
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
mixed

Returns the translation for the requested language, the fallback, all translations (if $lang is null), or null if no match.

On this page

Search results