/**
  * @param \stdClass $responseBody
  *
  * @return Validator
  */
 protected function getValidator($responseBody)
 {
     $responseSchema = $this->schemaManager->getResponseSchema($this->path, $this->httpMethod, $this->httpCode);
     $validator = new Validator();
     $validator->check($responseBody, $responseSchema);
     return $validator;
 }
Example #2
0
 protected function doValidation(Response $response)
 {
     $data = json_decode($response->getBody());
     if ($data === null) {
         throw new ValidationFailedException("The given JSON data can not be validated (last error: '" . $this->json_errors[json_last_error()] . "').");
     } else {
         $error = false;
         $messageParts = array();
         foreach ($this->jsonSchemaFiles as $jsonSchemaFile) {
             $factory = new Factory(null, null, Constraint::CHECK_MODE_TYPE_CAST | Constraint::CHECK_MODE_COERCE);
             $validator = new Validator($factory);
             $jsonSchemaObject = (object) json_decode(file_get_contents($jsonSchemaFile['jsonschemafileurl']));
             $validator->check($data, $jsonSchemaObject);
             if (!$validator->isValid()) {
                 $error = true;
                 $errorMessage = '';
                 foreach ($validator->getErrors() as $error) {
                     $errorMessage = $errorMessage . sprintf("[%s] %s\n", $error['property'], $error['message']);
                 }
                 $messageParts[] = $jsonSchemaFile['jsonschemafilename'] . ' - ' . $jsonSchemaFile['jsonschemafileurl'] . '(last error: ' . $errorMessage . ').';
             }
         }
         if ($error == true) {
             $message = 'JSON file (' . (string) $response->getUri() . ')  does not validate against the following JSON Schema files: ' . implode(", ", $messageParts);
             throw new ValidationFailedException($message);
         }
     }
 }
Example #3
0
 /**
  * Check data against a given entity type from the schema
  *
  * @param array|object $data Data from the API. Associative arrays will be reparsed into objects
  * @param string $entity Entity type, from the schema
  */
 protected function checkEntityAgainstSchema($data, $entity)
 {
     $absolute_ref = self::SCHEMA_BASE . 'definitions/' . $entity;
     $schema = $this->retriever->retrieve($absolute_ref);
     if (is_array($data)) {
         // Data was decoded as an array instead of an object, reencode for
         // schema checking
         $data = json_decode(json_encode($data));
     }
     $validator = new Validator(Validator::CHECK_MODE_NORMAL, $this->retriever);
     $validator->check($data, $schema);
     if (!$validator->isValid()) {
         $message = "JSON does not validate against schema:\n";
         $i = 0;
         foreach ($validator->getErrors() as $error) {
             $i++;
             $message .= $i . ') ';
             if (!empty($error['property'])) {
                 $message .= sprintf("[%s] %s\n", $error['property'], $error['message']);
             } else {
                 $message .= $error['message'] . "\n";
             }
         }
         $this->fail($message);
     }
 }
Example #4
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $path = $input->getArgument('path');
     if (!$path) {
         $path = getcwd() . DIRECTORY_SEPARATOR . 'resolver.json';
     }
     if (!is_file($path)) {
         $output->writeln(sprintf('<error>The file "%s" does not exists.</error>', $path));
         return 1;
     }
     // Get the schema and data as objects:
     $schema = json_decode(file_get_contents(__DIR__ . '/../../resources/schema.json'));
     $data = json_decode(file_get_contents($path));
     // Validate:
     $validator = new Validator();
     $validator->check($data, $schema);
     if ($validator->isValid()) {
         $output->writeln($path . ' is valid');
         return 0;
     }
     $output->writeln(sprintf('<error>The file "%s" contains errors.</error>', $path));
     foreach ($validator->getErrors() as $error) {
         if ($error['property']) {
             $output->writeln(sprintf('- %s: %s', $error['property'], $error['message']));
         } else {
             $output->writeln(sprintf('- %s', $error['message']));
         }
     }
     return 1;
 }
