If

The keywords if, then and else can be used to conditionally combine multiple subschemas. Conditional compositions can be used on property level and on object level.

{
    "$id": "example",
    "type": "object",
    "properties": {
        "example": {
            "type": "number",
            "if": {
                "multipleOf": 5
            },
            "then": {
                "minimum": 100
            },
            "else": {
                "maximum": 100
            }
        }
    }
}

Valid values are eg. 100, 105, 99. Invalid values are eg. 50, 101 or any non numeric values.

Generated interface:

public function setExample(float $example): static;
public function getExample(): ?float;

Possible exception (in this case 50 was provided so the if condition succeeds but the then branch failed):

Invalid value for 'example' declined by conditional composition constraint
  - Condition: Valid
  - Conditional branch failed:
    * Value for 'example' must not be smaller than 100

Another example exception with 101 as value for the property:

Invalid value for 'example' declined by conditional composition constraint
  - Condition: Failed
    * Value for 'example' must be a multiple of 5
  - Conditional branch failed:
    * Value for 'example' must not be larger than 100

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

// get the exception which triggered the condition to fail
// if error collection is enabled an ErrorRegistryException will be returned
public function getIfException(): ?Exception

// get the exception which triggered the conditional branch to fail
// if error collection is enabled an ErrorRegistryException will be returned
public function getThenException(): ?Exception
public function getElseException(): ?Exception

// 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

An object level composition will result in an object which contains all properties contained in the three possible blocks of the condition.

{
    "$id": "customer",
    "type": "object",
    "properties": {
        "country": {
            "enum": ["United States of America", "Canada"]
        }
    },
    "if": {
        "type": "object",
        "properties": {
            "country": {
                "const": "United States of America"
            }
        }
    },
    "then": {
        "type": "object",
        "properties": {
            "postal_code": {
                "pattern": "[0-9]{5}(-[0-9]{4})?"
            }
        }
    },
    "else": {
        "type": "object",
        "properties": {
            "postal_code": {
                "pattern": "[A-Z][0-9][A-Z] [0-9][A-Z][0-9]"
            }
        }
    }
}

Generated interface:

public function setCountry(string $country): static;
public function getCountry(): ?string;

public function setPostalCode(string $country): static;
public function getPostalCode(): ?string;

When the then and else branches define the same property with different types, the generator produces a union type hint — consistent with the behaviour of anyOf/oneOf:

{
    "$id": "example",
    "type": "object",
    "if": {
        "properties": {
            "name": {
                "const": "Alice"
            }
        }
    },
    "then": {
        "properties": {
            "age": {
                "type": "integer"
            }
        }
    },
    "else": {
        "properties": {
            "age": {
                "type": "string"
            }
        }
    }
}

Generated interface:

public function setAge(int | string | null $age): static;
public function getAge(): int | string | null;

When only a then block is present (no else), the branch may not apply at runtime and a missing branch doesn’t constrain anything. A value of any type is valid for the property while the if condition fails, so the type hint is widened to mixed. The same applies to a property which is only defined in an else block:

public function setAge(mixed $age): static;
public function getAge(): mixed;

While the branch is active the declared type is still enforced. A property which is additionally defined in the root properties keeps the type of the root definition.

Note

Any of the three branches (if, then, else) can be the boolean literal true or false. The generator resolves these statically at generation time:

  • if: false — condition never matches; else (if present) is applied unconditionally, then is ignored.

  • if: true — condition always matches; then (if present) is applied unconditionally, else is ignored.

  • if: false, else: false or if: true, then: false — the composition is always unsatisfiable; providing any value raises a ConditionalException at runtime. The generator also emits a warning at generation time.

  • then: false / else: false (with a real schema for if) — a value entering the branch is rejected with a ConditionalException at runtime, all other values are valid. E.g. "if": {"required": ["kind"]}, "then": false on an object denies the key kind. If both then and else are false, any provided value is rejected and the generator emits a warning at generation time.

  • then: true / else: true — when the relevant branch is entered, any value is accepted; treated as absent (no additional constraint).

Hint

The union-widening and nullability rules for if/then/else follow the same logic as anyOf/oneOf. See Cross-typed compositions for the full explanation.

Hint

A then/else branch does not need to declare "type": "object" itself to be treated as an object — the generator also detects object-ness implied by a $ref chain or nested allOf, and object-constraining keywords used without any type at all. See Composition-implied objects for the full explanation, including why an object-describing branch (bare properties/required, no type) does not reject a non-object value the way an object-asserting branch does.

