Class: JSON::Schema::PropertiesAttribute

Inherits:
Attribute
  • Object
show all
Defined in:
lib/json-schema/attributes/properties.rb

Direct Known Subclasses

PropertiesV4Attribute

Constant Summary

Constants inherited from Attribute

Attribute::TYPE_CLASS_MAPPINGS

Class Method Summary collapse

Methods inherited from Attribute

build_fragment, data_valid_for_type?, type_of_data, validation_error, validation_errors

Class Method Details

.required?(schema, options) ⇒ Boolean

Returns:

  • (Boolean)


6
7
8
# File 'lib/json-schema/attributes/properties.rb', line 6

def self.required?(schema, options)
  schema.fetch('required') { options[:allPropertiesRequired] }
end

.validate(current_schema, data, fragments, processor, validator, options = {}) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/json-schema/attributes/properties.rb', line 10

def self.validate(current_schema, data, fragments, processor, validator, options = {})
  return unless data.is_a?(Hash)

  schema = current_schema.schema
  schema['properties'].each do |property, property_schema|
    property = property.to_s

    if !data.key?(property) &&
       options[:insert_defaults] &&
       property_schema.has_key?('default') &&
       !property_schema['readonly']
      default = property_schema['default']
      data[property] = default.is_a?(Hash) ? default.clone : default
    end

    if required?(property_schema, options) && !data.has_key?(property)
      message = "The property '#{build_fragment(fragments)}' did not contain a required property of '#{property}'"
      validation_error(processor, message, fragments, current_schema, self, options[:record_errors])
    end

    if data.has_key?(property)
      expected_schema = JSON::Schema.new(property_schema, current_schema.uri, validator)
      expected_schema.validate(data[property], fragments + [property], processor, options)
    end
  end

  # When noAdditionalProperties is true, ensure no undefined properties exist in the data
  return unless options[:noAdditionalProperties] == true && !schema.key?('additionalProperties')

  diff = data.select do |k, v|
    k = k.to_s

    if schema.has_key?('patternProperties')
      match = false
      schema['patternProperties'].each do |property, property_schema|
        regexp = Regexp.new(property)
        if regexp.match(k)
          match = true
          break
        end
      end

      !schema['properties'].has_key?(k) && !match
    else
      !schema['properties'].has_key?(k)
    end
  end

  unless diff.empty?
    properties = diff.keys.join(', ')
    message = "The property '#{build_fragment(fragments)}' contained undefined properties: '#{properties}'"
    validation_error(processor, message, fragments, current_schema, self, options[:record_errors])
  end
end