Check attributes


1Overview

1.1Validation attributes

Temma provides several attributes used to validate incoming data:

  • \Temma\Attributes\Check\Params: Validates parameters present in the URL.
  • \Temma\Attributes\Check\Get: Validates data received as GET parameters.
  • \Temma\Attributes\Check\Post: Validates data received as POST parameters.
  • \Temma\Attributes\Check\Files: Validates uploaded files.
  • \Temma\Attributes\Check\Payload: Validates data sent in the request body.

These attributes are wrappers that call the validateParams(), validateInput(), validatePayload() and validateFiles() methods of the Request object. Validations are based on contracts in the format expected by the DataFilter object.

There is also an attribute for validating outgoing data:

  • \Temma\Attributes\Check\Output: Defines a validation contract for output data, used by the view.

This attribute calls the setValidationContract() method of the Response object.


1.2Common parameters

Some parameters are common to all of these attributes (except Output):

  • $strict: (bool) Enables strict validation mode (false by default).
  • $redirect: (string) URL to redirect the user to if the data is not valid.
  • $redirectVar: (string) Name of the template variable containing the redirection URL.
  • $redirectReferer: (bool) true by default. If true and $redirect and $redirectVar are empty, the HTTP REFERER header is used as the redirection URL.
  • $flashVar : (string) Name of the flash variable that will contain information in case of redirection ('form' by default). The content of the flash variable depends on the attribute used (see below).
    The default value 'form' means that received data is available in a flash session variable named __form.

1.3Redirection priority

When the data is not valid, the attribute can redirect the user to another page.
To determine the redirection URL, the following priority order is applied:

  1. If the $redirect parameter is defined, it is used.
  2. If the $redirectVar parameter is defined and contains the name of an existing, non-empty template variable, its value is used.
  3. If the $redirectReferer parameter is set to true, and the HTTP Referer header exists and is non-empty, it is used.
  4. If the etc/temma.php file contains an extended x-security configuration with a redirect key, its value is used.

If no redirection URL is found, an HTTP 403 (Forbidden) error is returned.


2Params

2.1Params: overview

This attribute validates the parameters received by an action (or by all actions of a controller).
It is a wrapper around the validateParams() method of the Request object.


2.2Params: specific parameters

  • $contract : (string|array) Name of the contract defined in the configuration file (see documentation), or name of a validation object, or list of contracts (one contract per parameter).
  • $flashVar : (string) Name of the flash variable that will contain a copy of the received parameters if the user is redirected.

2.3Params : examples

use \Temma\Attributes\Check\Params as TµCheckParams;

/*
 * All controller actions must have one parameter of type "int"
 * and one parameter of type "email".
 */
#[TµCheckParams(['int', 'email'])]
class Actions extends \Temma\Web\Controller {
    // ...
}
use \Temma\Attributes\Check\Params as TµCheckParams;

class Actions extends \Temma\Web\Controller {
    // this action expects a positive integer parameter
    // and a string of 12 characters or fewer
    #[TµCheckParams(['int; min: 0', 'string; maxLen: 12'])]
    public function doSomething(int $i, string $s) {
        // ...
    }

    // expects an integer parameter and an email address,
    // with strict validation mode enabled, while allowing additional parameters
    #[TµCheckParams(
        [
            'int',
            'email',
            '...'
        ],
        strict: true,
    )]
    public function action2(int $id, string $mail, float $amount, string $name) {
        // ...
    }

    // expects a negative integer and a string;
    // on error, redirects to '/path/to/error';
    // received parameters are copied to the '__getErr' flash variable
    #[TµCheckParams(
        ['int; max: 0', 'string'],
        redirect: '/path/to/error',
        flashVar: 'getErr',
    )]
    public function action3(int $id, string $value) {
        // ...
    }

    // expects a positive integer; on error, redirects to the URL
    // contained in the 'errorPage' template variable;
    // received parameters are copied to the default '__form'
    // flash variable
    #[TµCheckParams(
        ['int; min: 1'],
        redirectVar: 'errorPage',
    )]
    public function action4(int $id) {
        // ...
    }

    // parameters must validate the contract named "deleteUserParameters"
    // in the configuration file, defined as follows:
    // 'validationTypes' => [
    //     'deleteUserParameters' => [
    //         'type'   => 'list',
    //         'values' => [
    //             'int; min: 1',
    //             'hash; algo: sha256',
    //             'string; minLen: 2',
    //         ]
    //     ]
    // ]
    #[TµCheckParams('deleteUserParameters')]
    public function deleteUser(int $userId, string $checkHash, string $login) {
        // ...
    }
}

3Get

3.1Get: overview

This attribute validates the GET parameters received by a controller or an action.
It is a wrapper around the validateParams() method of the Request object.


3.2Get: specific parameters

  • $contract : (string|array) Name of the contract defined in the configuration file (see documentation), or name of a validation object, or associative array whose keys are GET parameter names and whose values are validation contracts.
  • $flashVar : (string) Name of the flash variable that will contain a copy of the received GET data if the user is redirected.