Note

An if, then or else schema which declares no type inherits the type of its schema (a schema root always has "type": "object" applied to it). An enum or const of such a schema which lists no value of the inherited type (e.g. {"enum": [1, 2, 3]} inside an object schema) can never be satisfied: an if which can’t match always selects the else schema, a then or else which can’t be satisfied rejects every value it is applied to. The generator emits a warning at generation time.

Note

For object-level if/then/else compositions, when a property appears in the required array of both then and else, the generator promotes that property to non-nullable. Exactly one of the two branches applies at runtime, and both guarantee the property’s presence. If there is no else block, the property is never promoted — the schema is silent when the condition fails, so the property may be absent. See Cross-typed compositions for the full promotion rules.

Note

Properties in object-level then or else branches may carry a "default" value. The generator applies the branch default only when the relevant branch is active — the then default applies when the if condition is satisfied, and the else default applies when it is not. A user-supplied value always overrides the branch default. Branch defaults are not included in meta()->rawInput().

When a then or else branch default conflicts with a root properties default or a patternProperties default for the same property, the generator throws a SchemaException at generation time.

See Default values for the full explanation.

Note

A property in a then or else branch may declare a "filter". The filter only affects the value while its branch is the active one, otherwise the property keeps the value as provided. A filter on a property of the if condition runs inside the condition and is not applied to the generated class. See Filters on properties of object branches.

Note

A transforming "filter" may be declared for the items of an array inside the then or else branch, the items are transformed while the branch is the active one. A filter on the items of the if condition is rejected with a SchemaException: the condition only selects the branch and never transforms the stored value. See Filters on array items.

Property and item evaluation propagation

For an enclosing schema that uses unevaluatedProperties or unevaluatedItems (Draft 2019-09 and later), each of the three branches (if, then, else) contributes independently:

  • if runs unconditionally. When it succeeds, its own declarations count as evaluated — the JSON Schema 2019-09 spec treats if as a positive applicator whose annotations survive.

  • then runs only when if succeeded; it contributes if it also succeeds.

  • else runs only when if failed; it contributes if it succeeds.

At most two of the three branches actually execute per validation call, so the effective contribution is: (if’s + then’s) when the condition holds, or (else’s) when it does not. Each contributing branch credits property names claimed by its properties, patternProperties, and additionalProperties (per key with a passing value), and — on the array side — the indices claimed by its items/additionalItems/contains.

Because branch outcomes depend on the input, the evaluated set is derived per validation call and refreshed whenever the model is mutated. A conditional that fails as a whole (for example a passing if followed by a failing then) contributes nothing, not even the annotations of the passing if — as with a failed allOf, keys it would have claimed show up as unevaluated in the error report when errors are collected.

An if which has neither a then nor an else branch is a valid schema which can never change the validation result. The generator emits a warning at generation time but doesn’t reject the schema: when the instance matches the condition, the properties and items the if evaluates still count as evaluated for an enclosing unevaluatedProperties or unevaluatedItems. Without one of these keywords the if has no effect at all.

A composition nested inside a branch (an anyOf inside an allOf branch, a conditional inside a oneOf branch, …) contributes the claims of its own successful branches to the enclosing branch, to any depth.

Note

Omitting additionalProperties from a branch is not the same as writing additionalProperties: true. An omitted keyword produces no annotation and therefore credits nothing to the enclosing unevaluatedProperties — only an explicit additionalProperties (whether true or {schema}) contributes. Two branches with identical extras behaviour but one writing the keyword and the other omitting it will therefore credit different evaluated sets. This is a spec-mandated distinction from JSON Schema 2019-09. The same rule applies on the array side: an explicit additionalItems credits the indices past the tuple, and an explicit items: true or items: {} credits every index. An explicit unevaluatedProperties: true or unevaluatedItems: true inside a branch likewise credits every key or index, while omitting these keywords credits nothing.

Note

Only this up direction (a branch’s own declarations propagating to an enclosing unevaluatedProperties/unevaluatedItems) is implemented. The reverse — a then or else branch’s own unevaluatedProperties/unevaluatedItems (other than a literal true, which never rejects anything) seeing property names or indices declared by the enclosing schema, if’s own declarations, or the other conditional branch — is not currently supported and throws PHPModelGenerator\Exception\UnsupportedSchemaFeatureException at generation time. See All Of’s equivalent note for a concrete example.