Example #5
0
 /**
  * @param string $schemaName
  */
 protected function assertJsonResponse($response, $statusCode = Response::HTTP_OK, $schemaName = null)
 {
     // Assert HTTP response status code
     $this->assertEquals($statusCode, $response->getStatusCode(), $response->getContent());
     $content = $response->getContent();
     $data = null;
     if ($content) {
         // Assert response is JSON content-type (unless response content is empty)
         $this->assertTrue($response->headers->contains('Content-Type', 'application/json'), $response->headers);
         // Parse the response body
         $data = json_decode($response->getContent());
     }
     // Validate JSON data with given schema
     if (null !== $schemaName) {
         $schemaUri = 'file://' . realpath(__DIR__ . '/../Resources/json_schemas/' . $schemaName . '.json');
         $retriever = new JsonSchema\Uri\UriRetriever();
         $schema = $retriever->retrieve($schemaUri);
         $validator = new JsonSchema\Validator();
         $validator->check($data, $schema);
         if (!$validator->isValid()) {
             $errorMessage = 'JSON response does not validate the schema';
             foreach ($validator->getErrors() as $error) {
                 $errorMessage .= sprintf("\n[%s] %s", $error['property'], $error['message']);
             }
             $this->fail($errorMessage);
         }
     }
     return $data;
 }
Example #6
0
 public function parseSingleSchema($schemeSpec)
 {
     if ($schemeSpec === null) {
         throw new ParseException('scheme must not be empty');
     }
     if (!is_string($schemeSpec)) {
         throw new ParseException('scheme must be a string');
     }
     $schemaJson = json_decode($schemeSpec);
     if (json_last_error() == JSON_ERROR_NONE) {
         $schemeUri = $schemaJson->{'$schema'};
         $retriever = new \JsonSchema\Uri\UriRetriever();
         $scheme = $retriever->retrieve($schemeUri);
         $validator = new Validator();
         $validator->check($schemaJson, $scheme);
         if ($validator->isValid()) {
             $arrayScheme = json_decode($schemeSpec, true);
             unset($arrayScheme['$schema']);
             return $arrayScheme;
         } else {
             foreach ($validator->getErrors() as $error) {
                 echo sprintf("[%s] %s\n", $error['property'], $error['message']);
             }
         }
     }
 }
 /**
  * @inheritdoc
  */
 protected function additionalFailureDescription($other)
 {
     $other = $this->forceToObject($other);
     $validator = new Validator();
     $validator->check($other, $this->schema);
     return implode("\n", array_map(function ($error) {
         return $error['message'];
     }, $validator->getErrors()));
 }
 /**
  * @param $jsonStr
  * @return Validator
  */
 private static function initValidator($jsonStr)
 {
     /** @var $this JsonValidatableTrait */
     $validator = new Validator();
     $data = json_decode($jsonStr);
     $schema = static::jsonViceVersa(static::getJsonSchema());
     $validator->check($data, $schema);
     return $validator;
 }
Example #9
0
 /**
  * @dataProvider getValidTests
  */
 public function testValidCases($input, $schema, $checkMode = Validator::CHECK_MODE_NORMAL)
 {
     $schema = json_decode($schema);
     $refResolver = new RefResolver(new UriRetriever());
     $refResolver->resolve($schema);
     $validator = new Validator($checkMode);
     $validator->check(json_decode($input), $schema);
     $this->assertTrue($validator->isValid(), print_r($validator->getErrors(), true));
 }
 public static function GetTestFiles()
 {
     $dir = dirname(dirname(__DIR__));
     $retriever = new UriRetriever();
     $schema = $retriever->retrieve('file://' . realpath($dir . '/schema/tests.json'));
     return new CallbackFilterIterator(new DirectoryIterator($dir . '/tests'), function (SplFileInfo $file) use($schema) {
         $validator = new Validator();
         return $file->isFile() && $file->isReadable() && preg_match('/\\.json$/', $file->getBasename()) && $validator->check($schema, json_decode(file_get_contents($file->getRealPath()))) == null && $validator->isValid();
     });
 }
 /**
  * Validates a json object
  *
  * @param string $json
  *
  * @throws \Exception
  *
  * @return boolean
  */
 public function validateJsonObject($json)
 {
     $validator = new Validator();
     $jsonSchema = $this->json;
     $validator->check($json, $jsonSchema);
     if (!$validator->isValid()) {
         throw new InvalidSchemaException($validator->getErrors());
     }
     return true;
 }
