Class: SvgConform::Requirements::AllowedElementsRequirement

Inherits:
BaseRequirement
  • Object
show all
Defined in:
lib/svg_conform/requirements/allowed_elements_requirement.rb

Overview

Validates that only allowed SVG elements and their attributes are used

Constant Summary collapse

RDF_NAMESPACES =

RDF-related namespaces (same as in NamespaceRequirement for consistency)

[
  "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
  "http://creativecommons.org/ns#",
  "http://purl.org/dc/elements/1.1/",
  "http://purl.org/dc/dcmitype/",
  "http://www.w3.org/2000/01/rdf-schema#",
].freeze
GLOBAL_PROPERTIES =

Global properties allowed on any element (from svgcheck word_properties.py) Defined once at class level to avoid repeated array allocations

%w[
  about base baseprofile d break class content cx cy datatype height href
  label lang pathlength points preserveaspectratio property r rel resource
  rev role rotate rx ry space snapshottime transform typeof version width
  viewbox x x1 x2 y y1 y2 stroke stroke-width stroke-linecap stroke-linejoin
  stroke-miterlimit stroke-dasharray stroke-dashoffset stroke-opacity
  vector-effect viewport-fill display viewport-fill-opacity visibility
  image-rendering color-rendering shape-rendering text-rendering
  buffered-rendering solid-opacity solid-color color stop-color stop-opacity
  line-increment text-align display-align font-size font-family font-weight
  font-style font-variant direction unicode-bidi text-anchor fill fill-rule
  fill-opacity requiredfeatures requiredformats requiredextensions
  requiredfonts systemlanguage
].freeze

Class Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from BaseRequirement

#collect_sax_data, #get_attributes, #needs_deferred_validation?, #skip_attribute_validation?, #to_s, #validate_document, #validate_sax_complete

Methods included from Interfaces::RequirementInterface

#collect_sax_data, #needs_deferred_validation?, #reset_state, #to_s, #validate_document, #validate_sax_complete

Methods included from NodeHelpers

#element?, #get_attribute, #has_attribute?, #remove_attribute, #set_attribute, #text?

Constructor Details

#initialize(**args) ⇒ AllowedElementsRequirement

Returns a new instance of AllowedElementsRequirement.



76
77
78
79
# File 'lib/svg_conform/requirements/allowed_elements_requirement.rb', line 76

def initialize(**args)
  super(args)
  after_initialize
end

Class Attribute Details

.configuration_validation_cacheObject (readonly)

Returns the value of attribute configuration_validation_cache.



57
58
59
# File 'lib/svg_conform/requirements/allowed_elements_requirement.rb', line 57

def configuration_validation_cache
  @configuration_validation_cache
end

.configuration_validation_mutexObject (readonly)

Returns the value of attribute configuration_validation_mutex.



57
58
59
# File 'lib/svg_conform/requirements/allowed_elements_requirement.rb', line 57

def configuration_validation_mutex
  @configuration_validation_mutex
end

Instance Method Details

#after_initializeObject



81
82
83
# File 'lib/svg_conform/requirements/allowed_elements_requirement.rb', line 81

def after_initialize
  build_element_config_index if element_configs&.any?
end

#build_element_config_indexObject

Build element configuration index for O(1) lookup



91
92
93
94
95
96
97
98
99
100
# File 'lib/svg_conform/requirements/allowed_elements_requirement.rb', line 91

def build_element_config_index
  return {} unless element_configs&.any?

  index = {}
  element_configs.each do |config|
    index[config.tag] = config
    index["*"] = config if config.tag == "*"
  end
  index
end

#check(node, context) ⇒ Object



154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
# File 'lib/svg_conform/requirements/allowed_elements_requirement.rb', line 154

def check(node, context)
  # Validate configuration (uses class-level cache to skip redundant validations)
  validate_configuration

  return unless element?(node)

  # Skip foreign namespace elements if configured (let NamespaceRequirement handle them)
  if skip_foreign_namespaces && foreign_namespace?(node)
    return
  end

  element_name = node.name

  # Check if element is explicitly disallowed
  if disallowed_element?(element_name)
    context.add_error(
      requirement_id: id,
      message: "Element '#{element_name}' is not allowed in this profile",
      node: node,
      severity: :error,
      data: { element: element_name },
    )
    return
  end

  # Check parent-child relationships
  if check_parent_child && node.parent && element?(node.parent)
    parent_name = node.parent.name
    if invalid_parent_child?(parent_name, element_name)
      context.add_error(
        requirement_id: id,
        message: "The element '#{element_name}' is not allowed as a child of '#{parent_name}'",
        node: node,
        severity: :error,
        data: { element: element_name, parent: parent_name },
      )
      # Mark node AND descendants as structurally invalid
      # svgcheck does not validate attributes of forbidden children - just reports one error
      context.mark_node_structurally_invalid(node)
      return
    end
  end

  # Check if element is in allowed list
  if element_configs&.any?
    allowed_elements = element_configs.map(&:tag)
    unless allowed_elements.include?(element_name)
      context.add_error(
        requirement_id: id,
        message: "Element '#{element_name}' is not allowed in this profile",
        node: node,
        severity: :error,
        data: { element: element_name },
      )
      # Mark as structurally invalid so children aren't validated
      # (matches svgcheck behavior: invalid element removed with all children)
      context.mark_node_structurally_invalid(node)
      return
    end
  end

  # Collect all potential attribute errors, then apply priority rules
  potential_errors = collect_attribute_errors(node)
  prioritized_errors = prioritize_errors(potential_errors)

  # Add the prioritized errors to the context
  prioritized_errors.each do |error|
    context.add_error(
      requirement_id: id,
      message: error[:message],
      node: node,
      severity: :error,
    )
  end
