Documentation

Request extends RequestResponseHandler
in package
Uses CanValidateForm, CanValidateMultiForm, CanRetrieveFromInput

The incoming request: input, URL parts, permission checks and form helpers

Table of Contents

$booter  : ZubZet
$input  : State
$store  : array<string|int, mixed>
$urlParameters  : array<string|int, mixed>
$urlParts  : array<string|int, mixed>
__construct()  : mixed
acceptLanguage()  : array<string|int, mixed>
bearerToken()  : string|null
checkPermission()  : bool
Checks if the current user has a permission. If the user is not logged in, the login page is rendered and the script exits.
checkSuperPermission()  : bool
csrfBlockAdditionalMethod()  : void
Runs the CSRF check, additionally covering methods normally exempt as safe (e.g. "GET"), so this request also gets CSRF-checked for them.
getBody()  : string|null
Get the body of the request
getBooterSettings()  : mixed
Gets a booter setting
getCookie()  : mixed
Gets a cookie
getCookies()  : array<string|int, mixed>
Alias for getCookie() to get all cookies
getCurrentURL()  : string
Returns the current URL
getDomain()  : string
Returns the app domain as specified in the configuration (`host=`), with scheme, port and path stripped (`https://example.com:8080/app` becomes `example.com`). An IPv6 literal keeps its brackets (`[::1]`).
getExecutionTime()  : float|null
getFile()  : mixed
Gets a posted file
getFiles()  : array<string|int, mixed>
Alias for getFile() to get all posted files
getGet()  : mixed
Gets a GET parameter
getJson()  : mixed
Decode the request body as JSON.
getModel()  : Model
Returns a model, one shared instance per request; falls back to the framework models when not found
getParameters()  : array<string|int, mixed>|string|bool
Gets the URL parameters (excluding the leading controller and action) specified by the path.
getPost()  : mixed
Gets a POST parameter
getReadableParameter()  : array<string|int, mixed>
Works like getParameters and decodes an SEO optimized URL. Example: test.com/episodes/this-is-some-text-64 The 64 is an id
getRequestingUser()  : User
Gets the user who made the request, also for guests (check isLoggedIn).
getRoot()  : string
Returns the current root URL including protocol and root directory
getRootFolder()  : string
Gets the URL base path of the app ("/" plus rootDirectory, with trailing slash).
getRouteParameter()  : mixed
getUrlParts()  : array<string|int, mixed>
getZRoot()  : string
Returns the framework root directory
getZViews()  : string
Returns the project's own views directory (config z_views, relative path with trailing slash), not the framework's IncludedComponents views
hasFormData()  : bool
Checks if the request contains form data, i.e. the POST flag isFormData that Z.js ZForm sends (plain HTML form posts return false). When a form action is provided, it must match the submitted action.
ip()  : string|null
Gets the IP of a request
isAction()  : bool
Checks if the POST field action equals $type, compared as text; it does not verify that the request came via AJAX
isCli()  : bool
Detects if a request was made from the console
referer()  : string|null
requireFreshTwoFactor()  : bool
Guards an action behind a recent two factor check. Answers true when the session passed one inside `two_factor_freshness_seconds`, and for every account that carries no two factor at all.
requireOrganization()  : bool
Checks if the current user belongs to an organization. If the user is not logged in, they will be redirected to the login page.
userAgent()  : string|null
validateCED()  : Result
Validates each row of a "Create Edit Delete" input read from getPost($name); sets doNothing if it is absent, and errors carry the row's subname and index
validateForm()  : Result
Validates form data from the client

Properties

$store

public array<string|int, mixed> $store = []

Store values within the Request to pass through data within internal redirects

$urlParameters

public array<string|int, mixed> $urlParameters = []

$urlParts

public array<string|int, mixed> $urlParts

Methods

__construct()

public __construct(State $input) : mixed
Parameters
$input : State
Return values
mixed —

acceptLanguage()

public acceptLanguage() : array<string|int, mixed>
Return values
array<string|int, mixed> —

bearerToken()

public bearerToken() : string|null
Return values
string|null —

checkPermission()

Checks if the current user has a permission. If the user is not logged in, the login page is rendered and the script exits.

public checkPermission(string $permission[, bool $boolResult = false ][, bool $includeSuperUser = false ]) : bool

If the user is logged in but does not have the permission, the 403 page is rendered and the script exits. The permission "console" passes only on CLI.

Parameters
$permission : string

Permission to check for

$boolResult : bool = false

If true, the function will return false instead of rendering the login/403 page and exiting

$includeSuperUser : bool = false

If true, the permission may also be held by the executing user (the user acting as another one)

Return values
bool —

True if the permission is granted (otherwise false with $boolResult, or the script exits)

checkSuperPermission()