Example #12
0
 private function check($json)
 {
     $schema = json_decode(file_get_contents(__DIR__ . '/../../../../res/composer-schema.json'));
     $validator = new Validator();
     $validator->check(json_decode($json), $schema);
     if (!$validator->isValid()) {
         return $validator->getErrors();
     }
     return true;
 }
Example #13
0
 public function validateSchema($json, $schema)
 {
     $validator = new Validator();
     $validator->check(json_decode($json), json_decode($schema));
     if ($validator->isValid()) {
         return true;
     } else {
         return $validator->getErrors();
     }
 }
 /**
  * Zkontroluje data proti zadanému schématu
  *
  * @param array|\StdClass
  * @param string
  * @return bool
  */
 public function check($data, $schemaFile)
 {
     $validator = new Validator();
     $schema = $this->getSchema($schemaFile);
     $validator->check($data, Json::decode($schema));
     if ($validator->isValid()) {
         return TRUE;
     }
     $this->errors = $validator->getErrors();
     return FALSE;
 }
 /**
  * @param \stdClass $headers
  *
  * @return Validator
  */
 protected function getValidator($headers)
 {
     $schema = new \stdClass();
     $headers = (object) array_change_key_case((array) $headers, CASE_LOWER);
     $properties = $this->schemaManager->getResponseHeaders($this->path, $this->httpMethod, $this->httpCode);
     $schema->properties = (object) array_change_key_case((array) $properties, CASE_LOWER);
     $schema->required = array_keys((array) $schema->properties);
     $validator = new Validator();
     $validator->check($headers, $schema);
     return $validator;
 }
Example #16
0
 /**
  * Tests right errors output.
  *
  * @covers ::displayErrors
  *
  * @return void
  */
 public function testDisplayErrors()
 {
     $validator = new Validator();
     $validator->addError(null, 'Foo');
     $validator->addError('subpath', 'Bar');
     $output = new StreamOutput(fopen('php://memory', 'r+'), StreamOutput::VERBOSITY_NORMAL, false);
     Utils::displayErrors($validator, $output);
     rewind($output->getStream());
     $this->assertStringEqualsFile(__DIR__ . '/fixtures/Utils/testDisplayErrors', stream_get_contents($output->getStream()));
     fclose($output->getStream());
 }
 /**
  * @param string $message
  * @return array
  */
 protected function validateMessage($message)
 {
     if (empty($message) === true) {
         return [];
     }
     $refResolver = new RefResolver(new UriRetriever(), new UriResolver());
     $schema = $refResolver->resolve('file://' . realpath(__DIR__ . "/json-api-schema.json"));
     $validator = new Validator();
     $validator->check(json_decode($message), $schema);
     return $validator->getErrors();
 }
Example #18
0
 public function __construct(array $config)
 {
     $config += $this->default;
     $schema = file_get_contents(__DIR__ . '/../res/config-schema.json');
     $validator = new JsonSchema\Validator();
     $validator->check((object) $config, json_decode($schema));
     if (!$validator->isValid()) {
         throw new \InvalidArgumentException(var_export($validator->getErrors(), true));
     }
     $this->config = $config;
 }
 /**
  * @param Request $request
  *
  * @throws InvalidParametersException
  * @throws UnsupportedException
  */
 public function validateRequest(Request $request)
 {
     $validator = new Validator();
     $validator->check($this->assembleParameterDataForValidation($request), $this->assembleRequestSchema());
     if (!$validator->isValid()) {
         /**
          * TODO Better utilize $validator->getErrors() so we can assemble a more helpful vnd.error response
          * @see https://github.com/kleijnweb/swagger-bundle/issues/27
          */
         throw new InvalidParametersException("Parameters incompatible with operation schema: " . implode(', ', $validator->getErrors()[0]), 400);
     }
 }
Example #20
0
 public function validate(Json $json, Validator $validator)
 {
     $validator->check($json->getContent(), $this->getContent());
     if (!$validator->isValid()) {
         $msg = "JSON does not validate. Violations:" . PHP_EOL;
         foreach ($validator->getErrors() as $error) {
             $msg .= sprintf("  - [%s] %s" . PHP_EOL, $error['property'], $error['message']);
         }
         throw new \Exception($msg);
     }
     return true;
 }
