Array

There are two types of arrays in JSON-Schema definitions: lists and tuples. Both types are supported by the model generator.

Lists

A simple array without further restrictions can be defined using array.

{
    "$id": "example",
    "type": "object",
    "properties": {
        "example": {
            "type": "array"
        }
    }
}

Generated interface:

public function setExample(array $example): static;
// As the property is not required it may be initialized with null. Consequently the return value is nullable
public function getExample(): ?array;

Possible exceptions:

  • Invalid type for ‘example’: requires ‘array’, got ‘__TYPE__’

The thrown exception will be a PHPModelGenerator\Exception\Generic\InvalidTypeException which provides the following methods to get further error details:

// returns a string if the property expects exactly one type, an array if the property accepts multiple types
public function getExpectedType()
// get the name of the property which failed
public function getPropertyName(): string
// get the value provided to the property
public function getProvidedValue()
// get the JSON pointer to the schema keyword that rejected the value
public function getJsonPointer(): JsonPointer

Items

The items of a list can be restricted with a nested schema. All items of the schema must match the defined schema.

{
    "$id": "example",
    "type": "object",
    "properties": {
        "example": {
            "type": "array",
            "items": {
                "type": "string",
                "minLength": 2
            }
        }
    }
}

With a schema like this all items must contain a string with at least two characters. Possible exceptions:

Invalid items in array 'example':
  - invalid item #3
    * Invalid type for 'example': requires 'string', got 'double'

The thrown exception will be a PHPModelGenerator\Exception\Arrays\InvalidItemException which provides the following methods to get further error details:

// returns a two-dimensional array which contains all validation exceptions grouped by item index
public function getInvalidItems(): array
// get the name of the property which failed
public function getPropertyName(): string
// get the value provided to the property
public function getProvidedValue()
// get the JSON pointer to the schema keyword that rejected the value
public function getJsonPointer(): JsonPointer

A more complex array may contain a nested object.

{
    "$id": "example",
    "type": "family",
    "properties": {
        "members": {
            "type": "array",
            "items": {
                "type": "object",
                "$id": "member",
                "properties": {
                    "name": {
                        "type": "string"
                    },
                    "age": {
                        "type": "integer",
                        "minimum": 0
                    }
                },
                "required": [
                    "name"
                ]
            }
        }
    }
}

In this case the model generator will generate two classes: Family and Member. Generated interfaces:

// class Family
public function setMembers(array $members): static;
public function getMembers(): ?array;

// class Member
public function setName(string $name): static;
public function getName(): string;

public function setAge(int $age): static;
public function getAge(): ?int;

The getMembers function of the class Family is type hinted with @returns Member[]. Consequently auto completion is available when developing something like:

$family = new Family($inputArray);

foreach ($family->getMembers() as $member) {
    // auto completion with available methods on $member
    $member->getName();
}

Hint

Arrays with item validation don’t accept elements which contain null. If your array needs to accept null entries you have to add null to the type of your items explicitly (eg. “type”: [“object”, “null”]).

The items keyword also accepts the boolean literals true and false.

items: true — any array element is accepted; equivalent to not specifying items.

items: false — the array must be empty. Providing a non-empty array throws a MaxItemsException (Array X must not contain more than 0 items).

Hint

The items may be transformed by a filter (eg. dateTime), also if they are declared inside a branch of a composition, as tuple items or unevaluatedItems or inside nested arrays (arrays which are items of an array). The array then contains the transformed items. See Filters on array items.

Tuples

A tuple array defines the structure of each array item on it’s own. A tuple array is defined by providing an array of schemas with the items keyword.

Items

{
    "$id": "example",
    "type": "object",
    "properties": {
        "example": {
            "type": "array",
            "items": [
                {
                    "type": "string",
                    "minLength": 2
                },
                {
                    "type": "object",
                    "properties": {
                        "name": {
                            "type": "string"
                        }
                    }
                }
            ]
        }
    }
}

If invalid tuples are provided a detailed exception will be thrown containing all violations:

Invalid tuple item in array 'example':
  - invalid tuple #1
    * Invalid type for 'tuple item #1 of array example': requires 'string', got 'integer'
  - invalid tuple #1
    * Invalid type for 'name': requires 'string', got 'boolean'

The thrown exception will be a PHPModelGenerator\Exception\Arrays\InvalidTupleException which provides the following methods to get further error details:

