Module: Lutaml::Xml::Adapter::PlanBasedBuilder

Included in:
BaseAdapter
Defined in:
lib/lutaml/xml/adapter/plan_based_builder.rb

Overview

Builds XML elements from model instances using namespace declaration plans.

Handles both ordered and unordered child serialization, nested model elements, simple values, and namespace resolution. This module is the core of model-to-XML conversion when a DeclarationPlan drives the output.

Instance Method Summary collapse

Instance Method Details

#build_element_with_plan(xml, element, plan, options = {}) ⇒ Object

Build element using prepared namespace declaration plan

Parameters:

  • xml (Builder)

    the XML builder

  • element (Object)

    the model instance

  • plan (DeclarationPlan)

    the declaration plan from DeclarationPlanner

  • options (Hash) (defaults to: {})

    serialization options



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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
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
153
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
# File 'lib/lutaml/xml/adapter/plan_based_builder.rb', line 18

def build_element_with_plan(xml, element, plan, options = {})
  plan ||= DeclarationPlan.empty
  mapper_class = options[:mapper_class] || element.class

  unless mapper_class.is_a?(Class) &&
      mapper_class.include?(Lutaml::Model::Serialize)
    tag_name = options[:tag_name] || "element"
    xml.create_and_add_element(tag_name) do |inner_xml|
      inner_xml.text(text_content_for_xml(element))
    end
    return xml
  end

  xml_mapping = mapper_class.mappings_for(:xml)
  return xml unless xml_mapping

  # TYPE-ONLY MODELS: No element wrapper, serialize children directly
  # BUT if we have a tag_name in options, that means parent wants a wrapper
  if xml_mapping.no_element?
    build_type_only_element(xml, element, xml_mapping, plan, options,
                            mapper_class)
    return xml
  end

  # Use xmlns declarations from plan
  attributes = {}

  # Apply namespace declarations from plan using extracted module
  attributes.merge!(NamespaceDeclarationBuilder.build_xmlns_attributes(plan))

  # Collect attribute custom methods to call after element creation
  attribute_custom_methods = []

  # Add regular attributes (non-xmlns)
  xml_mapping.attributes.each do |attribute_rule|
    next if options[:except]&.include?(attribute_rule.to)

    # Collect custom methods for later execution (after element is created)
    if attribute_rule.custom_methods[:to]
      attribute_custom_methods << attribute_rule
      next
    end

    mapping_rule_name = if attribute_rule.multiple_mappings?
                          attribute_rule.name.first
                        else
                          attribute_rule.name
                        end

    attr = attribute_definition_for(element, attribute_rule,
                                    mapper_class: mapper_class)
    value = attribute_rule.to_value_for(element)

    # Handle as_list and delimiter BEFORE serialization for array values
    # These features convert arrays to delimited strings before serialization
    if value.is_a?(Array)
      if attribute_rule.as_list && attribute_rule.as_list[:export]
        value = attribute_rule.as_list[:export].call(value)
      elsif attribute_rule.delimiter
        value = value.join(attribute_rule.delimiter)
      end
    end

    value = attr.serialize(value, :xml, register) if attr
    value = ExportTransformer.call(value, attribute_rule, attr,
                                   format: :xml)

    if render_element?(attribute_rule, element, value)
      # Resolve attribute namespace using extracted module
      ns_info = AttributeNamespaceResolver.resolve(
        rule: attribute_rule,
        attribute: attr,
        plan: plan,
        mapper_class: mapper_class,
        register: register,
      )

      # Build qualified attribute name based on W3C semantics
      attr_name = AttributeNamespaceResolver.build_qualified_name(
        ns_info,
        mapping_rule_name,
        attribute_rule,
      )
      attributes[attr_name] = value ? value.to_s : value

      # Add local xmlns declaration if needed
      if ns_info[:needs_local_declaration]
        attributes[ns_info[:local_xmlns_attr]] =
          ns_info[:local_xmlns_uri]
      end
    end
  end

  # Add schema_location attribute from ElementNode if present
  attributes.merge!(plan.root_node.schema_location_attr) if plan&.root_node&.schema_location_attr

  # Determine prefix from plan using extracted module
  prefix_info = ElementPrefixResolver.resolve(mapping: xml_mapping,
                                              plan: plan)
  prefix = prefix_info[:prefix]
  ns_decl = if xml_mapping.namespace_class
              plan.namespace_for_class(xml_mapping.namespace_class)
            end

  # Check if element's own namespace needs local declaration (out of scope)
  if ns_decl&.local_on_use?
    xmlns_attr = prefix ? "xmlns:#{prefix}" : "xmlns"
    attributes[xmlns_attr] = ns_decl.uri
  end

  # W3C COMPLIANCE: Detect if element needs xmlns="" using extracted module
  if BlankNamespaceHandler.needs_xmlns_blank?(mapping: xml_mapping,
                                              options: options)
    attributes["xmlns"] = ""
  end

  # Native type inheritance fix: handle local_on_use xmlns="" even if parents uses default format
  xmlns_prefix = nil
  xmlns_ns = nil
  if xml_mapping&.namespace_class && plan
    xmlns_ns = plan.namespace_for_class(xml_mapping.namespace_class)
    xmlns_prefix = xmlns_ns&.prefix
  end
  if xmlns_ns&.local_on_use? && !xml_mapping.namespace_uri
    attributes["xmlns:#{xmlns_prefix}"] =
      xmlns_ns&.uri || xml_mapping.namespace_uri
  end

  tag_name = options[:tag_name] || xml_mapping.root_element
  return if options[:except]&.include?(tag_name)

  # Track if THIS element uses default namespace format
  # Children will need this info to know if they should add xmlns=""
  this_element_uses_default_ns = xml_mapping.namespace_class &&
    plan.namespace_for_class(xml_mapping.namespace_class)&.default_format?

  # Get element_form_default from this element's namespace for children
  parent_element_form_default = xml_mapping.namespace_class&.element_form_default

  xml.create_and_add_element(tag_name, attributes: attributes.compact,
                                       prefix: prefix) do |inner_xml|
    # Call attribute custom methods now that element is created
    attribute_custom_methods.each do |attribute_rule|
      mapper_class.new.send(attribute_rule.custom_methods[:to],
                            element, inner_xml.parent, inner_xml)
    end

    if ordered?(element, options.merge(mapper_class: mapper_class))
      build_ordered_element_with_plan(inner_xml, element, plan,
                                      options.merge(
                                        mapper_class: mapper_class,
                                        parent_prefix: prefix,
                                        parent_uses_default_ns: this_element_uses_default_ns,
                                        parent_element_form_default: parent_element_form_default,
                                        parent_ns_decl: ns_decl,
                                      ))
    else
      build_unordered_children_with_plan(inner_xml, element, plan,
                                         options.merge(
                                           mapper_class: mapper_class,
                                           parent_prefix: prefix,
                                           parent_uses_default_ns: this_element_uses_default_ns,
                                           parent_element_form_default: parent_element_form_default,
                                           parent_ns_decl: ns_decl,
                                         ))
    end
  end
