Skip to content

Commit

Permalink
Add array coercion cases from ajv matrix
Browse files Browse the repository at this point in the history
  • Loading branch information
erayd committed Mar 13, 2017
1 parent 79b5881 commit 867f8a5
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 8 deletions.
20 changes: 20 additions & 0 deletions src/JsonSchema/Constraints/TypeConstraint.php
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,10 @@ protected function validateType(&$value, $type, $coerce = false)
}

if ('array' === $type) {
if ($coerce) {
$value = $this->toArray($value);
}

return $this->getTypeCheck()->isArray($value);
}

Expand Down Expand Up @@ -271,4 +275,20 @@ protected function toInteger($value)

return $value;
}

/**
* Converts a value to an array containing that value
*
* @param mixed $value
*
* @return array
*/
protected function toArray($value)
{
if (is_scalar($value) || is_null($value)) {
return array($value);
}

return $value;
}
}
22 changes: 14 additions & 8 deletions tests/Constraints/CoerciveTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,8 @@ public function getValidCoerceTests()
"boolean":"true",
"object":{},
"array":[],
"nullArray":null,
"stringArray":"string",
"null":null,
"any": "string",
"allOf": "1",
Expand All @@ -155,6 +157,8 @@ public function getValidCoerceTests()
"boolean":{"type":"boolean"},
"object":{"type":"object"},
"array":{"type":"array"},
"nullArray":{"type":"array"},
"stringArray":{"type":"array"},
"null":{"type":"null"},
"any": {"type":"any"},
"allOf" : {"allOf":[{
Expand Down Expand Up @@ -195,7 +199,7 @@ public function getValidCoerceTests()
public function getInvalidCoerceTests()
{
return array(
array(
array( // #0
'{
"string":null
}',
Expand All @@ -207,7 +211,7 @@ public function getInvalidCoerceTests()
"additionalProperties":false
}',
),
array(
array( // #1
'{
"number":"five"
}',
Expand All @@ -219,7 +223,7 @@ public function getInvalidCoerceTests()
"additionalProperties":false
}',
),
array(
array( // #2
'{
"integer":"5.2"
}',
Expand All @@ -231,7 +235,7 @@ public function getInvalidCoerceTests()
"additionalProperties":false
}',
),
array(
array( // #3
'{
"boolean":"0"
}',
Expand All @@ -243,7 +247,7 @@ public function getInvalidCoerceTests()
"additionalProperties":false
}',
),
array(
array( // #4
'{
"object":null
}',
Expand All @@ -255,9 +259,11 @@ public function getInvalidCoerceTests()
"additionalProperties":false
}',
),
array(
array( // #5
'{
"array":null
"array":{
"string":"string"
}
}',
'{
"type":"object",
Expand All @@ -267,7 +273,7 @@ public function getInvalidCoerceTests()
"additionalProperties":false
}',
),
array(
array( // #6
'{
"null":1
}',
Expand Down

0 comments on commit 867f8a5

Please sign in to comment.