public function resolve(RefResolver $resolver) { if (!$this->hasUri()) { return $this; } $resolver->resolve($this->encode(false), $this->uri); return $this; }
public function resolve(RefResolver $resolver) { if (!$this->hasUri()) { return $this; } $resolver->resolve($this->getContent(), $this->uri); return $this; }
public function resolve(RefResolver $resolver) { if (!$this->hasUri()) { throw new \LogicException('Cannot resolve JsonSchema without uri parameter'); } $resolver->resolve($this->getRawContent(), $this->uri); return $this; }
/** * @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)); }
/** * @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(); }
/** * Create a new JSON Schema definition from a string * * @param $schemaString * * @throws InvalidJsonException * * @return \Raml\Schema\Definition\JsonSchemaDefinition */ public function createSchemaDefinition($schemaString) { $retriever = new UriRetriever(); $jsonSchemaParser = new RefResolver($retriever); $data = json_decode($schemaString); if (!$data) { throw new InvalidJsonException(json_last_error()); } $jsonSchemaParser->resolve($data, $this->getSourceUri()); return new JsonSchemaDefinition($data); }
private function getSchema() { static $schema; if (!$schema) { $schemaDir = realpath(__DIR__ . '/../../Resources/format'); $retriever = new UriRetriever(); $schema = $retriever->retrieve("file://{$schemaDir}/framework.json"); $refResolver = new RefResolver($retriever); $refResolver->resolve($schema); } return $schema; }
/** * Create a new JSON Schema definition from a string * * @param $schemaString * * @throws InvalidJsonException * * @return \Raml\Schema\Definition\JsonSchemaDefinition */ public function createSchemaDefinition($schemaString) { $retriever = new UriRetriever(); $jsonSchemaParser = new RefResolver($retriever); $data = json_decode($schemaString); if (!$data) { echo 'Warning: Not valid json or file not found.' . PHP_EOL; echo 'JSON:' . var_export($schemaString, true) . PHP_EOL; throw new InvalidJsonException(json_last_error()); } $jsonSchemaParser->resolve($data, $this->getSourceUri()); return new JsonSchemaDefinition($data); }
/** * @param string $string * @param string[] Predefined schemas: $defs name => schema. * * @return object */ public static function loadSchema($string, $defs = []) { $uri = static::$uriPrefix . 'loadedschema.json'; $schemas = [$uri => $string]; foreach ($defs as $defName => $def) { $schemas[static::$uriPrefix . $defName] = $def; } $uriRetriever = new UriRetriever(); $uriRetriever->setUriRetriever(new PredefinedArray($schemas)); $uriResolver = new UriResolver(); $refResolver = new RefResolver($uriRetriever, $uriResolver); return $refResolver->resolve($uri); }
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 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; }
/** * Load a json from a path and resolve references * * @param string $filePath * * @throws \Exception * * @return string */ public function loadFile($filePath) { $retriever = new UriRetriever(); $jsonSchemaParser = new RefResolver($retriever); try { $json = $jsonSchemaParser->fetchRef('file://' . $filePath, null); } catch (\Exception $e) { $json = json_decode(file_get_contents($filePath)); } try { return json_encode($json); } catch (\Exception $e) { throw new InvalidJsonException(json_last_error()); } }
/** * Asserts that json content is valid according to the provided schema file. * * Example: * * static::assertJsonMatchesSchema('./schema.json', json_decode('{"foo":1}')) * * @param string $schema Path to the schema file * @param array|object $content JSON array or object */ public static function assertJsonMatchesSchema($schema, $content) { // Assume references are relative to the current file // Create an issue or pull request if you need more complex use cases $refResolver = new RefResolver(new UriRetriever(), new UriResolver()); $schemaObj = $refResolver->resolve('file://' . realpath($schema)); $validator = new Validator(); $validator->check($content, $schemaObj); $message = '- Property: %s, Contraint: %s, Message: %s'; $messages = array_map(function ($exception) use($message) { return sprintf($message, $exception['property'], $exception['constraint'], $exception['message']); }, $validator->getErrors()); $messages[] = '- Response: ' . json_encode($content); \PHPUnit_Framework_Assert::assertTrue($validator->isValid(), implode("\n", $messages)); }
/** * @param object $message * @return array */ protected function validateMessage($message) { if (empty($message) === true) { return []; } $jsonApiSchemaPath = realpath(__DIR__ . "/json-api-schema.json"); $retriever = new UriRetriever(); $schema = $retriever->retrieve('file://' . $jsonApiSchemaPath); RefResolver::$maxDepth = 100; $refResolver = new RefResolver($retriever); $refResolver->resolve($schema, 'file://' . dirname($jsonApiSchemaPath) . "/json-api-schema.json"); $validator = new Validator(); $validator->check($message, $schema); return $validator->getErrors(); }
/** * @dataProvider getSchemas */ public function testValidateSchema($data) { if (is_string($data)) { $data = json_decode(file_get_contents($data)); } // get the schema and data as objects $retriever = new UriRetriever(); $schema = $retriever->retrieve('http://json-schema.org/draft-04/schema#'); // resolve $ref's $refResolver = new RefResolver($retriever); $refResolver->resolve($schema, __DIR__ . '/Fixtures'); // validate $validator = new Validator(); $validator->check($data, $schema); $this->assertTrue($validator->isValid()); }
protected function setUp() { // Ugh... RefResolver::$maxDepth = 20; $server = ['HTTP_AUTHORIZATION' => 'Bearer ' . self::PSK_TOKEN]; $this->client = static::createClient([], $server); static::bootKernel(); $this->loadFixtures([]); }
public function assertValidSchema($data, $schema, $refResolverPath = null) { if ($refResolverPath) { $retriever = new UriRetriever(); $refResolver = new RefResolver($retriever); $refResolver->resolve($schema, $refResolverPath); } $validator = new SchemaValidator(); $validator->check($data, $schema); $success = $validator->isValid(); if (!$success) { $messages = []; foreach ($validator->getErrors() as $error) { $messages[] = sprintf("[%s] %s", $error['property'], preg_replace("/[\\s\r\n]+/", ' ', $error['message'])); } $this->assertTrue($success, join("\n", $messages)); } }
/** * @param \stdClass $data JSON data decoded into object notation * @throws \Exception */ public function assertJsonapiValid($data) { $schemaFile = dirname(__FILE__) . '/../resources/jsonapi-schema-1.0.json'; $schema = json_decode(file_get_contents($schemaFile)); $refResolver = new RefResolver(); # Minimum depth required to work with jsonapi schema $refResolver::$maxDepth = 11; $refResolver->resolve($schema); $validator = new Validator(); $validator->check($data, $schema); if (!$validator->isValid()) { $msg = "Invalid jsonapi reponse:\n"; foreach ($validator->getErrors() as $error) { $msg .= ' path "' . $error['property'] . '" -> ' . $error['message'] . "\n"; } throw new \Exception($msg); } }
/** * * @param string $schemaFile * * @return object */ protected function resolveSchemaFile($schemaFile) { $extension = pathinfo($schemaFile, PATHINFO_EXTENSION); switch ($extension) { case 'yml': case 'yaml': if (!class_exists(Yaml::class)) { throw new \InvalidArgumentException('You need to require the "symfony/yaml" component in order to parse yml files'); } $uriRetriever = new YamlUriRetriever(); break; case 'json': $uriRetriever = new UriRetriever(); break; default: throw new \InvalidArgumentException(sprintf('file "%s" does not provide a supported extension choose either json, yml or yaml', $schemaFile)); } $refResolver = new RefResolver($uriRetriever, new UriResolver()); return $refResolver->resolve($schemaFile); }
/** * 載入Schema * * @param mixed $schema schema * * @return object $schemaObj * @throws ModelException if data type is not string, array or object */ private function loadSchema($schema) { // 加上副檔名JSON if (pathinfo($schema, PATHINFO_EXTENSION) != 'json') { $schema .= '.json'; } // 檢查Schema檔是否存在 if (file_exists(realpath("{$this->path}/{$schema}"))) { $schemaFile = realpath("{$this->path}/{$schema}"); $schemaPath = dirname($schemaFile); } elseif (file_exists(realpath($schema))) { $schemaFile = realpath($schema); $schemaPath = dirname($schemaFile); } else { return false; } // 載入Schema $retriever = new JsonUriRetriever(); $schemaObj = $retriever->retrieve("file://{$schemaFile}"); $refResolver = new JsonRefResolver($retriever); $refResolver->resolve($schemaObj, "file://{$schemaPath}/"); return $schemaObj; }
public static function createFromJson($json) { $data = json_decode($json); if (is_null($data)) { throw new InvalidJsonFactoryException($json); } $schemaPath = static::getJsonSchemaPath(); if ($schemaPath) { $schemaUri = 'file://' . $schemaPath; $schemaRetriever = new MtgApiJsonSchemaUriRetriever(); $schema = $schemaRetriever->retrieve($schemaUri); $schemaReferenceResolver = new RefResolver($schemaRetriever); $schemaReferenceResolver->resolve($schema, $schemaUri); $schemaValidator = new Validator(); $schemaValidator->check($data, $schema); if (!$schemaValidator->isValid()) { foreach ($schemaValidator->getErrors() as $error) { throw new InvalidJsonFactoryException($json, sprintf('[%s] %s', $error['property'], $error['message'])); } } } return static::createFromData($data); }
/** * Registers services on the given app. * * This method should only be used to configure services and parameters. * It should not get services. * * @param Application $app */ public function register(Application $app) { $app['json.request.validator'] = $app->protect(function (Request $request) use($app) { $action = $request->attributes->get('_controller'); if (!is_string($action) || !isset($app['json.request.validator.schemaMap'][$action])) { //no schema map found for this url, skip validation return; } $schemaFile = $app['json.request.validator.schemaMap'][$action]; $schemaPath = ROOT_PATH . '/web/schema/' . $schemaFile; $retriever = new UriRetriever(); $schema = $retriever->retrieve('file://' . $schemaPath); // If you use $ref or if you are unsure, resolve those references here // This modifies the $schema object $refResolver = new RefResolver($retriever); $refResolver->resolve($schema, 'file://' . ROOT_PATH . '/web/schema/'); $validator = new Validator(); $validator->check(json_decode($request->getContent()), $schema); if ($validator->getErrors()) { $schemaPublicUrl = $request->getSchemeAndHttpHost() . '/' . $request->getBaseUrl() . '/schema/' . $schemaFile; return new JsonResponse(['error' => 'Data contains errors', 'details' => $validator->getErrors(), 'schemaUrl' => $schemaPublicUrl], 400); } }); }
/** * @Then the json data should be valid * @Then the response json should be valid * @Then the json key :key data should be valid * @Then the response json key :key should be valid */ public function theJsonDataShouldBeValid($key = null) { $validator = new Validator(); $data = $this->getJsonContent(false); if ($key) { $this->theResponseJsonShouldContain($key); $data = $data->{$key}; } $this->resolver->resolve($this->schema); $validator->check($data, $this->schema); if (!$validator->isValid()) { $errors = $validator->getErrors(); $errors = array_map(function ($error) { return sprintf('%s: %s', $error['property'], $error['message']); }, $errors); $errors[] = sprintf('%1$sProvided Data: %1$s%2$s', PHP_EOL, json_encode($data, JSON_PRETTY_PRINT)); throw new \Exception(implode(PHP_EOL, $errors)); } }
private function loadSchema($file) { // Retrieve schema and cache in UriRetriever $file = Path::canonicalize($file); // Add file:// scheme if necessary if (false === strpos($file, '://')) { $file = 'file://' . $file; } // Resolve references to other schemas try { $schema = $this->resolver->resolve($file); } catch (ResourceNotFoundException $e) { throw new InvalidSchemaException(sprintf('The schema %s does not exist.', $file), 0, $e); } try { $this->assertSchemaValid($schema); } catch (InvalidSchemaException $e) { throw new InvalidSchemaException(sprintf('An error occurred while loading the schema %s: %s', $file, $e->getMessage()), 0, $e); } return $schema; }
/** * @param string $uri * * @return Schema */ public function create($uri) { return new Schema($this->resolver->resolve(strpos($uri, '//') === false ? "file://{$uri}" : $uri)); }
/** * @param $data a schema document to be meta-validated * @return bool * @throws \RS\Repose\Core\Exceptions\ReposeValidationException */ public function isValidSchema($data) { $refResolver = new RefResolver(new UriRetriever(), new UriResolver()); // TODO make setup option $schema = $refResolver->resolve('file:///home/repose/repose-core/public/draft/repose-schema-schema.json'); $validator = new Validator(); $validator->check($data, $schema); return $validator->isValid() ?: $validator->getErrors(); }
/** * Resolve schema references to object. * * @param stdClass $schema * * @return stdClass The same object with references replaced with definition target. */ protected function resolveSchemaReferences(stdClass $schema) { $refResolver = new RefResolver(new UriRetriever()); $refResolver->resolve($schema, $this->definitionUri); return $schema; }
/** * @return \stdClass * @throws \Zend\Validator\Exception\RuntimeException */ private function getSchema() { $file = $this->file; if (!$file) { throw new Exception\RuntimeException('Validator option `file` is required and cannot be empty.'); } $url = parse_url($file); if (!array_key_exists('scheme', $url)) { $file = 'file://' . realpath($file); } $refResolver = new RefResolver(new UriRetriever(), new UriResolver()); try { return $refResolver->resolve($file); } catch (\Exception $e) { throw new Exception\RuntimeException(sprintf('Could not load JSON Schema: %s', $e->getMessage()), $e->getCode(), $e); } }
/** * @param stdClass $data * @param $schemaPath * @throws Exception */ protected function assertJsonSchemaValid(stdClass $data, $schemaPath) { $resolver = new JsonSchemaRefResolver(new JsonSchemaUriRetriever(), new JsonSchemaUriResolver()); $schema = $resolver->resolve('file://' . $schemaPath); $validator = new JsonSchemaValidator(); $validator->check($data, $schema); $msg = "JSON does not validate. Violations:\n"; foreach ($validator->getErrors() as $error) { $msg .= sprintf("[%s] %s\n", $error['property'], $error['message']) . "\n"; } $msg .= "Object: " . print_r((array) $data, 1) . "\n"; $this->testCaseObject->assertTrue($validator->isValid(), $msg); }