end

#build_ordered_element_with_plan(xml, element, plan, options) ⇒ Object

Build ordered child elements using prepared namespace declaration plan

Parameters:

  • xml (Builder)

    the XML builder

  • element (Object)

    the model instance

  • plan (DeclarationPlan, Hash)

    the declaration plan

  • options (Hash)

    serialization options



415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
# File 'lib/lutaml/xml/adapter/plan_based_builder.rb', line 415

def build_ordered_element_with_plan(xml, element, plan, options)
  mapper_class = options[:mapper_class] || element.class
  xml_mapping = mapper_class.mappings_for(:xml)

  index_hash = {}
  content = []

  element.element_order.each do |object|
    object_key = "#{object.name}-#{object.type}"
    index_hash[object_key] ||= -1
    curr_index = index_hash[object_key] += 1

    element_rule = xml_mapping.find_by_name(object.name,
                                            type: object.type,
                                            node_type: object.node_type,
                                            namespace_uri: object.namespace_uri)
    next if element_rule.nil? || options[:except]&.include?(element_rule.to)

    # Handle custom methods
    if element_rule.custom_methods[:to]
      mapper_class.new.send(element_rule.custom_methods[:to], element,
                            xml.parent, xml)
      next
    end

    # Get attribute definition and value (handle delegation)
    attribute_def, value = fetch_attribute_and_value(element,
                                                     element_rule, mapper_class)

    next if element_rule == xml_mapping.content_mapping && element_rule.cdata && object.text?

    if element_rule == xml_mapping.content_mapping
      process_ordered_content(element, xml_mapping, xml, curr_index,
                              content)
    elsif !value.nil? || element_rule.render_nil?
      process_ordered_element(xml, element, element_rule, attribute_def,
                              value, curr_index, plan, xml_mapping, options)
    end
  end

  add_ordered_content(xml, content) unless content.empty?