// returns a two-dimensional array which contains all validation exceptions grouped by item index
public function getInvalidTuples()
// get the name of the property which failed
public function getPropertyName(): string
// get the value provided to the property
public function getProvidedValue()
// get the JSON pointer to the schema keyword that rejected the value
public function getJsonPointer(): JsonPointer

Hint

Incomplete tuples are valid. Consequently an empty array provided for the schema shown above would pass the validation. Keep this in mind when designing tuple constraints. To force the given data to provide all tuples use tuple items combined with the minItems array size validation.

Additional items

Using the keyword additionalItems the array can be limited to not contain any other value by providing false. If a schema is provided all additional items must be valid against the provided schema. Simple checks like ‘must contain a string’ are possible as well as checks like ‘must contain an object with a specific structure’.

{
    "$id": "example",
    "type": "object",
    "properties": {
        "example": {
            "type": "array",
            "items": [
                {
                    "type": "string",
                    "minLength": 2
                },
                {
                    "type": "integer"
                },
            ],
            "additionalItems": {
                "type": "object",
                "properties": {
                    "name": {
                        "type": "string"
                    }
                }
            }
        }
    }
}

Possible exceptions:

  • Tuple array ‘example’ contains not allowed additional items: expected 2 items, got 3

The thrown exception will be a PHPModelGenerator\Exception\Arrays\AdditionalTupleItemsException which provides the following methods to get further error details:

// Get the expected tuple amount
public function getExpectedAmount(): int
// Get the amount of items provided
public function getAmount(): int
// get the name of the property which failed
public function getPropertyName(): string
// get the value provided to the property
public function getProvidedValue()
// get the JSON pointer to the schema keyword that rejected the value
public function getJsonPointer(): JsonPointer

If invalid additional items are provided a detailed exception will be thrown containing all violations:

Tuple array 'property' contains invalid additional items
  - invalid additional item '3'
    * Invalid type for 'name': requires 'string', got 'integer'
  - invalid additional item '5'
    * Invalid type for 'additional item': requires 'object', got 'integer'

The thrown exception will be a PHPModelGenerator\Exception\Arrays\InvalidAdditionalTupleItemsException which provides the following methods to get further error details:

// returns a two-dimensional array which contains all validation exceptions grouped by item index
public function getNestedExceptions(): array
// get the name of the property which failed
public function getPropertyName(): string
// get the value provided to the property
public function getProvidedValue()
// get the JSON pointer to the schema keyword that rejected the value
public function getJsonPointer(): JsonPointer

Contains

The contains check uses a schema which must match at least one of the items provided in the input data to pass the validation. Simple checks like ‘must contain a string’ are possible as well as checks like ‘must contain an object with a specific structure’.

{
    "$id": "example",
    "type": "object",
    "properties": {
        "example": {
            "type": "array",
            "contains": {
                "type": "string"
            }
        }
    }
}

Possible exceptions:

  • No item in array ‘example’ matches the ‘contains’ constraint

The thrown exception will be a PHPModelGenerator\Exception\Arrays\ContainsException which provides the following methods to get further error details:

// get the name of the property which failed
public function getPropertyName(): string
// get the value provided to the property
public function getProvidedValue()
// get the JSON pointer to the schema keyword that rejected the value
public function getJsonPointer(): JsonPointer

The contains keyword also accepts the boolean literals true and false.

contains: true — the array must contain at least one element (since true validates everything, any element satisfies the constraint).

contains: false — no element could ever satisfy the constraint; any array value raises a ContainsException at runtime. The generator also emits a warning at generation time.

Limiting the number of matches

Since Draft 2019-09 the number of items which must match the contains schema can be limited with minContains and maxContains. Both must be non-negative integers. If minContains is omitted it defaults to 1, if maxContains is omitted the number of matches is not limited. Draft 7 ignores both keywords.

{
    "$id": "example",
    "type": "object",
    "properties": {
        "example": {
            "type": "array",
            "contains": {
                "type": "string"
            },
            "minContains": 0,
            "maxContains": 0
        }
    }
}

minContains: 0 makes the contains constraint optional. Combined with maxContains: 0 only arrays in which no item matches the contains schema are valid. Contradicting limits are rejected with a SchemaException while the classes are generated: minContains larger than maxContains as well as maxContains: 0 without minContains: 0, as the omitted minContains defaults to 1.

Possible exceptions:

  • Array ‘example’ must not contain less than 2 items matching the contains constraint, 1 matching items provided

  • Array ‘example’ must not contain more than 0 items matching the contains constraint, 1 matching items provided