public checkSuperPermission(string $permission[, bool $boolResult = false ]) : bool
Parameters
$permission : string
$boolResult : bool = false
Return values
bool —

csrfBlockAdditionalMethod()

Runs the CSRF check, additionally covering methods normally exempt as safe (e.g. "GET"), so this request also gets CSRF-checked for them.

public csrfBlockAdditionalMethod(string ...$additionalMethods) : void

A rejected request is redirected to 403 and the script ends.

Parameters
$additionalMethods : string

Methods to remove from the safe-method exemption for this call, "GET" when none is given

Return values
void —

getBody()

Get the body of the request

public getBody() : string|null

Reads the raw input from the request body.

Return values
string|null —

The raw body content of the request (Returns null if empty or unavailable).

getBooterSettings()

Gets a booter setting

public getBooterSettings([string|null $key = null ][, bool $useDefault = true ][, mixed $default = null ]) : mixed
Parameters
$key : string|null = null

Key of the setting, null or empty returns all settings

$useDefault : bool = true

Return $default instead of throwing when the key does not exist

$default : mixed = null

Value returned for a missing key when $useDefault is true

Tags
throws
InvalidArgumentException

If the key does not exist and $useDefault is false

Return values
mixed —

Value of the key

getCookie()

Gets a cookie

public getCookie([string|null $key = null ][, mixed $default = null ]) : mixed
Parameters
$key : string|null = null

The key of the parameter, null returns all cookies

$default : mixed = null

Default value

Return values
mixed —

The value, $default if the key is missing, or all cookies when $key is null

getCookies()

Alias for getCookie() to get all cookies

public getCookies() : array<string|int, mixed>
Return values
array<string|int, mixed> —

The cookies

getCurrentURL()

Returns the current URL

public getCurrentURL() : string
Return values
string —

Returns the current URL, consisting of the configured host followed by the raw REQUEST_URI (root directory, path and query string)

getDomain()

Returns the app domain as specified in the configuration (`host=`), with scheme, port and path stripped (`https://example.com:8080/app` becomes `example.com`). An IPv6 literal keeps its brackets (`[::1]`).

public getDomain() : string
Return values
string —

the domain

getExecutionTime()

public getExecutionTime() : float|null
Return values
float|null —

getFile()

Gets a posted file

public getFile([string|null $key = null ][, mixed $default = null ]) : mixed
Parameters
$key : string|null = null

The name of the file, null returns all files

$default : mixed = null

Default value if the file is not posted

Return values
mixed —

The $_FILES entry (name, type, tmp_name, error, size), $default if the key is missing, or all files when $key is null

getFiles()

Alias for getFile() to get all posted files

public getFiles() : array<string|int, mixed>
Return values
array<string|int, mixed> —

The posted files

getGet()

Gets a GET parameter

public getGet([string|null $key = null ][, mixed $default = null ]) : mixed
Parameters
$key : string|null = null

The key of the parameter, null returns the whole GET array

$default : mixed = null

Default value

Return values
mixed —

The value, $default if the key is missing, or the whole array when $key is null

getJson()

Decode the request body as JSON.

public getJson([int|null $maxBytes = null ][, int $maxDepth = 512 ]) : mixed

Every well formed JSON value is accepted, whatever the method and the Content-Type of the request are: an object or a list comes back as an array, and a number, a string, a boolean or null as that value. A request without a body gives null, so an optional body reads as $req->getJson() ?? []. Large integers come back as strings instead of lossy floats.

Parameters
$maxBytes : int|null = null

Longest accepted body in bytes, no limit when null

$maxDepth : int = 512

Deepest accepted nesting, 512 is the limit PHP itself applies

Tags
throws
UnexpectedValueException

With the code 413 for a body longer than $maxBytes

throws
JsonException

If the body is not well formed JSON

Return values
mixed —

The decoded value with objects as associative arrays, null without a body

getModel()

Returns a model, one shared instance per request; falls back to the framework models when not found

public getModel(string $model[, string|null $dir = null ]) : Model
Parameters
$model : string

Name of the model, sub-folders dot separated (e.g. "admin.User")

$dir : string|null = null

Set this when the model is stored in a specific directory, needs a trailing slash

Tags
throws
Exception

When the model does not exist

Return values
Model —

The model

getParameters()

Gets the URL parameters (excluding the leading controller and action) specified by the path.

public getParameters(int $offset[, int $length = null ][, string $val = null ]) : array<string|int, mixed>|string|bool
Parameters
$offset : int

The offset from which to start. Can be -1 if action_fallback is used

$length : int = null

The amount of array elements that will be returned at the set offset. If null, every element will be returned

$val : string = null

If the length is 1 and $val is set, a Boolean will be returned. $val will be compared to the parameter as text, so "05" is not "5"

Return values
array<string|int, mixed>|string|bool —

