/** * 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); } }
/** * Creates all service hook handlers. */ private function initialize() { $injector = new Injector(); $namespace = __NAMESPACE__ . "\\Service\\"; $basePath = __DIR__ . "/../vendor/kelunik/chat-services/res/schema/"; $transform = function ($match) { return strtoupper($match[1]); }; try { foreach ($this->config["services"] as $name => $enabled) { if (!$enabled) { continue; } $service = $injector->make($namespace . preg_replace_callback("~-([a-z])~", $transform, ucfirst($name))); $found = false; foreach (scandir($basePath . $name) as $file) { if ($file === "." || $file === "..") { continue; } $found = true; $uri = realpath($basePath . $name . "/" . $file); $schema = $this->retriever->retrieve("file://" . $uri); $this->schemas[$name][strtok($file, ".")] = $schema; } if (!$found) { throw new RuntimeException("every service must have at least one event schema"); } $this->services[$name] = $service; } } catch (InjectorException $e) { throw new RuntimeException("couldn't create all services", 0, $e); } }
/** * @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; }
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(); }); }
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; }
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; }
/** * @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(); }
/** * validate a given plugin object against the defined json format * * @param $json * @throws Exceptions\ValidatorException */ private function validate($json) { $retriever = new JsonSchema\Uri\UriRetriever(); // Detect phar archives - they don't need the file:// prefix $prefix = strpos(__DIR__, 'phar://') === 0 ? '' : 'file://'; $schema = $retriever->retrieve($prefix . __DIR__ . '/../res/plugin-info-schema.json'); $validator = new JsonSchema\Validator(); $validator->check(json_decode(json_encode($json)), $schema); if (!$validator->isValid()) { $errors = array_map(function ($error) { return $error['property'] . ': ' . $error['message']; }, $validator->getErrors()); throw new ValidatorException("Json not valid: " . implode(', ', $errors)); } }
/** * @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()); }
/** * @param $json * @param null $schema * @return bool * @throws \Exception */ public function validate($json, $schema = null) { // Get the schema and data as objects $retriever = new UriRetriever(); $schema = $schema ?: $retriever->retrieve('file://' . realpath($this->schema->resolve())); // Validate $validator = new Validator(); $validator->check($json, $schema); if (!$validator->isValid()) { $errors = $validator->getErrors(); $messages = collect($errors)->transform(function ($error) { return $this->formatErrorMessage($error); })->implode("\n"); throw new \Exception($messages); } return true; }
/** * Tests currency integrity. */ function testCurrencyIntegrity() { $resourceDirectory = __DIR__ . '/../resources'; $currencyFileNames = glob($resourceDirectory . '/currency/*.json'); $schemaUri = 'file://' . __DIR__ . '/../resources/schema/currency.json'; $schemaRetriever = new UriRetriever(); $schema = $schemaRetriever->retrieve($schemaUri); foreach ($currencyFileNames as $currencyFileName) { $schemaValidator = new Validator(); $schemaValidator->check(json_decode(file_get_contents($currencyFileName)), $schema); if (!$schemaValidator->isValid()) { foreach ($schemaValidator->getErrors() as $error) { $message = sprintf('%s for property %s in %s', $error['message'], $error['property'], $currencyFileName); $this->fail($message); } } } }
function loadConfig() { $config = json_decode(file_get_contents(__DIR__ . "/../etc/config/config.json")); $retriever = new UriRetriever(); $path = realpath(__DIR__ . "/../res/schema/config.json"); $schema = $retriever->retrieve("file://{$path}"); $validator = new Validator(); $validator->check($config, $schema); if (!$validator->isValid()) { $errors = implode(",\n", array_map(function ($error) { if ($error["property"]) { return sprintf("[%s] %s", $error["property"], $error["message"]); } else { return $error["message"]; } }, $validator->getErrors())); throw new RuntimeException("config file not valid\n\n{$errors}"); } $config = collapseConfig($config); return $config; }
/** * @param array $message * @throws InvalidMessageException */ public function __construct(array $message) { $schema = dirname(__DIR__) . '/MessagesSchema/' . $this->schema . '.json'; $errors = ''; if (!isset($message['type']) || $message['type'] !== $this->schema) { throw new InvalidMessageException('Message type is invalid. It must be set and equal to json-schema name'); } $message = json_encode($message, JSON_FORCE_OBJECT); $retriever = new UriRetriever(); $schema = $retriever->retrieve('file://' . realpath($schema)); $validator = new Validator(); $validator->check(json_decode($message), $schema); if ($validator->isValid()) { $this->message = $message; } else { foreach ($validator->getErrors() as $error) { $errors .= sprintf("[%s] %s\n", $error['property'], $error['message']); } throw new InvalidMessageException($errors); } }
/** * Validate response by json schema * * @param string $schema path to json schema file */ public function canSeeResponseIsValidOnSchemaFile($schema) { $schemaPath = realpath($schema); $retriever = new \JsonSchema\Uri\UriRetriever(); $schema = $retriever->retrieve('file://' . $schemaPath); $refResolver = new \JsonSchema\RefResolver($retriever); $refResolver->resolve($schema, 'file://' . $schemaPath); $response = $this->getModule('REST')->response; $validator = new \JsonSchema\Validator(); $validator->setUriRetriever(new UriRetriever()); $validator->check(json_decode($response), $schema); $message = ''; $isValid = $validator->isValid(); if (!$isValid) { $message = "JSON does not validate. Violations:\n"; foreach ($validator->getErrors() as $error) { $message .= $error['property'] . " " . $error['message'] . PHP_EOL; } } $this->assertTrue($isValid, $message); }
/** * 載入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; }
/** * 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); } }); }
/** * Loads a JSON Schema from an external JSON file to validate the overall workflow * * @param $name */ public function setSchemaFromFile($name) { $retriever = new UriRetriever(); $schema = $retriever->retrieve('file://' . realpath($name)); $this->schema = $schema; }
/** * Validates a value. * * @param string $value A JSON encoded string to validate. * @return array|null An array of error data, or null if the data is valid. */ protected function validateValue($value) { if (!is_string($value)) { return [$this->notString, []]; } $value = json_decode($value); if (json_last_error()) { return [$this->notJsonString, []]; } $retriever = new UriRetriever(); $schema = $retriever->retrieve($this->schema); $validator = new JSValidator(); $validator->check($value, $schema); if (!$validator->isValid()) { $errors = $validator->getErrors(); $error = reset($errors); return [$this->message, ['property' => $error['property'], 'message' => ucfirst($error['message'])]]; } return null; }