3.3Get: examples

use \Temma\Attributes\Check\Get as TµCheckGet;

/*
 * All controller actions must receive GET parameters
 * "id" (int type) and "mail" (email type).
 */
#[TµCheckGet([
  'id'   => 'int',
  'mail' => 'email',
])]
class Actions extends \Temma\Web\Controller {
    // ...
}
use \Temma\Attributes\Check\Get as TµCheckGet;

class Actions extends \Temma\Web\Controller {
    // this action expects a GET parameter "id" (without specifying the type)
    #[TµCheckGet(['id'])]
    public function getList() {
        // ...
    }

    // expects an "id" parameter and a "name" parameter (string with minimum 3 characters)
    // with strict validation mode enabled, while allowing additional parameters
    #[TµCheckGet(
        [
            'id',
            'name' => 'string; minLen: 3; maxLen: 20',
            '...'
        ],
        strict: true,
    )]
    public function removeItem(int $id) {
        // ...
    }

    // expects an integer 'id' and an optional string 'name';
    // on error, redirects to '/path/to/error';
    // received GET data is copied to the '__getErr' flash variable
    #[TµCheckGet(
        [
            'id'    => 'int',
            'name?' => 'string',
        ],
        redirect: '/path/to/error',
        flashVar: 'getErr',
    )]
    public function defineItem(int $id, mixed $value) {
        // ...
    }

    // expects an integer 'id'; on error, the HTTP referer is not used;
    // redirection goes to the URL defined in the configuration
    // (x-security.redirect);
    // received data is copied to the default '__form' flash variable
    #[TµCheckGet(
        ['id' => 'int'],
        redirectReferer: false,
    )]
    public function showItem(int $id) {
        // ...
    }

    // GET parameters must validate the contract named "internalUserData" in
    // the configuration file, defined as follows:
    // 'validationTypes' => [
    //     'internalUserData' => [
    //         'login' => 'string; minLen: 2',
    //         'email' => 'email; mask: @mydomain.com$',
    //         'name'  => 'string; minLen: 2',
    //     ]
    // ]
    #[TµCheckGet('internalUserData')]
    public function updateUser(int $userId) {
        // ...
    }
}

4Post

4.1Post: overview

This attribute validates POST parameters received by a controller or an action.
It is a wrapper around the validateParams() method of the Request object.


4.2Post: specific parameters

  • $contract : (string|array) Name of the contract defined in the configuration file (see documentation), or name of a validation object, or associative array whose keys are POST parameter names and whose values are validation contracts.
  • $flashVar : (string) Name of the flash variable that will contain a copy of the received POST data if the user is redirected.

4.3Post: examples

use \Temma\Attributes\Check\Post as TµCheckPost;

/*
 * All controller actions must receive POST parameters
 * "id" (int type) and "mail" (email type).
 */
#[TµCheckPost([
  'id'   => 'int',
  'mail' => 'email',
])]
class Actions extends \Temma\Web\Controller {
    // ...
}
use \Temma\Attributes\Check\Post as TµCheckPost;

class Actions extends \Temma\Web\Controller {
    // this action expects a POST parameter "id" (without specifying the type)
    #[TµCheckPost(['id'])]
    public function getList() {
        // ...
    }

    // expects an "id" parameter and a "name" parameter (string with minimum 3 characters)
    #[TµCheckPost([
        'id',
        'name' => 'string; minLen: 3'
    ])]
    public function removeItem(int $id) {
        // ...
    }

    // expects an integer 'id'; on error, redirects to '/path/to/error';
    // received POST data is copied to the '__postErr' flash variable
    #[TµCheckPost(
        ['id' => 'int'],
        redirect: '/path/to/error',
        flashVar: 'postErr',
    )]
    public function defineItem(int $id, mixed $value) {
        // ...
    }

    // expects an integer 'id' and a string 'name';
    // on error, redirects to the URL contained in the
    // 'formErrorUrl' template variable; no flash variable is set
    #[TµCheckPost(
        [
            'id'   => 'int',
            'name' => 'string',
        ],
        redirectVar: 'formErrorUrl',
        flashVar: null,
    )]
    public function createItem(int $id, string $name) {
        // ...
    }

    // POST parameters must validate the contract named "itemData" in
    // the configuration file, defined as follows:
    // 'validationTypes' => [
    //     'itemData' => [
    //         'code'         => 'ean',
    //         'dateCreation' => 'email; mask: @mydomain.com$',
    //         'name'         => 'string; minLen: 2',
    //     ]
    // ]
    #[TµCheckPost('itemData')]
    public function updateItem(int $itemId) {
        // ...
    }
}

5Files

5.1Files: overview

This attribute validates files received by a controller or an action.
It is a wrapper around the validateFiles() method of the Request object.


