Created
December 18, 2016 13:39
-
-
Save jeremyb/a0419ad9d5501fb602f052169112166f to your computer and use it in GitHub Desktop.
JSON data validation with Swagger definitions (through justinrainbow/json-schema)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// composer require justinrainbow/json-schema | |
require __DIR__.'/vendor/autoload.php'; | |
$jsonSchema = json_decode( | |
file_get_contents('https://raw.githubusercontent.com/OAI/OpenAPI-Specification/master/examples/v2.0/json/petstore-simple.json') | |
); | |
$schemaStorage = new \JsonSchema\SchemaStorage(); | |
$schemaStorage->addSchema('file://petstore', $jsonSchema); | |
$factory = new \JsonSchema\Constraints\Factory($schemaStorage); | |
$jsonValidator = new \JsonSchema\Validator($factory); | |
$jsonValidator->check( | |
json_decode('{"data":123}'), | |
(object) ['$ref' => 'file://petstore#/definitions/NewPet'] | |
); | |
var_dump($jsonValidator->isValid()); // false | |
var_dump($jsonValidator->getErrors()); // [{"property":"name","pointer":"\/name","message":"The property name is required","constraint":"required"}] | |
var_dump('####################################################################'); | |
$jsonValidator = new \JsonSchema\Validator($factory); | |
$jsonValidator->check( | |
json_decode('{"name": "Cat", "tag": "miaou"}'), | |
(object) ['$ref' => 'file://petstore#/definitions/NewPet'] | |
); | |
var_dump($jsonValidator->isValid()); // true | |
var_dump($jsonValidator->getErrors()); // [] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment