Etienne Cha Etienne Cha - 3 months ago 31
JSON Question

JSON Schema : required properties ignored

I discovered JSON Schema today it looks to be 100% fitting my needs, but it's actually driving me nuts with one of the most basic cases. Before creating this post, I obviously did my best to follow existing documentation and looked on the internet trying to find something helping.

Stack : PHP7 - justinrainbow/json-schema 2.0.5

Here is the schema :

{
"description":"UserCreate",
"type":"object",
"properties":{
"login":{
"type":"string",
"required":true
},
"idAsc":{
"type":"string",
"required":true
}
},
"required":[
"login",
"idAsc"
]
}


As you can see I am using both required definition (boolean and array), just to be sure I am using the good one, I also tried with only array and or boolean with the same result.

Here is the data

{
"login":"email@email.com"
}


I am expecting the following code to detect the lack of the required idAsc parameter.

$validator = new JsonSchema\Validator;
$validator->check($data, $schema);
if ($validator->isValid() == false)
echo("Missing something");
else
echo("Good");


But this code keep printing "Good”… I am definitely missing something about JSON Schema.

Thank's for your help, best regards.

Answer

I finally make it work, after debugging step by step the implementation of JSON Schema I was using :

First of all, I loaded the JSON Schema myself, the example given in the Github repo look to be broken for me (https://github.com/justinrainbow/json-schema):

$data = json_decode(file_get_contents('data.json'));

// Validate
$validator = new JsonSchema\Validator;
$validator->check($data, (object)['$ref' => 'file://' . realpath('schema.json')]);

I was not able to find any call to file_get_contents or relatives inside the library during my step by step debug. For this reason I decided to load the schema myself instead of giving the path to it:

function getSchema($filePath) {
   // NOT WORKING -> return json_decode(file_get_contents($filePath), true);
   return json_decode(file_get_contents($filePath));
}

$data = json_decode($rest->getRequest()->getBody());
$schema = $this->getSchema(realpath('controllers/schemas/userCreate.json'));

$validator = new JsonSchema\Validator;
$check_return = $validator->check($data, $schema);

Please pay attention to the commented line in the getSchema function, if you use json_decode with true as 2nd parameter it's not going to work either, the schema has to be an object and not an array !

Now everything is working like a charm for me ;)

Best regards,

Comments