Array of parameters, the single parameter (or a Boolean comparison with $val) if length is 1, false if length is 1 and the parameter is missing

getPost()

Gets a POST parameter

public getPost([string|null $key = null ][, mixed $default = null ]) : mixed
Parameters
$key : string|null = null

The key of the parameter, null returns the whole POST array

$default : mixed = null

Default value

Return values
mixed —

The value, $default if the key is missing, or the whole array when $key is null

getReadableParameter()

Works like getParameters and decodes an SEO optimized URL. Example: test.com/episodes/this-is-some-text-64 The 64 is an id

public getReadableParameter(int $offset) : array<string|int, mixed>
Parameters
$offset : int

The offset from which to start. Can be -1 if action_fallback is used

Return values
array<string|int, mixed> —

getRequestingUser()

Gets the user who made the request, also for guests (check isLoggedIn).

public getRequestingUser() : User
Return values
User —

Object of the requesting user

getRoot()

Returns the current root URL including protocol and root directory

public getRoot() : string
Return values
string —

a URL like $opt["root"] but including the host before

getRootFolder()

Gets the URL base path of the app ("/" plus rootDirectory, with trailing slash).

public getRootFolder() : string
Return values
string —

URL base path used to prefix links and cookie paths

getRouteParameter()

public getRouteParameter([mixed $key = null ]) : mixed
Parameters
$key : mixed = null
Return values
mixed —

getUrlParts()

public getUrlParts() : array<string|int, mixed>
Return values
array<string|int, mixed> —

getZRoot()

Returns the framework root directory

public getZRoot() : string
Return values
string —

getZViews()

Returns the project's own views directory (config z_views, relative path with trailing slash), not the framework's IncludedComponents views

public getZViews() : string
Return values
string —

hasFormData()

Checks if the request contains form data, i.e. the POST flag isFormData that Z.js ZForm sends (plain HTML form posts return false). When a form action is provided, it must match the submitted action.

public hasFormData([string|null $formAction = null ]) : bool

When it contains form data, methods like validateForm() can be used.

Parameters
$formAction : string|null = null

Optional action identifying one form among multiple forms

Return values
bool —

ip()

Gets the IP of a request

public ip() : string|null
Return values
string|null —

The IP of the client, client-supplied headers (spoofable) are trusted first. Empty string if none is found

isAction()

Checks if the POST field action equals $type, compared as text; it does not verify that the request came via AJAX

public isAction(string $type) : bool
Parameters
$type : string

Type of the request. Request is sent via Z.js => Z.Request.action()

Return values
bool —

True if the request is of the specified type

isCli()

Detects if a request was made from the console

public isCli() : bool
Return values
bool —

True if the request was made from a console

referer()

public referer() : string|null
Return values
string|null —

requireFreshTwoFactor()

Guards an action behind a recent two factor check. Answers true when the session passed one inside `two_factor_freshness_seconds`, and for every account that carries no two factor at all.

public requireFreshTwoFactor([int|null $freshnessSeconds = null ][, bool $boolResult = false ]) : bool

Without $boolResult a stale session is answered with a json error carrying twoFactorRenew, which Z.js turns into the two factor modal. Pass true to answer the client yourself instead:

if(!$req->requireFreshTwoFactor(boolResult: true)) {
    return $res->error("Two factor required", ["twoFactorRenew" => true]);
}
Parameters
$freshnessSeconds : int|null = null

How recent the check has to be, or null for the configured window

$boolResult : bool = false

Return the answer rather than ending the request

Return values
bool —

Whether the session is fresh enough

requireOrganization()

Checks if the current user belongs to an organization. If the user is not logged in, they will be redirected to the login page.

public requireOrganization([bool $boolResult = false ]) : bool

If the user is logged in but does not belong to an organization, they will be redirected to 403.

Parameters
$boolResult : bool = false

If true, the function will return a boolean result instead of redirecting

Return values
bool —

userAgent()

public userAgent() : string|null
Return values
string|null —

validateCED()

Validates each row of a "Create Edit Delete" input read from getPost($name); sets doNothing if it is absent, and errors carry the row's subname and index

public validateCED(string $name, array<string|int, Field> $rules) : Result
Parameters
$name : string

Name of the input field

$rules : array<string|int, Field>

Fields every row is validated against

Return values
Result —

Result of the validation. Needed to perform response actions

validateForm()

Validates form data from the client

public validateForm(array<string|int, Field> $fields[, array<string|int, mixed> $data = null ]) : Result
Parameters
$fields : array<string|int, Field>

Array of fields with the validation rules

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

Input for the validation, defaults to getPost() + getFiles() when null. getGet() or getPost() can be used here as parameters, an empty array is validated as it is Rules other than required() are skipped for empty values.

Return values
Result —

A result to work with

Search results