ChoiceMapping.py 1.44 KB
Newer Older
canterburym's avatar
canterburym committed
import logging

from xmlschema.validators.simple_types import *
from xmlschema.validators.complex_types import *
from xmlschema.validators.groups import *
from xmlschema.validators.facets import *

from .TypeMapping import TypeMapping
from .ComplexTypeMapping import ComplexTypeMapping

log = logging.getLogger()

class ChoiceMapping(ComplexTypeMapping):
    @classmethod
    def process_choice(cls, choice: XsdGroup, current_ns : str):
        if choice.model != 'choice':
            raise Exception(f"Wrong group type: {c.model}")
        oneOf = []
        for c in choice.iter_model():
            if not (type(c) is XsdElement):
                raise Exception (f"Non-element {c} encountered in choice {choice}")
            t = TypeMapping.get_type_from_elem(c, current_ns)
            oneOf.append({
                "type" : "object",
                "properties" : {
                    c.local_name : t
                },
                "required" : [c.local_name]
            })
        return oneOf   

    def map(self, xst : BaseXsdType):
        log.debug(f"Attempting mapping of {xst} to choice")
        j = super().map(xst)
        if j is None:
            log.debug("Not a complex type, giving up")
            return None
        content = xst.content
        if (content.model != 'choice'):
            log.debug("Not a choice, giving up")
            return None
        return { 'oneOf' : ChoiceMapping.process_choice(content, xst.namespaces[''])}