Passed
Branch master (0442a2)
by P.R.
02:00
created

Html.generate_attribute()   F

Complexity

Conditions 14

Size

Total Lines 59

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 59
rs 3.1234
cc 14

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like Html.generate_attribute() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
"""
2
SDoc
3
4
Copyright 2016 Set Based IT Consultancy
5
6
Licence MIT
7
"""
8
9
10
class Html:
11
    """
12
    Static class with helper functions for generating HTML code.
13
    """
14
15
    # ------------------------------------------------------------------------------------------------------------------
16
    @staticmethod
17
    def escape(text, quote=True):
18
        """
19
        Returns a string with special characters converted to HTML entities.
20
21
        :param str text: The string with optionally special characters.
22
        :param bool quote: If true the quotation mark characters, both double quote (") and single quote (')
23
                           characters are also translated.
24
25
        :rtype: str
26
        """
27
        text = text.replace("&", "&")  # Must be done first!
28
        text = text.replace("<", "&lt;")
29
        text = text.replace(">", "&gt;")
30
        if quote:
31
            text = text.replace('"', "&quot;")
32
            text = text.replace('\'', "&#x27;")
33
34
        return text
35
36
    # ------------------------------------------------------------------------------------------------------------------
37
    @staticmethod
38
    def generate_attribute(name, value):
39
        """
40
        Returns a string proper conversion of special characters to HTML entities of an attribute of a HTML tag.
41
42
        :param str name: The name of the attribute.
43
        :param str value: The value of the attribute.
44
45
        :rtype: str
46
        """
47
        html = ''
48
49
        # Boolean attributes.
50
        if name in ('autofocus',
51
                    'checked',
52
                    'disabled',
53
                    'hidden',
54
                    'ismap',
55
                    'multiple',
56
                    'novalidate',
57
                    'readonly',
58
                    'required',
59
                    'selected',
60
                    'spellcheck'):
61
            if value:
62
                html += ' '
63
                html += name
64
                html += '="'
65
                html += name
66
                html += '"'
67
68
        # Annoying boolean attribute exceptions.
69
        elif name in ('draggable', 'contenteditable'):
70
            if value is not None:
71
                html += ' '
72
                html += name
73
                html += '="true"' if value else '="false"'
74
75
        elif name == 'autocomplete':
76
            if value is not None:
77
                html += ' '
78
                html += name
79
                html += '="on"' if value else '="off"'
80
81
        elif name == 'translate':
82
            if value is not None:
83
                html += ' '
84
                html += name
85
                html += '="yes"' if value else '="no"'
86
87
        else:
88
            if value is not None and value != '':
89
                html += ' '
90
                html += Html.escape(name)
91
                html += '="'
92
                html += Html.escape(value)
93
                html += '"'
94
95
        return html
96
97
    # ------------------------------------------------------------------------------------------------------------------
98
    @staticmethod
99
    def generate_element(tag_name, attributes=None, inner_text='', is_html=False):
100
        """
101
        Generates HTML code for an element.
102
103
        Note: tags for void elements such as '<br/>' are not supported.
104
105
        :param str tag_name: The name of the tag, e.g. a, form.
106
        :param dict[str,str] attributes: The attributes of the tag. Special characters in the attributes will be
107
                                         replaced with HTML entities.
108
        :param str inner_text: The inner text of the tag.
109
        :param bool is_html: If set the inner text is a HTML snippet, otherwise special characters in the inner text
110
                             will be replaced with HTML entities.
111
112
        :rtype: str
113
        """
114
        html = Html.generate_tag(tag_name, attributes)
115
        html += inner_text if is_html else Html.escape(inner_text)
116
        html += '</'
117
        html += tag_name
118
        html += '>'
119
120
        return html
121
122
    # ------------------------------------------------------------------------------------------------------------------
123
    @staticmethod
124
    def generate_tag(tag_name, attributes=None):
125
        """
126
        Generates HTML code for a start tag of an element.
127
128
        :param str tag_name: The name of the tag, e.g. a, form.
129
        :param dict[str,str] attributes: The attributes of the tag. Special characters in the attributes will be
130
                                         replaced with HTML entities.
131
132
        :rtype: str
133
        """
134
        html = '<'
135
        html += tag_name
136
        for key in sorted(attributes):
137
            html += Html.generate_attribute(key, attributes[key])
138
        html += '>'
139
140
        return html
141
142
    # ------------------------------------------------------------------------------------------------------------------
143
    @staticmethod
144
    def generate_void_element(tag_name, attributes=None):
145
        """
146
        Generates HTML code for an element.
147
148
        Note: tags for void elements such as '<br/>' are not supported.
149
150
        :param str tag_name: The name of the tag, e.g. a, form.
151
        :param dict[str,str] attributes: The attributes of the tag. Special characters in the attributes will be
152
                                         replaced with HTML entities.
153
154
        :rtype: str
155
        """
156
        html = '<'
157
        html += tag_name
158
        for key in sorted(attributes):
159
            html += Html.generate_attribute(key, attributes[key])
160
        html += '/>'
161
162
        return html
163
164
# ----------------------------------------------------------------------------------------------------------------------
165