Class: Canon::Xml::DataModel

Inherits:
DataModel
  • Object
show all
Defined in:
lib/canon/xml/data_model.rb

Class Method Summary collapse

Class Method Details

.assign_moxml_namespace_scopes(element, inherited, own_namespaces) ⇒ Object



316
317
318
319
320
321
322
323
324
# File 'lib/canon/xml/data_model.rb', line 316

def self.assign_moxml_namespace_scopes(element, inherited, own_namespaces)
  scope = TreeBuilder::DEFAULT.merge_namespace_scope(inherited,
                                                     own_namespaces[element].to_a)
  TreeBuilder::DEFAULT.attach_namespace_scope(element, scope)

  element.children.each do |child|
    assign_moxml_namespace_scopes(child, scope, own_namespaces) if child.is_a?(Nodes::ElementNode)
  end
end

.build_from_moxml(moxml_doc, preserve_whitespace: false) ⇒ Object



236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
# File 'lib/canon/xml/data_model.rb', line 236

def self.build_from_moxml(moxml_doc, preserve_whitespace: false)
  root = Nodes::RootNode.new
  skip_types = [Moxml::Doctype]

  if moxml_doc.is_a?(Moxml::Document) && moxml_doc.root
    element = build_moxml_subtree_from_records(moxml_doc.root,
                                               preserve_whitespace: preserve_whitespace)
    root.add_child(element) if element
    TreeBuilder::DEFAULT.add_document_children(root, moxml_doc.children,
                                               moxml_doc.root, skip_types) do |child|
      walk_moxml(child, preserve_whitespace: preserve_whitespace)
    end
  else
    TreeBuilder::DEFAULT.add_document_children(root, moxml_doc.children,
                                               nil, skip_types) do |child|
      walk_moxml(child, preserve_whitespace: preserve_whitespace)
    end
  end

  root
end

.build_from_nokogiri(nokogiri_doc, preserve_whitespace: false) ⇒ Object

-- Nokogiri walk: top-down, scope flows down the recursion --



139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/canon/xml/data_model.rb', line 139

def self.build_from_nokogiri(nokogiri_doc, preserve_whitespace: false)
  root = Nodes::RootNode.new
  skip_types = defined?(Nokogiri) ? [Nokogiri::XML::DTD] : []

  if nokogiri_doc.is_a?(Nokogiri::XML::Document) && nokogiri_doc.root
    root.add_child(walk_nokogiri(nokogiri_doc.root,
                                 preserve_whitespace: preserve_whitespace))
    TreeBuilder::DEFAULT.add_document_children(root, nokogiri_doc.children,
                                               nokogiri_doc.root, skip_types) do |child|
      walk_nokogiri(child, preserve_whitespace: preserve_whitespace)
    end
  else
    TreeBuilder::DEFAULT.add_document_children(root, nokogiri_doc.children,
                                               nil, skip_types) do |child|
      walk_nokogiri(child, preserve_whitespace: preserve_whitespace)
    end
  end

  root
end

.build_moxml_element_from_record(record, frames, own_namespaces) ⇒ Object



298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
# File 'lib/canon/xml/data_model.rb', line 298

def self.build_moxml_element_from_record(record, frames, own_namespaces)
  element = TreeBuilder::DEFAULT.element(
    name: record[:qname],
    prefix: record[:prefix],
    namespace_uri: record[:namespace_uri],
    attributes: record[:attributes],
  )

  # Adopt completed children: they pop in reverse order; reversing
  # once is O(n) (unshift per child would be O(n^2) on wide trees).
  children = []
  children << frames.pop[1] while frames.any? && frames.last[0] > record[:depth]
  children.reverse_each { |child| element.add_child(child) }

  own_namespaces[element] = record[:namespaces]
  element
end

.build_moxml_subtree_from_records(moxml_element, preserve_whitespace: false) ⇒ Object



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
# File 'lib/canon/xml/data_model.rb', line 258

def self.build_moxml_subtree_from_records(moxml_element,
preserve_whitespace: false)
  frames = []
  own_namespaces = {}.compare_by_identity

  moxml_element.materialize do |record|
    # The record contract is root-subtree-only since moxml 0.5.11
    # (moxml#140). Older 0.5.x releases — still allowed by canon's
    # gemspec floor — leaked epilog document-level records at depth
    # 0, which the document-children enumeration also covers; one
    # integer compare per record keeps those working.
    next if record[:depth].zero? && record[:kind] != :element

    node = case record[:kind]
           when :element
             build_moxml_element_from_record(record, frames,
                                             own_namespaces)
           when :text, :cdata
             content = record[:text].to_s
             TreeBuilder::DEFAULT.text(content,
                                       keep: WhitespacePolicy.keep_dom_text?(
                                         content, preserve_whitespace: preserve_whitespace
                                       ))
           when :comment
             TreeBuilder::DEFAULT.comment(record[:text])
           when :processing_instruction
             TreeBuilder::DEFAULT.processing_instruction(record[:qname],
                                                         record[:text] || "")
           end

    frames.push([record[:depth], node]) if node
  end

  top = frames.last
  return nil unless top

  assign_moxml_namespace_scopes(top[1], nil, own_namespaces)
  top[1]