Example #21
0
 /**
  * {@inheritdoc}
  */
 public function isValid($data)
 {
     $validator = new Validator();
     $validator->check(json_decode($data), json_decode($this->getSchema()));
     if ($validator->isValid()) {
         return true;
     }
     $this->logger->error(implode(', ', array_map(function ($error) {
         return sprintf('"%s" %s', $error['property'], $error['message']);
     }, $validator->getErrors())));
     return false;
 }
 public function validate(Json $json, Validator $validator, RefResolver $refResolver)
 {
     $schema = $refResolver->resolve('file://' . realpath($this->filename));
     $validator->check($json->getRawContent(), $schema);
     if (!$validator->isValid()) {
         $msg = "JSON does not validate. Violations:" . PHP_EOL;
         foreach ($validator->getErrors() as $error) {
             $msg .= sprintf("  - [%s] %s" . PHP_EOL, $error['property'], $error['message']);
         }
         throw new \Exception($msg);
     }
     return true;
 }
Example #23
0
 /**
  * Display validation errors.
  *
  * @param Validator       $validator The json-schema validator.
  * @param OutputInterface $output    An OutputInterface instance.
  */
 public static function displayErrors(Validator $validator, OutputInterface $output)
 {
     $table = new Table($output);
     $style = new TableStyle();
     $style->setCellHeaderFormat('<error>%s</error>');
     $style->setHorizontalBorderChar(' ');
     $style->setVerticalBorderChar(' ');
     $style->setCrossingChar(' ');
     $table->setHeaders(['Property', 'Error']);
     $table->setRows($validator->getErrors());
     $table->setStyle($style);
     $table->render();
 }
 public function validate($data)
 {
     $data = json_decode(json_encode($data));
     $this->validator->check($data, (object) ['$ref' => $this->getSchemaPath()]);
     $result = false;
     if ($this->validator->isValid()) {
         return new ValidationResult(true, '');
     }
     $messages = array_map(function ($error) {
         return sprintf("[%s] %s.", $error['property'], $error['message']);
     }, $this->validator->getErrors());
     return new ValidationResult($result, trim(implode(' ', $messages)));
 }
 /**
  * Execute the middleware.
  *
  * @param ServerRequestInterface $request
  * @param ResponseInterface $response
  * @param callable $next
  *
  * @return ResponseInterface
  * @throws \RuntimeException
  * @throws \InvalidArgumentException
  * @throws \JsonSchema\Exception\ExceptionInterface
  */
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
 {
     $value = $request->getParsedBody();
     if (!is_object($value)) {
         return $this->invalidateResponse($response, sprintf('Parsed body must be an object. Type %s is invalid.', gettype($value)));
     }
     $validator = new Validator();
     $validator->check($value, $this->schema);
     if (!$validator->isValid()) {
         return $this->invalidateResponse($response, 'Unprocessable Entity', ['Content-Type' => 'application/json'], json_encode($validator->getErrors(), JSON_UNESCAPED_SLASHES));
     }
     return $next($request, $response);
 }
 public function testComplex()
 {
     $jsonArray = array(DATA_PATH . 'example.address1.json', DATA_PATH . 'example.address2.json', DATA_PATH . 'facebook-data.json');
     foreach ($jsonArray as $jsonUrl) {
         $sUT = new JSONStringParser();
         $validator = new Validator();
         $json = file_get_contents($jsonUrl);
         $results = $sUT->parse($json);
         $this->assertInstanceOf('JSONSchema\\Structure\\Schema', $results);
         $validator->check(json_decode($json), $results->toObject());
         $this->assertTrue($validator->isValid(), "\n Error : " . json_encode($validator->getErrors()) . "\njson : " . $json . "\nschema : " . $results->toString());
     }
 }
