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

For missing properties, the key for that error in set to "" #154

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
2 changes: 1 addition & 1 deletion src/JsonSchema/Constraints/UndefinedConstraint.php
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ protected function validateCommonProperties($value, $schema = null, $path = null
// Draft 4 - Required is an array of strings - e.g. "required": ["foo", ...]
foreach ($schema->required as $required) {
if (!property_exists($value, $required)) {
$this->addError($path, "the property " . $required . " is required");
$this->addError($required, "the property " . $required . " is required");
}
}
} else if (isset($schema->required) && !is_array($schema->required)) {
Expand Down
64 changes: 64 additions & 0 deletions tests/JsonSchema/Tests/Constraints/RequiredPropertyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,72 @@

namespace JsonSchema\Tests\Constraints;

use JsonSchema\Constraints\UndefinedConstraint;

class RequiredPropertyTest extends BaseTestCase
{

public function testErrorPropertyIsPopulatedForRequiredIfMissingInInput()
{
$validator = new UndefinedConstraint();
$document = json_decode(
'{
"bar": 42
}'
);
$schema = json_decode(
'{
"type": "object",
"properties": {
"foo": {"type": "number"},
"bar": {"type": "number"}
},
"required": ["foo"]
}'
);

$validator->check($document, $schema);
$error = $validator->getErrors();
$this->assertErrorHasExpectedPropertyValue($error, "foo");
}

public function testErrorPropertyIsPopulatedForRequiredIfEmptyValueInInput()
{
$validator = new UndefinedConstraint();
$document = json_decode(
'{
"bar": 42,
"foo": null
}'
);
$schema = json_decode(
'{
"type": "object",
"properties": {
"foo": {"type": "number"},
"bar": {"type": "number"}
},
"required": ["foo"]
}'
);

$validator->check($document, $schema);
$error = $validator->getErrors();
$this->assertErrorHasExpectedPropertyValue($error, "foo");
}

protected function assertErrorHasExpectedPropertyValue($error, $propertyValue)
{
if (!(isset($error[0]) && is_array($error[0]) && isset($error[0]['property']))) {
$this->fail(
"Malformed error response. Expected to have subset in form: array(0 => array('property' => <value>)))"
. " . Error response was: " . json_encode($error)
);
}
$this->assertEquals($propertyValue, $error[0]['property']);

}

public function getInvalidTests()
{
return array(
Expand Down