end

.check_for_relative_namespace_uris(doc) ⇒ Object



115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/canon/xml/data_model.rb', line 115

def self.check_for_relative_namespace_uris(doc)
  doc.traverse do |node|
    next unless node.is_a?(Nokogiri::XML::Element)

    node.namespace_definitions.each do |ns|
      next if ns.href.nil? || ns.href.empty?
      if relative_uri?(ns.href)
        raise Canon::Error,
              "Relative namespace URI not allowed: #{ns.href}"
      end
    end
  end
end

.check_moxml_relative_namespace_uris(node) ⇒ Object



219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
# File 'lib/canon/xml/data_model.rb', line 219

def self.check_moxml_relative_namespace_uris(node)
  case node
  when Moxml::Element
    node.namespace_definitions.each do |ns|
      href = ns.uri
      next if href.nil? || href.empty?
      if relative_uri?(href)
        raise Canon::Error,
              "Relative namespace URI not allowed: #{href}"
      end
    end
    node.children.each { |child| check_moxml_relative_namespace_uris(child) }
  when Moxml::Document
    node.children.each { |child| check_moxml_relative_namespace_uris(child) }
  end
end

.extract_xml_encoding(xml_string) ⇒ Object



82
83
84
85
86
87
88
89
# File 'lib/canon/xml/data_model.rb', line 82

def self.extract_xml_encoding(xml_string)
  binary_string = xml_string.dup.force_encoding("BINARY")
  if binary_string =~ /\A\s*<\?xml[^>]*\bencoding\s*=\s*["']([^"']+)["'][^>]*\?>/i
    return Regexp.last_match(1)
  end

  nil
end

.from_moxml_xml(xml_string, preserve_whitespace:) ⇒ Object

