The IfThenElseSchema applies one of two schemas depending on a condition: when the if schema matches, the then schema is applied, otherwise the else schema. It covers the JSON Schema if / then / else keywords.
use Chubbyphp\Parsing\Parser;
$p = new Parser();
$schema = $p->if($p->string())
->then($p->string()->minLength(3))
->else($p->int()->minimum(0))
;
$data = $schema->parse('test'); // Returns: 'test' (string, validated by then)
$data = $schema->parse(42); // Returns: 42 (not a string, validated by else)
$data = $schema->parse('ab'); // Throws error (string, but then fails)
$data = $schema->parse(-1); // Throws error (not a string, and else fails)- The input is checked against the
ifschema — as a pure condition: its coercions and transformations never leak, the chosen branch receives the original input - If the
ifschema matches, thethenschema is applied and its output returned, otherwise theelseschema - An absent branch means no constraint — the input is returned unchanged (JSON Schema: an absent
then/elseacts astrue) - When the applied branch fails, its errors propagate unchanged —
IfThenElseSchemaproduces no errors of its own
$schema = $p->if($p->assoc(['country' => $p->const('CH')])->additionalProperties($p->any()))
->then($p->assoc(['country' => $p->string(), 'postalCode' => $p->string()->pattern('/^\d{4}$/')]))
->else($p->assoc(['country' => $p->string(), 'postalCode' => $p->string()]))
;// only constrains strings, everything else passes unchanged
$schema = $p->if($p->string())->then($p->string()->minLength(3));
$schema->parse('test'); // Returns: 'test'
$schema->parse(42); // Returns: 42 (untouched)An else schema works without a then schema just as well: $p->if($ifSchema)->else($elseSchema).
ifis condition-only:$p->if($p->string()->toUpperCase())->then($p->const('test'))parses'test'successfully — thethenbranch receives the original'test', not'TEST'.nullinput:nullis evaluated against theifschema like any other value; withnullable(),nullshort-circuits before the condition is checked.ifschemas that cannot fail: anifschema withcatch()ordefault()may always succeed, which makes theelsebranch unreachable.- Error details: only the applied branch's errors are reported; the
ifschema's outcome is a decision, not an error.
IfThenElseSchema itself never produces an error — the applied branch schema's errors propagate unchanged.