The thrown exceptions will be a PHPModelGenerator\Exception\Arrays\MinContainsException or a PHPModelGenerator\Exception\Arrays\MaxContainsException. They provide the following methods to get further error details:

// get the name of the property which failed
public function getPropertyName(): string
// get the value provided to the property
public function getProvidedValue()
// get the JSON pointer to the schema keyword that rejected the value
public function getJsonPointer(): JsonPointer
// get the number of items which match the contains schema
public function getMatches(): int
// get the configured minContains (MinContainsException) or maxContains (MaxContainsException)
public function getMinContains(): int
public function getMaxContains(): int

Unevaluated Items

The unevaluatedItems keyword (Draft 2019-09 and later) constrains every index that was not evaluated by any positive sibling applicator at the same schema level. Indices claimed by items (single-schema or tuple form), by prefixItems (the Draft 2020-12 spelling of the tuple form), by the keyword covering the entries behind the tuple when present, by a passing contains match, or by a successful composition branch (allOf, anyOf, oneOf, if/then/else, $ref) count as evaluated. not is a negative applicator and contributes nothing.

Unlike additionalItems, unevaluatedItems looks across composition branches: an index covered by a branch that ended up succeeding is credited, and an index covered only by a branch that failed is not. Compositions nested inside a branch contribute their own successful branches the same way, to any depth.

A property subschema that declares array applicators but omits type: array is treated as an array property: the keywords apply whenever the provided value is an array, and a value of any other type passes through unchanged.

Note

additionalItems only claims indices when a tuple sits in front of it. Declared on its own, without a tuple-form items/prefixItems alongside it, the keyword has no effect and claims nothing — so every index stays unevaluated. This holds identically whether the keyword is declared directly on the array property or inside one of its composition branches.

Tuple items in Draft 2020-12

Draft 2020-12 renamed the tuple form of items to prefixItems and reused items itself for the entries behind the tuple — the role additionalItems fills in earlier drafts. Both spellings validate positionally and contribute the same evaluated indices:

{
    "$id": "example",
    "type": "object",
    "properties": {
        "example": {
            "type": "array",
            "prefixItems": [
                {
                    "type": "string"
                }
            ],
            "unevaluatedItems": false
        }
    }
}

Index 0 is validated against the prefixItems entry and counted as evaluated; every further element raises an UnevaluatedItemsException. Adding "items": {"type": "integer"} alongside prefixItems instead validates every element from index 1 on, leaving nothing unevaluated.

prefixItems must be a list of schemas. Any other value (a single schema, a boolean, a scalar) is invalid and rejected with a SchemaException when the model is generated; a scalar items is rejected the same way. An empty prefixItems is read as a tuple without entries, so items validates every element.

On Draft 7 and Draft 2019-09 prefixItems is not a known keyword and is ignored, so items keeps its own meaning there and still validates every element. Being ignored also means it evaluates no index: the schema above rejects ["a"] on Draft 2019-09, where nothing evaluates index 0, whether the keyword is declared on the array property or inside one of its composition branches.

Using false

Setting unevaluatedItems: false forbids any array index left uncovered by a sibling.

{
    "$id": "example",
    "type": "object",
    "properties": {
        "example": {
            "type": "array",
            "items": [
                {
                    "type": "string"
                }
            ],
            "allOf": [
                {
                    "items": [
                        {
                            "type": "string"
                        },
                        {
                            "type": "integer"
                        }
                    ]
                }
            ],
            "unevaluatedItems": false
        }
    }
}

Indices 0 and 1 are covered by the tuple items of the outer or the allOf branch. Any further element raises an UnevaluatedItemsException with the offending indices:

Provided JSON for 'example' contains not allowed unevaluated items [#2, #3]

The thrown exception will be a PHPModelGenerator\Exception\Arrays\UnevaluatedItemsException which provides the following methods to get further error details:

// Get the zero-based indices of the offending items
public function getUnevaluatedItems(): array
// get the name of the property which failed
public function getPropertyName(): string
// get the value provided to the property
public function getProvidedValue()
// get the JSON pointer to the schema keyword that rejected the value
public function getJsonPointer(): JsonPointer

Using a schema

When unevaluatedItems is set to a schema, every unevaluated index’s value must validate against that schema:

{
    "$id": "example",
    "type": "object",
    "properties": {
        "example": {
            "type": "array",
            "items": [
                {
                    "type": "string"
                }
            ],
            "unevaluatedItems": {
                "type": "integer"
            }
        }
    }
}

If invalid unevaluated items are provided a detailed exception is thrown containing all violations:

Invalid unevaluated items in array 'example':
  - invalid unevaluated item #1
    * Invalid type for 'unevaluated item': requires 'int', got 'string'

The thrown exception will be a PHPModelGenerator\Exception\Arrays\InvalidUnevaluatedItemsException which provides the following methods to get further error details:

// returns a two-dimensional array which contains all validation exceptions grouped by item index
public function getInvalidItems(): array
// get the name of the property which failed
public function getPropertyName(): string
// get the value provided to the property
public function getProvidedValue()
// get the JSON pointer to the schema keyword that rejected the value
public function getJsonPointer(): JsonPointer

Interaction with sibling applicators

When a sibling applicator already claims every index, the unevaluatedItems validator has nothing to check. The generator recognises these dead-code shapes at generation time, emits a warning, and skips unevaluatedItems entirely:

  • items: false rejects every index, so the array is forced empty.

  • items: true, items: {} or items: {schema} in single-schema form leave no unclaimed index at all, because items covers every position.

  • additionalItems: false alongside tuple items blocks any index past the tuple length — every index is either tuple-covered (and evaluated) or rejected by additionalItems.

  • additionalItems: true or additionalItems: {schema} alongside tuple items accepts and evaluates every index past the tuple length (a schema additionally validates it) — every index is again claimed. A tail value is accepted or rejected by additionalItems alone; a skipped unevaluatedItems schema never takes part in the decision.

  • items behind a prefixItems tuple (Draft 2020-12) is the same pair under the new spelling: items: false rejects every index past the tuple, items: true or items: {schema} accepts and evaluates it. Behind a tuple items only governs the tail, so the warning names the pair (sibling prefixItems tuple plus items: ...) instead of describing items as if it covered every index.

Unlike additionalProperties on objects, the deny additional properties setting has no effect on arrays: an index past a tuple stays subject to unevaluatedItems.

Note

contains credits only the indices that actually satisfy its subschema, so any index not matched by contains remains available for unevaluatedItems. When minContains: 0 is set, contains may succeed with zero matches and contributes nothing to the evaluated set.

Note

unevaluatedItems also accepts the boolean literal true. On its own this is a no-op — every index is considered evaluated — and no validator is emitted. Inside a composition branch an explicit unevaluatedItems: true (like items: true or items: {}) annotates every index of the array, so a successful branch credits all of them to an enclosing unevaluatedItems. An omitted keyword produces no annotation.

Hint

See combined schemas for the per-keyword rules that govern how each composition contributes to the evaluated set.

Size validation

To limit the size of an array use the minItems and maxItems keywords.

{
    "$id": "example",
    "type": "object",
    "properties": {
        "example": {
            "type": "array",
            "minItems": 2,
            "maxItems": 5
        }
    }
}

Possible exceptions:

  • Array ‘example’ must not contain less than 2 items

  • Array ‘example’ must not contain more than 5 items

The thrown exception will be a PHPModelGenerator\Exception\Arrays\MaxItemsException or a PHPModelGenerator\Exception\Arrays\MinItemsException which provides the following methods to get further error details:

// for a MaxItemsException: get the maximum amount of allowed items
public function getMaxItems(): int
// for a MinItemsException: get the minimum amount of required items
public function getMinItems(): int
// get the name of the property which failed
public function getPropertyName(): string
// get the value provided to the property
public function getProvidedValue()
// get the JSON pointer to the schema keyword that rejected the value
public function getJsonPointer(): JsonPointer

Uniqueness

The items of an array can be forced to be unique with the uniqueItems keyword.

Items are compared as JSON values: objects are equal if they contain the same keys with equal values, independent of the order of the keys, and numbers are equal if they have the same value, independent of their type (1 and 1.0 are the same item). The order of the items of a nested list matters. Values of different types are never equal, so 0, false, null, "" and "0" are five different items. Items which are transformed into model instances are compared by the data they were created from.

{
    "$id": "example",
    "type": "object",
    "properties": {
        "example": {
            "type": "array",
            "uniqueItems": true
        }
    }
}

Possible exceptions:

  • Items of array ‘example’ are not unique

The thrown exception will be an PHPModelGenerator\Exception\Arrays\UniqueItemsException which provides the following methods to get further error details:

// get the name of the property which failed
public function getPropertyName(): string
// get the value provided to the property
public function getProvidedValue()
// get the JSON pointer to the schema keyword that rejected the value
public function getJsonPointer(): JsonPointer