Webmozart\Json\JsonValidator::validate PHP Method

validate() public method

The schema may be passed as file path or as object returned from json_decode($schemaFile).
public validate ( mixed $data, string | object | null $schema = null ) : string[]
$data mixed The decoded JSON data
$schema string | object | null 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
    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;
    }

Usage Example

Ejemplo n.º 1
0
 /**
  * @expectedException \Webmozart\Json\InvalidSchemaException
  */
 public function testValidateFailsIfInvalidSchemaNotRecognized()
 {
     // justinrainbow/json-schema cannot validate "anyOf", so the following
     // will load the schema successfully and fail when the file is validated
     // against the schema
     $this->validator->validate((object) array('name' => 'Bernhard'), (object) array('type' => 12345));
 }
All Usage Examples Of Webmozart\Json\JsonValidator::validate