Skip to content

Commit 5c2c673

Browse files
committed
fix: Create deep copy before checking each sub schema in anyOf
#711
1 parent 7eea9e4 commit 5c2c673

File tree

2 files changed

+50
-2
lines changed

2 files changed

+50
-2
lines changed

src/JsonSchema/Constraints/UndefinedConstraint.php

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -333,11 +333,15 @@ protected function validateOfProperties(&$value, $schema, JsonPointer $path, $i
333333
if (isset($schema->anyOf)) {
334334
$isValid = false;
335335
$startErrors = $this->getErrors();
336+
$coerceOrDefaults = $this->factory->getConfig(self::CHECK_MODE_COERCE_TYPES | self::CHECK_MODE_APPLY_DEFAULTS);
337+
336338
foreach ($schema->anyOf as $anyOf) {
337339
$initErrors = $this->getErrors();
338340
try {
339-
$this->checkUndefined($value, $anyOf, $path, $i);
340-
if ($isValid = (count($this->getErrors()) == count($initErrors))) {
341+
$anyOfValue = $coerceOrDefaults ? DeepCopy::copyOf($value) : $value;
342+
$this->checkUndefined($anyOfValue, $anyOf, $path, $i);
343+
if ($isValid = (count($this->getErrors()) === count($initErrors))) {
344+
$value = $anyOfValue;
341345
break;
342346
}
343347
} catch (ValidationException $e) {

tests/Constraints/UndefinedConstraintTest.php

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,50 @@ public function getValidTests(): array
6969
JSON
7070
,
7171
'checkMode' => Constraint::CHECK_MODE_COERCE_TYPES
72+
],
73+
'anyOf with apply defaults should not affect value passed to each sub schema (#711)' => [
74+
'input' => <<<JSON
75+
{
76+
"b": 2
77+
}
78+
JSON
79+
,
80+
'schema' => <<<JSON
81+
{
82+
"anyOf": [
83+
{
84+
"required": [ "a" ],
85+
"properties": {
86+
"a": {
87+
"type": "integer"
88+
},
89+
"aDefault": {
90+
"type": "integer",
91+
"default": 1
92+
}
93+
},
94+
"type": "object",
95+
"additionalProperties": false
96+
},
97+
{
98+
"required": [ "b" ],
99+
"properties": {
100+
"b": {
101+
"type": "integer"
102+
},
103+
"bDefault": {
104+
"type": "integer",
105+
"default": 2
106+
}
107+
},
108+
"type": "object",
109+
"additionalProperties": false
110+
}
111+
]
112+
}
113+
JSON
114+
,
115+
'checkMode' => Constraint::CHECK_MODE_APPLY_DEFAULTS
72116
]
73117
];
74118
}

0 commit comments

Comments
 (0)