本文整理汇总了PHP中JsonSchema\Validator::getErrors方法的典型用法代码示例。如果您正苦于以下问题:PHP Validator::getErrors方法的具体用法?PHP Validator::getErrors怎么用?PHP Validator::getErrors使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类JsonSchema\Validator
的用法示例。
在下文中一共展示了Validator::getErrors方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: validate
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)));
}
示例2: load
/**
* @param string $string JSON encoded object.
* @param object|null $schema JSON schema, loaded and resolved by loadSchema().
*
* @return object
* @throws JsonLoadException
*/
public static function load($string, $schema = null)
{
$object = json_decode($string);
if ($object === null) {
throw new JsonLoadException(json_last_error_msg());
}
if ($schema !== null) {
$validator = new Validator();
$validator->check($object, $schema);
if (!$validator->isValid()) {
throw new JsonLoadException(sprintf("Schema error at %s: %s", $validator->getErrors()[0]['property'], $validator->getErrors()[0]['message']));
}
}
return $object;
}
示例3: mergeAndValidateConfig
/**
* Merge the given config on to "configurable" (either a GeneratorInterface
* or a RendererInterface) instance's default config and validate it
* according to the "configurable" instance's JSON schema.
*
* @param ConfigurableInterface $configurable
* @param array $reportConfig
*
* @return array
*/
private function mergeAndValidateConfig(ConfigurableInterface $configurable, array $reportConfig)
{
$reportConfig = array_replace_recursive($configurable->getDefaultConfig(), $reportConfig);
// not sure if there is a better way to convert the schema array to objects
// as expected by the validator.
$validationConfig = json_decode(json_encode($reportConfig));
$schema = $configurable->getSchema();
if (!is_array($schema)) {
throw new \InvalidArgumentException(sprintf('Configurable class "%s" must return the JSON schema as an array', get_class($configurable)));
}
// convert the schema to a \stdClass
$schema = json_decode(json_encode($schema));
// json_encode encodes an array instead of an object if the schema
// is empty. JSON schema requires an object.
if (empty($schema)) {
$schema = new \stdClass();
}
$this->validator->check($validationConfig, $schema);
if (!$this->validator->isValid()) {
$errorString = array();
foreach ($this->validator->getErrors() as $error) {
$errorString[] = sprintf('[%s] %s', $error['property'], $error['message']);
}
throw new \InvalidArgumentException(sprintf('Invalid JSON: %s%s', PHP_EOL . PHP_EOL . PHP_EOL, implode(PHP_EOL, $errorString)));
}
return $reportConfig;
}
示例4: parseSingleSchema
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']);
}
}
}
}
示例5: checkEntityAgainstSchema
/**
* 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);
}
}
示例6: assertJsonResponse
/**
* @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;
}
示例7: execute
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;
}
示例8: validate
/**
* Validates JSON data against a schema.
*
* The schema may be passed as file path or as object returned from
* `json_decode($schemaFile)`.
*
* @param mixed $data The decoded JSON data
* @param string|object|null $schema The schema file or object. If `null`,
* the validator will look for a `$schema`
* property
*
* @return string[] The errors found during validation. Returns an empty
* array if no errors were found
*
* @throws InvalidSchemaException If the schema is invalid
*/
public function validate($data, $schema = null)
{
if (null === $schema && isset($data->{'$schema'})) {
$schema = $data->{'$schema'};
}
if (is_string($schema)) {
$schema = $this->loadSchema($schema);
} elseif (is_object($schema)) {
$this->assertSchemaValid($schema);
} else {
throw new InvalidSchemaException(sprintf('The schema must be given as string, object or in the "$schema" ' . 'property of the JSON data. Got: %s', is_object($schema) ? get_class($schema) : gettype($schema)));
}
$this->validator->reset();
try {
$this->validator->check($data, $schema);
} catch (InvalidArgumentException $e) {
throw new InvalidSchemaException(sprintf('The schema is invalid: %s', $e->getMessage()), 0, $e);
}
$errors = array();
if (!$this->validator->isValid()) {
$errors = (array) $this->validator->getErrors();
foreach ($errors as $key => $error) {
$prefix = $error['property'] ? $error['property'] . ': ' : '';
$errors[$key] = $prefix . $error['message'];
}
}
return $errors;
}
示例9: doValidation
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);
}
}
}
示例10: testValidCases
/**
* @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));
}
示例11: additionalFailureDescription
/**
* @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()));
}
示例12: validateAndThrowException
/**
* @param $validator
* @throws \UnexpectedValueException
*/
private static function validateAndThrowException(Validator $validator)
{
if (!$validator->isValid()) {
$errorStr = '';
foreach ($validator->getErrors() as $error) {
$errorStr .= sprintf('[%s] %s ', $error['property'], $error['message']);
}
throw new \UnexpectedValueException($errorStr);
}
}
示例13: validateJsonObject
/**
* 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;
}
示例14: check
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;
}
示例15: validateSchema
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();
}
}