Skip to content

Commit 252e023

Browse files
committed
Merge pull request #103 from alexmmm/fix-required-property-validation
Fix required property validation
2 parents d97cf3c + e8a72f0 commit 252e023

File tree

2 files changed

+71
-4
lines changed

2 files changed

+71
-4
lines changed

src/JsonSchema/Constraints/Undefined.php

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -117,14 +117,15 @@ protected function validateCommonProperties($value, $schema = null, $path = null
117117

118118
// Verify required values
119119
if (is_object($value)) {
120-
if (isset($schema->required) && is_array($schema->required) ) {
120+
121+
if (!($value instanceof Undefined) && isset($schema->required) && is_array($schema->required) ) {
121122
// Draft 4 - Required is an array of strings - e.g. "required": ["foo", ...]
122123
foreach ($schema->required as $required) {
123124
if (!property_exists($value, $required)) {
124125
$this->addError($path, "the property " . $required . " is required");
125126
}
126127
}
127-
} else if (isset($schema->required)) {
128+
} else if (isset($schema->required) && !is_array($schema->required)) {
128129
// Draft 3 - Required attribute - e.g. "foo": {"type": "string", "required": true}
129130
if ( $schema->required && $value instanceof Undefined) {
130131
$this->addError($path, "is missing and it is required");

tests/JsonSchema/Tests/Constraints/RequiredPropertyTest.php

Lines changed: 68 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,40 @@ public function getInvalidTests()
144144
"null":{"type":"null", "required": true}
145145
}
146146
}'
147-
)
147+
),
148+
array(
149+
'{
150+
"foo": {"baz": 1.5}
151+
}',
152+
'{
153+
"type": "object",
154+
"properties": {
155+
"foo": {
156+
"type": "object",
157+
"properties": {
158+
"bar": {"type": "number"}
159+
},
160+
"required": ["bar"]
161+
}
162+
}
163+
}'
164+
),
165+
array(
166+
'{
167+
"foo": {"baz": 1.5}
168+
}',
169+
'{
170+
"type": "object",
171+
"properties": {
172+
"foo": {
173+
"type": "object",
174+
"properties": {
175+
"bar": {"type": "number", "required": true}
176+
}
177+
}
178+
}
179+
}'
180+
),
148181
);
149182
}
150183

@@ -266,7 +299,40 @@ public function getValidTests()
266299
"foo": { "required": true }
267300
}
268301
}'
269-
)
302+
),
303+
array(
304+
'{
305+
"boo": {"bar": 1.5}
306+
}',
307+
'{
308+
"type": "object",
309+
"properties": {
310+
"foo": {
311+
"type": "object",
312+
"properties": {
313+
"bar": {"type": "number"}
314+
},
315+
"required": ["bar"]
316+
}
317+
}
318+
}'
319+
),
320+
array(
321+
'{
322+
"boo": {"bar": 1.5}
323+
}',
324+
'{
325+
"type": "object",
326+
"properties": {
327+
"foo": {
328+
"type": "object",
329+
"properties": {
330+
"bar": {"type": "number", "required": true}
331+
}
332+
}
333+
}
334+
}'
335+
),
270336
);
271337
}
272338
}

0 commit comments

Comments
 (0)