end

#element_config_indexObject

Ensure element config index is built (lazy initialization)



86
87
88
# File 'lib/svg_conform/requirements/allowed_elements_requirement.rb', line 86

def element_config_index
  @element_config_index ||= build_element_config_index
end

#validate_configurationObject

Check for configuration conflicts and emit warnings Uses class-level cache to skip validation for identical configurations



104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/svg_conform/requirements/allowed_elements_requirement.rb', line 104

def validate_configuration
  return if allowed_attribute_patterns.empty? || !element_configs&.any?

  # Create cache key from configuration
  config_key = {
    patterns: allowed_attribute_patterns.sort,
    element_configs: element_configs.map do |ec|
      { tag: ec.tag, attr: ec.attr&.sort }
    end,
  }.hash

  # Check cache (thread-safe)
  already_validated = self.class.configuration_validation_mutex.synchronize do
    self.class.configuration_validation_cache[config_key]
  end

  return if already_validated

  # Perform validation
  element_configs.each do |element_config|
    next unless element_config&.attr

    disallowed_attrs = []
    element_config.attr.each do |attribute|
      if attribute.start_with?("!")
        disallowed_attrs << attribute[1..].downcase
      end
    end

    next if disallowed_attrs.empty?

    # Check if any disallowed attribute matches an allowed pattern
    conflicts = disallowed_attrs.select do |disallowed|
      matches_allowed_pattern?(disallowed)
    end

    if conflicts.any?
      warn "Configuration warning in #{id}: " \
           "Element '#{element_config.tag}' has disallowed attributes [#{conflicts.join(', ')}] " \
           "that match allowed_attribute_patterns [#{allowed_attribute_patterns.join(', ')}]. " \
           "Allowed patterns take precedence over element-specific disallowed attributes."
    end
  end

  # Mark as validated (thread-safe)
  self.class.configuration_validation_mutex.synchronize do
    self.class.configuration_validation_cache[config_key] = true
  end
end

#validate_sax_element(element, context) ⇒ Object



230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
# File 'lib/svg_conform/requirements/allowed_elements_requirement.rb', line 230

def validate_sax_element(element, context)
  # Validate configuration (uses class-level cache to skip redundant validations)
  validate_configuration

  # Skip if parent is structurally invalid (matches DOM behavior)
  if element.parent && context.node_structurally_invalid?(element.parent)
    # Mark this element as invalid too since it won't be in final document
    context.mark_node_structurally_invalid(element)
    return
  end

  # Skip foreign namespace elements if configured (let NamespaceRequirement handle them)
  if skip_foreign_namespaces && foreign_namespace_sax?(element)
    return
  end

  element_name = element.name

  # Check if element is explicitly disallowed
  if disallowed_element?(element_name)
    context.add_error(
      requirement_id: id,
      message: "Element '#{element_name}' is not allowed in this profile",
      node: element,
      severity: :error,
      data: { element: element_name },
    )
    return
  end

  # Check parent-child relationships
  if check_parent_child && element.parent
    parent_name = element.parent.name
    if invalid_parent_child?(parent_name, element_name)
      context.add_error(
        requirement_id: id,
        message: "The element '#{element_name}' is not allowed as a child of '#{parent_name}'",
        node: element,
        severity: :error,
        data: { element: element_name, parent: parent_name },
      )
      # Mark node as structurally invalid
      context.mark_node_structurally_invalid(element)
      return
    end
  end

  # Check if element is in allowed list
  if element_configs&.any?
    allowed_elements = element_configs.map(&:tag)
    unless allowed_elements.include?(element_name)
      context.add_error(
        requirement_id: id,
        message: "Element '#{element_name}' is not allowed in this profile",
        node: element,
        severity: :error,
        data: { element: element_name },
      )
      # Mark as structurally invalid
      context.mark_node_structurally_invalid(element)
      return
    end
  end

  # Validate attributes
  potential_errors = collect_attribute_errors_sax(element)
  prioritized_errors = prioritize_errors(potential_errors)

  # Add the prioritized errors to the context
  prioritized_errors.each do |error|
    context.add_error(
      requirement_id: id,
      message: error[:message],
      node: element,
      severity: :error,
    )
  end
end