end

#build_unordered_children_with_plan(xml, element, plan, options) ⇒ Object

Build unordered child elements using prepared namespace declaration plan

Parameters:

  • xml (Builder)

    the XML builder

  • element (Object)

    the model instance

  • plan (DeclarationPlan, Hash)

    the declaration plan

  • options (Hash)

    serialization options



353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
# File 'lib/lutaml/xml/adapter/plan_based_builder.rb', line 353

def build_unordered_children_with_plan(xml, element, plan, options)
  mapper_class = options[:mapper_class] || element.class
  xml_mapping = mapper_class.mappings_for(:xml)

  # Process child elements with their plans (INCLUDING raw_mapping for map all)
  mappings = xml_mapping.elements + [xml_mapping.raw_mapping].compact
  mappings.each do |element_rule|
    next if options[:except]&.include?(element_rule.to)

    # Handle custom methods
    if element_rule.custom_methods[:to]
      mapper_class.new.send(element_rule.custom_methods[:to], element,
                            xml.parent, xml)
      next
    end

    attribute_def = attribute_definition_for(element, element_rule,
                                             mapper_class: mapper_class)

    # For delegated attributes, attribute_def might be nil
    next unless attribute_def || element_rule.delegate

    value = attribute_value_for(element, element_rule)
    next unless element_rule.render?(value, element)

    # Get child's plan if available
    child_plan = child_plan_for(plan, element_rule.to)

    # Check if value is a Collection instance
    is_collection_instance = value.is_a?(Lutaml::Model::Collection)

    if value && (attribute_def&.type(register)&.<=(Lutaml::Model::Serialize) || is_collection_instance)
      handle_nested_elements_with_plan(
        xml,
        value,
        element_rule,
        attribute_def,
        child_plan,
        options,
        parent_plan: plan,
      )
    elsif element_rule.delegate && attribute_def.nil?
      # Handle non-model values (strings, etc.) for delegated attributes
      add_simple_value(xml, element_rule, value, nil, plan: plan,
                                                      mapping: xml_mapping, options: options)
    else
      add_simple_value(xml, element_rule, value, attribute_def,
                       plan: plan, mapping: xml_mapping, options: options)
    end
  end

  # Process content mapping
  process_content_mapping(element, xml_mapping.content_mapping,
                          xml, mapper_class)
end

#build_xml_element(xml, element, parent_uses_default_ns: false, parent_element_form_default: nil, parent_namespace_class: nil, plan: nil, xml_mapping: nil) ⇒ Object

Build XML from XmlDataModel::XmlElement structure

Parameters:

  • xml (Builder)

    XML builder

  • element (XmlDataModel::XmlElement)

    element to build

  • parent_uses_default_ns (Boolean) (defaults to: false)

    parent uses default namespace format

  • parent_element_form_default (Symbol) (defaults to: nil)

    parent’s element_form_default

  • parent_namespace_class (Class) (defaults to: nil)

    parent’s namespace class

  • plan (DeclarationPlan, nil) (defaults to: nil)

    optional declaration plan for xmlns=“”

  • xml_mapping (Xml::Mapping) (defaults to: nil)

    optional mapping for namespace resolution



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
229
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
# File 'lib/lutaml/xml/adapter/plan_based_builder.rb', line 196

