Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

handle coercion of multiple types #322

Merged
merged 1 commit into from
Oct 24, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 14 additions & 12 deletions src/JsonSchema/Constraints/ObjectConstraint.php
Original file line number Diff line number Diff line change
Expand Up @@ -201,18 +201,20 @@ protected function toInteger($value)
*/
protected function coerce($value, $definition)
{
$type = isset($definition->type)?$definition->type:null;
if($type){
switch($type){
case "boolean":
$value = $this->toBoolean($value);
break;
case "integer":
$value = $this->toInteger($value);
break;
case "number":
$value = $this->toNumber($value);
break;
$types = isset($definition->type)?$definition->type:null;
if($types){
foreach((array)$types as $type) {
switch ($type) {
case "boolean":
$value = $this->toBoolean($value);
break;
case "integer":
$value = $this->toInteger($value);
break;
case "number":
$value = $this->toNumber($value);
break;
}
}
}
return $value;
Expand Down
10 changes: 10 additions & 0 deletions tests/Constraints/CoerciveTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@ public function testValidCoerceCases($input, $schema, $errors = array())
$this->assertTrue(gettype($value->integer) == "integer");
$this->assertTrue(gettype($value->boolean) == "boolean");

$this->assertTrue(gettype($value->multitype1) == "boolean");
$this->assertTrue(gettype($value->multitype2) == "double");
$this->assertTrue(gettype($value->multitype3) == "integer");

$this->assertTrue($validator->isValid(), print_r($validator->getErrors(), true));
}

Expand Down Expand Up @@ -112,6 +116,9 @@ public function getValidCoerceTests()
"array":[],
"null":null,
"any": "string",
"multitype1": "false",
"multitype2": "1.2",
"multitype3": "7",
"any1": 2.6,
"any2": 4,
"any3": false,
Expand All @@ -130,6 +137,9 @@ public function getValidCoerceTests()
"array":{"type":"array"},
"null":{"type":"null"},
"any": {"type":"any"},
"multitype1": {"type":["boolean","integer","number"]},
"multitype2": {"type":["boolean","integer","number"]},
"multitype3": {"type":["boolean","integer","number"]},
"any1": {"type":"any"},
"any2": {"type":"any"},
"any3": {"type":"any"},
Expand Down