Skip to content

Commit d44cac0

Browse files
shmaxbighappyface
authored andcommitted
handle coercion of multiple types (#322)
1 parent 4f10e03 commit d44cac0

File tree

2 files changed

+24
-12
lines changed

2 files changed

+24
-12
lines changed

src/JsonSchema/Constraints/ObjectConstraint.php

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -201,18 +201,20 @@ protected function toInteger($value)
201201
*/
202202
protected function coerce($value, $definition)
203203
{
204-
$type = isset($definition->type)?$definition->type:null;
205-
if($type){
206-
switch($type){
207-
case "boolean":
208-
$value = $this->toBoolean($value);
209-
break;
210-
case "integer":
211-
$value = $this->toInteger($value);
212-
break;
213-
case "number":
214-
$value = $this->toNumber($value);
215-
break;
204+
$types = isset($definition->type)?$definition->type:null;
205+
if($types){
206+
foreach((array)$types as $type) {
207+
switch ($type) {
208+
case "boolean":
209+
$value = $this->toBoolean($value);
210+
break;
211+
case "integer":
212+
$value = $this->toInteger($value);
213+
break;
214+
case "number":
215+
$value = $this->toNumber($value);
216+
break;
217+
}
216218
}
217219
}
218220
return $value;

tests/Constraints/CoerciveTest.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,10 @@ public function testValidCoerceCases($input, $schema, $errors = array())
5858
$this->assertTrue(gettype($value->integer) == "integer");
5959
$this->assertTrue(gettype($value->boolean) == "boolean");
6060

61+
$this->assertTrue(gettype($value->multitype1) == "boolean");
62+
$this->assertTrue(gettype($value->multitype2) == "double");
63+
$this->assertTrue(gettype($value->multitype3) == "integer");
64+
6165
$this->assertTrue($validator->isValid(), print_r($validator->getErrors(), true));
6266
}
6367

@@ -112,6 +116,9 @@ public function getValidCoerceTests()
112116
"array":[],
113117
"null":null,
114118
"any": "string",
119+
"multitype1": "false",
120+
"multitype2": "1.2",
121+
"multitype3": "7",
115122
"any1": 2.6,
116123
"any2": 4,
117124
"any3": false,
@@ -130,6 +137,9 @@ public function getValidCoerceTests()
130137
"array":{"type":"array"},
131138
"null":{"type":"null"},
132139
"any": {"type":"any"},
140+
"multitype1": {"type":["boolean","integer","number"]},
141+
"multitype2": {"type":["boolean","integer","number"]},
142+
"multitype3": {"type":["boolean","integer","number"]},
133143
"any1": {"type":"any"},
134144
"any2": {"type":"any"},
135145
"any3": {"type":"any"},

0 commit comments

Comments
 (0)