Skip to content

ArrayGate

Verja\ArrayGate validates a list — an indexed array where every element follows the same rules. It is used via Gate::array() but can also be instantiated directly.

Required by default

An ArrayGate requires the value to be a non-null array unless 'nullable' is passed explicitly. Pass 'nullable' to allow the field to be absent or null:

->array('tags')            // required: must be present and be an array
->array('tags', 'nullable') // optional: null / absent is allowed

Element gate

The last argument to Gate::array() or new ArrayGate() can be an element gate that defines how each element in the list is validated. It can be:

  • A GateInterface instance (Gate, ArrayGate, PropertyGate)
  • A numeric-keyed array of string/object definitions (shorthand for a PropertyGate)
// Each element must be a trimmed, non-empty slug
->array('tags', ['trim', 'slug', 'notEmpty'])

// Each element is a structured object
->array('items', (new Gate())
    ->int('id', 'required')
    ->string('label', 'required')
)

// Each element must be a positive integer
->array('itemIds', 'min:1', ['integer', 'min:1'])
//                  ↑ array-level validator    ↑ element-level validator

Array-level validators

Arguments before the element gate apply to the array as a whole. For example min:1 checks that the array contains at least one element, max:10 that it has at most ten:

->array('tags', 'min:1', 'max:10', ['trim', 'slug'])
//              ↑ at least 1       ↑ element definition

Between, Min, and Max count array elements when applied to arrays.

Execution order

For each ArrayGate validation:

  1. Prefix validators (required / nullable) — fail fast
  2. IsArray — ensures the value is an array
  3. Array-level filters and validators (e.g. min:1)
  4. Element iteration — each element is validated against the element gate

Element errors appear in errorMap as fieldName.0, fieldName.1, etc.

Using ArrayGate directly

use Verja\ArrayGate;

// List of email addresses, at least one required
$gate = new ArrayGate('min:1', ['required', 'emailAddress']);

$result = $gate->validate(['alice@example.com', 'not-an-email']);
// $result->valid === false
// $result->errorMap === ['1' => [Error(NO_EMAIL_ADDRESS, ...)]]

Nullable example

$gate = (new Gate())
    ->string('title', 'required')
    ->array('attachments', 'nullable', (new Gate())
        ->string('filename', 'required')
        ->int('size', 'required', 'max:10485760')
    );

// Passing null for 'attachments' is valid
$result = $gate->validate(['title' => 'Hello', 'attachments' => null]);
// $result->valid === true