5.2Files: specific parameters

  • $contract : (array) Associative array whose keys are file names and whose values are validation contracts.
  • $flashVar : (string) Name of the flash variable that will contain a copy of the data received in the $_FILES superglobal if the user is redirected.

5.3Files: examples

use \Temma\Attributes\Check\Files as TµCheckFiles;

class Actions extends \Temma\Web\Controller {
    // this action expects a file "id_card" (no further constraints)
    #[TµCheckFiles(['id_card'])]
    public function uploadId() {
        // ...
    }

    // expects a "picto" file (GIF or PNG image) and an optional "avatar" file (PDF or image)
    #[TµCheckFiles([
        'picto'   => 'binary; mime: image/gif, image/png',
        'avatar?' => 'binary; mime: application/pdf, image'
    ])]
    public function createUser() {
        // ...
    }
}

6Payload

6.1Payload: overview

This attribute validates the request body content ("payload") received by a controller or an action.
It is a wrapper around the validatePayload() method of the Request object.


6.2Payload: specific parameters

  • $contract : (string|array) Name of the contract defined in the configuration file (see documentation), or name of the validation object, or validation contract.
  • $flashVar : (string) Name of the flash variable that will contain the boolean value true if the user is redirected.

5.3Payload: examples

use \Temma\Attributes\Check\Payload as TµCheckPayload;

class Actions extends \Temma\Web\Controller {
    // this action expects a payload containing a JSON stream (no further constraints)
    #[TµCheckPayload('json')]
    public function getStream() {
        // ...
    }

    // expects a JSON stream containing a list of integers
    #[TµCheckPayload([
        'type'     => 'json',
        'contract' => 'list; contract: int'
    ])]
    public function removeItems() {
        // ...
    }

    // expects a base64-encoded image
    #[TµCheckPayload('base64; mime: image')]
    public function uploadAvatar(int $id) {
        // ...
    }

    // expects a JSON stream containing an associative array
    // with defined and typed keys, using strict validation;
    // on error, redirects to '/path/to/error';
    // the '__postErr' flash variable is set to true
    #[TµCheckPayload(
        [
            'type'     => 'json',
            'contract' => [
                'type' => 'assoc',
                'keys' => [
                    'id'   => 'int',
                    'name' => 'string',
                    'role' => 'enum; values: user, member, admin',
                ],
            ],
        ],
        redirect: '/path/to/error',
        flashVar: 'postErr',
    )]
    public function uploadUserList() {
        // ...
    }

    // the payload must validate the contract named "internalUserJson" in
    // the configuration file, defined as follows:
    // 'validationTypes' => [
    //     'internalUserJson' => [
    //         'type'     => 'json',
    //         'contract' => [
    //             'type' => 'assoc',
    //             'keys' => [
    //                 'login' => 'string; minLen: 2',
    //                 'email' => 'email; mask: @mydomain.com$',
    //                 'name'  => 'string; minLen: 2',
    //             ]
    //         ]
    //     ]
    // ]
    #[TµCheckPayload('internalUserJson')]
    public function updateUserData(int $userId) {
        // ...
    }
}

7Output

7.1Output: overview

This attribute defines a validation contract for output data (template variables) for a controller or an action.
It is a wrapper around the setValidationContract() method of the Response object. The defined contract can be used by the view to validate data before sending it to the browser.

Unlike other Check attributes, this attribute does not support common parameters ($strict, $redirect, $redirectVar, $flashVar).


7.2Output: specific parameters

  • $contract : (null|string|array) Name of the contract defined in the configuration file (see documentation), or name of a validation object, or validation contract (see the DataFilter object), or null to remove a previously defined contract.

7.3Output: examples

use \Temma\Attributes\Check\Output as TµCheckOutput;

/*
 * All controller actions must provide a "name" template variable (string)
 * and a "mail" variable (email).
 */
#[TµCheckOutput([
    'name' => 'string',
    'mail' => 'email',
])]
class Actions extends \Temma\Web\Controller {
    // ...
}
use \Temma\Attributes\Check\Output as TµCheckOutput;

class Actions extends \Temma\Web\Controller {
    // checks that the "id" template variable is an integer
    // between 5 and 128, strictly validated
    #[TµCheckOutput(['=id' => 'int; min: 5; max: 128'])]
    public function showItem() {
        // ...
    }

    // checks for a "name" variable (string), a "mail" variable (email),
    // and an optional "balance" variable (float)
    #[TµCheckOutput([
        'name'     => 'string',
        'mail'     => 'email',
        'balance?' => 'float',
    ])]
    public function showUser() {
        // ...
    }

    // output data must validate the contract named "userData"
    // in the configuration file, defined as follows:
    // 'validationTypes' => [
    //     'userData' => [
    //         'id'    => 'int',
    //         'login' => 'string; minLen: 2',
    //         'email' => 'email',
    //     ]
    // ]
    #[TµCheckOutput('userData')]
    public function getUser(int $userId) {
        // ...
    }
}