-- moxml record stream: post-order frames adopt children -- One flattened record stream (moxml#132/#138) instead of a wrapper walk, so document conversion costs no Moxml::Node allocation per node. Own namespace declarations ride an identity-keyed stash; assign_moxml_namespace_scopes expands them to in-scope scopes afterwards (post-order arrival means scopes cannot flow down during the stream).



207
208
209
210
211
212
213
214
215
216
217
# File 'lib/canon/xml/data_model.rb', line 207

def self.from_moxml_xml(xml_string, preserve_whitespace:)
  doc = Canon::XmlParsing.moxml_context.parse(xml_string, readonly: true)
  check_moxml_relative_namespace_uris(doc)
  result = build_from_moxml(doc, preserve_whitespace: preserve_whitespace)
  # Canon owns this document's full lifecycle: the canon tree holds
  # no engine references once built, so release the native tree now
  # instead of waiting for the GC finalizer (moxml#134; no-op on
  # GC-managed adapters).
  doc.free
  result
end

.from_nokogiri_xml(xml_string, preserve_whitespace:) ⇒ Object

--- Nokogiri path ---



105
106
107
108
109
110
111
112
113
# File 'lib/canon/xml/data_model.rb', line 105

def self.from_nokogiri_xml(xml_string, preserve_whitespace:)
  doc = Nokogiri::XML(xml_string, &:nonet)
  check_for_relative_namespace_uris(doc)
  result = build_from_nokogiri(doc,
                               preserve_whitespace: preserve_whitespace)
  errors = Array(doc.errors).map(&:to_s)
  result.parse_errors = errors if errors.any?
  result
end

.from_xml(xml_string, preserve_whitespace: false) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
# File 'lib/canon/xml/data_model.rb', line 9

def self.from_xml(xml_string, preserve_whitespace: false)
  normalized_xml = normalize_encoding(xml_string)

  if Canon::XmlBackend.nokogiri?
    from_nokogiri_xml(normalized_xml,
                      preserve_whitespace: preserve_whitespace)
  else
    from_moxml_xml(normalized_xml,
                   preserve_whitespace: preserve_whitespace)
  end
end

.normalize_encoding(xml_string) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/canon/xml/data_model.rb', line 21

def self.normalize_encoding(xml_string)
  return xml_string unless xml_string.is_a?(String)

  declared_encoding = extract_xml_encoding(xml_string)

  if declared_encoding
    if declared_encoding.upcase != "UTF-8"
      utf8_reinterpreted = try_utf8_reinterpretation(xml_string)
      if utf8_reinterpreted
        return update_xml_declaration(xml_string,
                                      "UTF-8")
      end

      return transcode_to_utf8(xml_string, declared_encoding)
    end
  elsif xml_string.encoding.name != "UTF-8"
    reinterpreted = try_utf8_reinterpretation(xml_string)
    return reinterpreted if reinterpreted

    return transcode_to_utf8(xml_string, xml_string.encoding.name)
  end

  xml_string
end

.parse(xml_string) ⇒ Object



91
92
93
# File 'lib/canon/xml/data_model.rb', line 91

def self.parse(xml_string)
  from_xml(xml_string)
end

.relative_uri?(uri) ⇒ Boolean

Returns:

  • (Boolean)


99
100
101
# File 'lib/canon/xml/data_model.rb', line 99

def self.relative_uri?(uri)
  uri !~ %r{^[a-zA-Z][a-zA-Z0-9+.-]*:}
end

.serialize(node) ⇒ Object



95
96
97
# File 'lib/canon/xml/data_model.rb', line 95

def self.serialize(node)
  node.to_s
end

.transcode_to_utf8(xml_string, source_encoding) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/canon/xml/data_model.rb', line 52

def self.transcode_to_utf8(xml_string, source_encoding)
  if source_encoding != "UTF-8"
    forced = xml_string.dup.force_encoding(source_encoding)
    if forced.valid_encoding?
      utf8_check = xml_string.dup.force_encoding("UTF-8")
      if utf8_check.valid_encoding?
        return xml_string.dup.force_encoding("UTF-8")
      end

      return forced.encode("UTF-8", source_encoding,
                           invalid: :replace,
                           undef: :replace,
                           replace: "?")
    end
  end

  xml_string.dup.force_encoding("UTF-8")
rescue EncodingError
  xml_string
end

.try_utf8_reinterpretation(xml_string) ⇒ Object



73
74
75
76
77
78
79
80
# File 'lib/canon/xml/data_model.rb', line 73

def self.try_utf8_reinterpretation(xml_string)
  return xml_string if xml_string.encoding.name == "UTF-8"

  forced = xml_string.dup.force_encoding("UTF-8")
  return forced if forced.valid_encoding?

  nil
end

.update_xml_declaration(xml_string, new_encoding) ⇒ Object



46
47
48
49
50
# File 'lib/canon/xml/data_model.rb', line 46

def self.update_xml_declaration(xml_string, new_encoding)
  xml_string.sub(/\bencoding\s*=\s*["'][^"']+["']/i) do |_match|
    %(encoding="#{new_encoding}")
  end
end

.walk_moxml(node, preserve_whitespace: false, inherited_namespaces: nil) ⇒ Object

-- moxml wrapper walk: fragments and user-supplied nodes --



328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
# File 'lib/canon/xml/data_model.rb', line 328

def self.walk_moxml(node, preserve_whitespace: false,
inherited_namespaces: nil)
  case node
  when Moxml::Element
    scope = TreeBuilder::DEFAULT.merge_namespace_scope(
      inherited_namespaces,
      node.namespace_definitions.map { |ns| [ns.prefix, ns.uri] },
    )
    element = TreeBuilder::DEFAULT.element(
      name: node.name,
      prefix: node.namespace&.prefix,
      namespace_uri: node.namespace&.uri,
      attributes: node.attributes.map do |attr|
        [attr.name, attr.value, attr.namespace&.uri, attr.namespace&.prefix]
      end,
      namespace_scope: scope,
    )
    node.children.each do |child|
      built = walk_moxml(child,
                         preserve_whitespace: preserve_whitespace,
                         inherited_namespaces: scope)
      element.add_child(built) if built
    end
    element
  when Moxml::Text, Moxml::Cdata
    TreeBuilder::DEFAULT.text(node.content,
                              keep: WhitespacePolicy.keep_dom_text?(
                                node.content,
                                preserve_whitespace: preserve_whitespace,
                                element_parent: node.parent.is_a?(Moxml::Element),
                              ))
  when Moxml::Comment
    TreeBuilder::DEFAULT.comment(node.content)
  when Moxml::ProcessingInstruction
    TreeBuilder::DEFAULT.processing_instruction(node.target, node.content)
  end
end

.walk_nokogiri(node, preserve_whitespace:, inherited_namespaces: nil) ⇒ Object



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
# File 'lib/canon/xml/data_model.rb', line 160

def self.walk_nokogiri(node, preserve_whitespace:,
inherited_namespaces: nil)
  case node
  when Nokogiri::XML::Element
    scope = TreeBuilder::DEFAULT.merge_namespace_scope(
      inherited_namespaces,
      node.namespace_definitions.map { |ns| [ns.prefix, ns.href] },
    )
    element = TreeBuilder::DEFAULT.element(
      name: node.name,
      prefix: node.namespace&.prefix,
      namespace_uri: node.namespace&.href,
      attributes: node.attribute_nodes.map do |attr|
        [attr.name, attr.value, attr.namespace&.href, attr.namespace&.prefix]
      end,
      namespace_scope: scope,
    )
    node.children.each do |child|
      built = walk_nokogiri(child,
                            preserve_whitespace: preserve_whitespace,
                            inherited_namespaces: scope)
      element.add_child(built) if built
    end
    element
  when Nokogiri::XML::Text, Nokogiri::XML::CDATA
    TreeBuilder::DEFAULT.text(node.content,
                              keep: WhitespacePolicy.keep_dom_text?(
                                node.content,
                                preserve_whitespace: preserve_whitespace,
                                element_parent: node.parent.is_a?(Nokogiri::XML::Element),
                              ),
                              original: node.to_xml)
  when Nokogiri::XML::Comment
    TreeBuilder::DEFAULT.comment(node.content)
  when Nokogiri::XML::ProcessingInstruction
    TreeBuilder::DEFAULT.processing_instruction(node.name, node.content)
  end
end