def build_xml_element(xml, element, parent_uses_default_ns: false,
    parent_element_form_default: nil, parent_namespace_class: nil, plan: nil, xml_mapping: nil)
  # Prepare attributes hash
  attributes = {}

  # Get element's namespace class
  element_ns_class = element.namespace_class
  attribute_form_default = element_ns_class&.attribute_form_default || :unqualified
  element_prefix = element_ns_class&.prefix_default

  # Get element_form_default for children
  this_element_form_default = element_ns_class&.element_form_default || :unqualified

  # Add regular attributes
  element.attributes.each do |attr|
    # Determine attribute name with namespace consideration
    attr_name = if attr.namespace_class
                  # Check if attribute is in SAME namespace as element
                  if attr.namespace_class == element_ns_class && attribute_form_default == :unqualified
                    # Same namespace + unqualified -> NO prefix (W3C rule)
                    attr.name
                  else
                    # Different namespace OR qualified -> use prefix
                    attr_prefix = attr.namespace_class.prefix_default
                    attr_prefix ? "#{attr_prefix}:#{attr.name}" : attr.name
                  end
                elsif attribute_form_default == :qualified && element_prefix
                  # Attribute inherits element's namespace when qualified
                  "#{element_prefix}:#{attr.name}"
                else
                  # Unqualified attribute
                  attr.name
                end
    # Ensure attribute value is a string
    attributes[attr_name] = attr.value.to_s
  end

  # Determine element name with namespace prefix
  tag_name = element.name

  # Priority 2.5: Child namespace different from parent's default namespace
  # MUST use prefix format to distinguish from parent
  child_needs_prefix = if element_ns_class && parent_namespace_class &&
      element_ns_class != parent_namespace_class && parent_uses_default_ns
                         element_prefix # Use child's prefix
                       end

  # FIX: Read prefix from plan if available, otherwise use fallback logic
  prefix = if child_needs_prefix
             # Priority 2.5 takes precedence
             child_needs_prefix
           elsif plan && element_ns_class
             # Read format decision from DeclarationPlan
             ns_info = ElementPrefixResolver.resolve(
               mapping: xml_mapping,
               plan: plan,
             )
             ns_info[:prefix]
           elsif element_ns_class && element_prefix
             # Fallback: Element has explicit prefix_default - use prefix format
             element_prefix
           end

  # Track if THIS element uses default namespace format for children
  this_element_uses_default_ns = false

  # Add namespace declaration if element has namespace
  if element.namespace_class
    ns_uri = element.namespace_class.uri

    # Check if namespace is already declared by parent (hoisting optimization)
    # This works for BOTH default and prefix format parents
    ns_already_declared = parent_namespace_class && parent_namespace_class.uri == ns_uri

    if prefix && !ns_already_declared
      attributes["xmlns:#{prefix}"] = ns_uri
      # W3C Compliance: xmlns="" only needed for blank namespace children
      # Prefixed children are already in different namespace from parent's default
    elsif !prefix && !ns_already_declared
      attributes["xmlns"] = ns_uri
      this_element_uses_default_ns = true
    end
  elsif plan && DeclarationPlanQuery.element_needs_xmlns_blank?(plan,
                                                                element)
    # W3C Compliance: Element has no namespace (blank namespace)
    attributes["xmlns"] = ""
  elsif !plan
    # Fallback logic when no plan is available
    if parent_uses_default_ns
      if parent_element_form_default == :qualified
        # Child should INHERIT parent's namespace - no xmlns="" needed
      else
        # Parent's element_form_default is :unqualified - child in blank namespace
        attributes["xmlns"] = ""
      end
    end
  end

  # Check if element was created from nil value with render_nil option
  if element.respond_to?(:xsi_nil) && element.xsi_nil
    attributes["xsi:nil"] = true
  end

  # Create element
  xml.create_and_add_element(tag_name, attributes: attributes,
                                       prefix: prefix) do |inner_xml|
    # Handle raw content (map_all directive)
    has_raw_content = false
    if element.respond_to?(:raw_content)
      raw_content = element.raw_content
      if raw_content && !raw_content.to_s.empty?
        inner_xml.add_xml_fragment(inner_xml, raw_content.to_s)
        has_raw_content = true
      end
    end

    # Skip text content and children if we have raw content
    unless has_raw_content
      # Add text content if present
      if element.text_content
        if element.cdata
          inner_xml.cdata(element.text_content.to_s)
        else
          inner_xml.text(text_content_for_xml(element.text_content))
        end
      end

      # Recursively build child elements, passing namespace context and plan
      element.children.each do |child|
        case child
        when Lutaml::Xml::DataModel::XmlElement
          build_xml_element(inner_xml, child,
                            parent_uses_default_ns: this_element_uses_default_ns,
                            parent_element_form_default: this_element_form_default,
                            parent_namespace_class: element_ns_class,
                            plan: plan,
                            xml_mapping: xml_mapping)
        when Lutaml::Xml::DataModel::XmlComment
          inner_xml.add_comment(child.content)
        when String
          if element.cdata
            inner_xml.cdata(child.to_s)
          else
            inner_xml.text(text_content_for_xml(child))
          end
        end
      end
    end
  end
end