Example #27
0
 public function process($id)
 {
     $retriever = new UriRetriever();
     $schemaFolder = DRUPAL_ROOT . '/' . drupal_get_path('module', 'open_data_schema_pod') . '/data/v1.1';
     $schema = $retriever->retrieve('file://' . $schemaFolder . '/dataset.json');
     $data = $this->getDataset($id);
     RefResolver::$maxDepth = 10;
     $refResolver = new RefResolver($retriever);
     $refResolver->resolve($schema, 'file://' . $schemaFolder . '/');
     $validator = new Validator();
     $validator->check($data, $schema);
     return $validator;
 }
 public function execute()
 {
     if (!class_exists(Validator::class)) {
         $this->error('The JsonSchema library cannot be found, please install it through composer.', 1);
     } elseif (!class_exists(SpdxLicenses::class)) {
         $this->error('The spdx-licenses library cannot be found, please install it through composer.', 1);
     }
     $path = $this->getArg(0);
     $data = json_decode(file_get_contents($path));
     if (!is_object($data)) {
         $this->error("{$path} is not a valid JSON file.", 1);
     }
     if (!isset($data->manifest_version)) {
         $this->output("Warning: No manifest_version set, assuming 1.\n");
         // For backwards-compatability assume 1
         $data->manifest_version = 1;
     }
     $version = $data->manifest_version;
     if ($version !== ExtensionRegistry::MANIFEST_VERSION) {
         $schemaPath = dirname(__DIR__) . "/docs/extension.schema.v{$version}.json";
     } else {
         $schemaPath = dirname(__DIR__) . '/docs/extension.schema.json';
     }
     if ($version < ExtensionRegistry::OLDEST_MANIFEST_VERSION || $version > ExtensionRegistry::MANIFEST_VERSION) {
         $this->error("Error: {$path} is using a non-supported schema version, it should use " . ExtensionRegistry::MANIFEST_VERSION, 1);
     } elseif ($version < ExtensionRegistry::MANIFEST_VERSION) {
         $this->output("Warning: {$path} is using a deprecated schema, and should be updated to " . ExtensionRegistry::MANIFEST_VERSION . "\n");
     }
     $licenseError = false;
     // Check if it's a string, if not, schema validation will display an error
     if (isset($data->{'license-name'}) && is_string($data->{'license-name'})) {
         $licenses = new SpdxLicenses();
         $valid = $licenses->validate($data->{'license-name'});
         if (!$valid) {
             $licenseError = '[license-name] Invalid SPDX license identifier, ' . 'see <https://spdx.org/licenses/>';
         }
     }
     $validator = new Validator();
     $validator->check($data, (object) ['$ref' => 'file://' . $schemaPath]);
     if ($validator->isValid() && !$licenseError) {
         $this->output("{$path} validates against the version {$version} schema!\n");
     } else {
         foreach ($validator->getErrors() as $error) {
             $this->output("[{$error['property']}] {$error['message']}\n");
         }
         if ($licenseError) {
             $this->output("{$licenseError}\n");
         }
         $this->error("{$path} does not validate.", 1);
     }
 }
Example #29
0
 protected static function validateSchema($data, $path)
 {
     $schemaFile = __DIR__ . '/../../../../res/session-schema.json';
     $schemaData = json_decode(file_get_contents($schemaFile));
     $validator = new Validator();
     $validator->check($data, $schemaData);
     if (!$validator->isValid()) {
         $errors = array();
         foreach ((array) $validator->getErrors() as $error) {
             $errors[] = ($error['property'] ? $error['property'] . ' : ' : '') . $error['message'];
         }
         throw new JsonValidationException('"' . $path . '" does not match the expected JSON schema', $errors);
     }
 }
 /**
  * Validates a Ribkey using all other form datas
  * Beware, form data
  * @param  string     $value      [description]
  * @param  Constraint $constraint [description]
  * @return boolean                [description]
  */
 public function validate($value, Constraint $constraint)
 {
     $this->setSchemaAndData($value);
     // Validate/
     $validator = new jsonValidator();
     $validator->check($this->data, $this->schema);
     if (!$validator->isValid()) {
         $error = "";
         foreach ($validator->getErrors() as $validatorError) {
             $error .= sprintf(" le champs %s %s<br>", $validatorError['property'], $validatorError['message']);
         }
         $this->context->addViolation($error);
     }
 }