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

Add support for type coercion #308

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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,30 @@ if ($validator->isValid()) {
}
}
```
###Type Coercion
If you're validating data passed to your application via HTTP, you can cast strings and booleans to the expected types defined by your schema:
```
$request = (object)[
'processRefund'=>"true",
'refundAmount'=>"17"
];

$validator = new \JsonSchema\Validator(\JsonSchema\Constraints\Constraint::CHECK_MODE_COERCE);
$validator->check($request, (object) [
"type"=>"object",
"properties"=>[
"processRefund"=>[
"type"=>"boolean"
],
"refundAmount"=>[
"type"=>"number"
]
]
]); // validates!

is_bool($request->processRefund); // true
is_int($request->refundAmount); // true
```

## Running the tests

Expand Down
1 change: 1 addition & 0 deletions src/JsonSchema/Constraints/Constraint.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ abstract class Constraint implements ConstraintInterface

const CHECK_MODE_NORMAL = 1;
const CHECK_MODE_TYPE_CAST = 2;
const CHECK_MODE_COERCE = 3;

/**
* @var null|Factory
Expand Down
2 changes: 1 addition & 1 deletion src/JsonSchema/Constraints/EnumConstraint.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public function check($element, $schema = null, JsonPointer $path = null, $i = n

foreach ($schema->enum as $enum) {
$enumType = gettype($enum);
if ($this->checkMode === self::CHECK_MODE_TYPE_CAST && $type == "array" && $enumType == "object") {
if (($this->checkMode === self::CHECK_MODE_TYPE_CAST || $this->checkMode === self::CHECK_MODE_COERCE) && $type == "array" && $enumType == "object") {
if ((object)$element == $enum) {
return;
}
Expand Down
3 changes: 2 additions & 1 deletion src/JsonSchema/Constraints/Factory.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ class Factory
'format' => 'JsonSchema\Constraints\FormatConstraint',
'schema' => 'JsonSchema\Constraints\SchemaConstraint',
'validator' => 'JsonSchema\Validator',
'coercer' => 'JsonSchema\Coerce'
);

/**
Expand Down Expand Up @@ -92,7 +93,7 @@ public function getSchemaStorage()
public function getTypeCheck()
{
if (!isset($this->typeCheck[$this->checkMode])) {
$this->typeCheck[$this->checkMode] = $this->checkMode === Constraint::CHECK_MODE_TYPE_CAST
$this->typeCheck[$this->checkMode] = ($this->checkMode === Constraint::CHECK_MODE_TYPE_CAST || $this->checkMode === Constraint::CHECK_MODE_COERCE)
? new TypeCheck\LooseTypeCheck
: new TypeCheck\StrictTypeCheck;
}
Expand Down
69 changes: 68 additions & 1 deletion src/JsonSchema/Constraints/ObjectConstraint.php
Original file line number Diff line number Diff line change
Expand Up @@ -121,17 +121,83 @@ public function validateElement($element, $matches, $objectDefinition = null, Js
*/
public function validateDefinition($element, $objectDefinition = null, JsonPointer $path = null)
{
$default = $this->getFactory()->createInstanceFor('undefined');

foreach ($objectDefinition as $i => $value) {
$property = $this->getProperty($element, $i, $this->getFactory()->createInstanceFor('undefined'));
$property = $this->getProperty($element, $i, $default);
$definition = $this->getProperty($objectDefinition, $i);

if($this->checkMode == Constraint::CHECK_MODE_COERCE){
if(!($property instanceof Constraint)) {
$element->{$i} = $property = $this->coerce($property, $definition);
}
}

if (is_object($definition)) {
// Undefined constraint will check for is_object() and quit if is not - so why pass it?
$this->checkUndefined($property, $definition, $path, $i);
}
}
}

/**
* Converts a value to boolean. For example, "true" becomes true.
* @param $value The value to convert to boolean
* @return bool|mixed
*/
protected function toBoolean($value)
{
if($value === "true"){
return true;
}

if($value === "false"){
return false;
}

return $value;
}

/**
* Converts a numeric string to a number. For example, "4" becomes 4.
*
* @param mixed $value The value to convert to a number.
* @return int|float|mixed
*/
protected function toNumber($value)
{
if(is_numeric($value)) {
return $value + 0; // cast to number
}

return $value;
}

/**
* Given a value and a definition, attempts to coerce the value into the
* type specified by the definition's 'type' property.
*
* @param mixed $value Value to coerce.
* @param \stdClass $definition A definition with information about the expected type.
* @return bool|int|string
*/
protected function coerce($value, $definition)
{
$type = isset($definition->type)?$definition->type:null;
if($type){
switch($type){
case "boolean":
$value = $this->toBoolean($value);
break;

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dead space

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

removed

case "number":
$value = $this->toNumber($value);
break;
}
}
return $value;
}

/**
* retrieves a property from an object or array
*
Expand All @@ -146,6 +212,7 @@ protected function getProperty($element, $property, $fallback = null)
if (is_array($element) /*$this->checkMode == self::CHECK_MODE_TYPE_CAST*/) {
return array_key_exists($property, $element) ? $element[$property] : $fallback;
} elseif (is_object($element)) {

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dead space

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

removed

return property_exists($element, $property) ? $element->$property : $fallback;
}

Expand Down
1 change: 0 additions & 1 deletion src/JsonSchema/Validator.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@

namespace JsonSchema;

use JsonSchema\Constraints\SchemaConstraint;
use JsonSchema\Constraints\Constraint;
use JsonSchema\Entity\JsonPointer;

Expand Down