Passed
Branch main (249e74)
by Daniel
02:10
created

ElectronicInvoiceWrite   A

Complexity

Total Complexity 42

Size/Duplication

Total Lines 214
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 134
c 3
b 0
f 0
dl 0
loc 214
rs 9.0399
wmc 42

11 Methods

Rating   Name   Duplication   Size   Complexity  
B setDecisionElements() 0 33 6
B setProduceMiddleXml() 0 26 6
A setExtraElement() 0 10 4
A setHeaderCommonBasicComponents() 0 7 3
A setElementsOrdered() 0 21 3
A setElementComment() 0 10 4
A setPrepareXml() 0 18 4
A setSingleComment() 0 7 3
A setSingleElementWithAttribute() 0 14 5
A writeElectronicInvoice() 0 18 2
A setMultipleElementsOrdered() 0 8 2

How to fix   Complexity   

Complex Class

Complex classes like ElectronicInvoiceWrite 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.

While breaking up the class, it is a good idea to analyze how other classes use ElectronicInvoiceWrite, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 *
5
 * The MIT License (MIT)
6
 *
7
 * Copyright (c) 2024 Daniel Popiniuc
8
 *
9
 * Permission is hereby granted, free of charge, to any person obtaining a copy
10
 * of this software and associated documentation files (the "Software"), to deal
11
 * in the Software without restriction, including without limitation the rights
12
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
 * copies of the Software, and to permit persons to whom the Software is
14
 * furnished to do so, subject to the following conditions:
15
 *
16
 * The above copyright notice and this permission notice shall be included in all
17
 * copies or substantial portions of the Software.
18
 *
19
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
 * SOFTWARE.
26
 *
27
 */
28
29
namespace danielgp\efactura;
30
31
class ElectronicInvoiceWrite
32
{
33
    use TraitVersions;
34
35
    protected \XMLWriter $objXmlWriter;
36
37
    private function setDecisionElements(array $arrayInput, string $strKey, string $strTag, string $strCategory): void
38
    {
39
        switch ($strCategory) {
40
            case 'ArrayElementsOrdered':
41
                foreach ($arrayInput['data'][$strTag] as $value2) {
42
                    $this->setElementsOrdered([
43
                        'commentParentKey' => $strKey,
44
                        'data'             => $value2,
45
                        'tag'              => $strTag,
46
                    ]);
47
                }
48
                break;
49
            case 'ElementsOrdered':
50
                $this->setElementsOrdered([
51
                    'commentParentKey' => $strKey,
52
                    'data'             => $arrayInput['data'][$strTag],
53
                    'tag'              => $strTag,
54
                ]);
55
                break;
56
            case 'MultipleElementsOrdered':
57
                $this->setMultipleElementsOrdered([
58
                    'commentParentKey' => $strKey,
59
                    'data'             => $arrayInput['data'][$strTag],
60
                    'tag'              => $strTag,
61
                ]);
62
                break;
63
            case 'SingleElementWithAttribute':
64
                $this->setSingleElementWithAttribute([
65
                    'commentParentKey' => $arrayInput['commentParentKey'],
66
                    'data'             => $arrayInput['data'][$strTag],
67
                    'tag'              => $strTag,
68
                ]);
69
                break;
70
        }
71
    }
72
73
    private function setElementComment(string $strKey): void
74
    {
75
        if (array_key_exists($strKey, $this->arraySettings['Comments'])) {
76
            $elementComment = $this->arraySettings['Comments'][$strKey];
77
            if (is_array($elementComment)) {
78
                foreach ($elementComment as $value) {
79
                    $this->objXmlWriter->writeComment($value);
80
                }
81
            } else {
82
                $this->objXmlWriter->writeComment($elementComment);
83
            }
84
        }
85
    }
86
87
    private function setElementsOrdered(array $arrayInput): void
88
    {
89
        $this->setElementComment($arrayInput['commentParentKey']);
90
        $this->objXmlWriter->startElement('cac:' . $arrayInput['tag']);
91
        $this->setExtraElement($arrayInput, 'Start');
92
        foreach ($this->arraySettings['CustomOrder'][$arrayInput['commentParentKey']] as $value) {
93
            if (array_key_exists($value, $arrayInput['data'])) { // because certain value are optional
94
                $key         = implode('_', [$arrayInput['commentParentKey'], $value]);
95
                $matches     = [];
96
                preg_match('/^.*(Amount|Quantity)$/', $value, $matches, PREG_OFFSET_CAPTURE);
97
                $strCategory = $this->setCategorizedVerifications([
98
                    'commentParentKey' => $arrayInput['commentParentKey'],
99
                    'data'             => $arrayInput['data'][$value],
100
                    'matches'          => $matches,
101
                    'tag'              => $value,
102
                ]);
103
                $this->setDecisionElements($arrayInput, $key, $value, $strCategory);
104
            }
105
        }
106
        $this->setExtraElement($arrayInput, 'End');
107
        $this->objXmlWriter->endElement(); // $arrayInput['tag']
108
    }
109
110
    private function setExtraElement(array $arrayInput, string $strType): void
111
    {
112
        if (in_array($arrayInput['tag'], ['AccountingCustomerParty', 'AccountingSupplierParty'])) {
113
            switch ($strType) {
114
                case 'End':
115
                    $this->objXmlWriter->endElement();
116
                    break;
117
                case 'Start':
118
                    $this->objXmlWriter->startElement('cac:Party');
119
                    break;
120
            }
121
        }
122
    }
123
124
    private function setHeaderCommonBasicComponents(array $arrayElementWithData): void
125
    {
126
        $arrayCustomOrdered = $this->arraySettings['CustomOrder']['Header_CBC'];
127
        foreach ($arrayCustomOrdered as $value) {
128
            if (array_key_exists($value, $arrayElementWithData)) {
129
                $this->setElementComment($value);
130
                $this->objXmlWriter->writeElement('cbc:' . $value, $arrayElementWithData[$value]);
131
            }
132
        }
133
    }
134
135
    private function setMultipleElementsOrdered(array $arrayData): void
136
    {
137
        foreach ($arrayData['data'] as $value) {
138
            $strCommentParentKey = $this->setManageComment($arrayData['commentParentKey'], $value);
139
            $this->setElementsOrdered([
140
                'commentParentKey' => $strCommentParentKey,
141
                'data'             => $value,
142
                'tag'              => $arrayData['tag'],
143
            ]);
144
        }
145
    }
146
147
    private function setPrepareXml(string $strFile, int $intIdent = 4, array $arrayDocumentData): void
148
    {
149
        $this->objXmlWriter = new \XMLWriter();
150
        $this->objXmlWriter->openURI($strFile);
151
        $this->objXmlWriter->setIndent(true);
152
        $this->objXmlWriter->setIndentString(str_repeat(' ', $intIdent));
153
        $this->objXmlWriter->startDocument('1.0', 'UTF-8');
154
        $this->objXmlWriter->startElement($arrayDocumentData['DocumentTagName']);
155
        foreach ($arrayDocumentData['DocumentNameSpaces'] as $key => $value) {
156
            if ($key === '') {
157
                $strValue = sprintf($value, $arrayDocumentData['DocumentTagName']);
158
                $this->objXmlWriter->writeAttributeNS(null, 'xmlns', null, $strValue);
159
            } else {
160
                $this->objXmlWriter->writeAttributeNS('xmlns', $key, null, $value);
161
            }
162
        }
163
        if (array_key_exists('SchemaLocation', $arrayDocumentData)) {
164
            $this->objXmlWriter->writeAttribute('xsi:schemaLocation', $arrayDocumentData['SchemaLocation']);
165
        }
166
    }
167
168
    private function setProduceMiddleXml(array $arrayData): void
169
    {
170
        foreach ($this->arrayProcessing['OptionalElementsHeader'] as $key => $strLogicType) {
171
            if (array_key_exists($key, $arrayData)) {
172
                switch ($strLogicType) {
173
                    case 'Multiple':
174
                        $this->setMultipleElementsOrdered([
175
                            'commentParentKey' => $key,
176
                            'data'             => $arrayData[$key],
177
                            'tag'              => $key,
178
                        ]);
179
                        break;
180
                    case 'Single':
181
                        $this->setElementsOrdered([
182
                            'commentParentKey' => $key,
183
                            'data'             => $arrayData[$key],
184
                            'tag'              => $key,
185
                        ]);
186
                        break;
187
                    case 'SingleCompany':
188
                        $this->setElementsOrdered([
189
                            'commentParentKey' => $key,
190
                            'data'             => $arrayData[$key]['Party'],
191
                            'tag'              => $key,
192
                        ]);
193
                        break;
194
                }
195
            }
196
        }
197
    }
198
199
    private function setSingleComment(array $arrayInput): void
200
    {
201
        if (array_key_exists('commentParentKey', $arrayInput)) {
202
            $this->setElementComment(implode('_', [$arrayInput['commentParentKey'], $arrayInput['tag']]));
203
            if (str_ends_with($arrayInput['tag'], 'Quantity')) {
204
                $this->setElementComment(implode('_', [$arrayInput['commentParentKey'], $arrayInput['tag']
205
                    . 'UnitOfMeasure']));
206
            }
207
        }
208
    }
209
210
    private function setSingleElementWithAttribute(array $arrayInput): void
211
    {
212
        $this->setSingleComment($arrayInput);
213
        if (is_array($arrayInput['data']) && array_key_exists('value', $arrayInput['data'])) {
214
            $this->objXmlWriter->startElement('cbc:' . $arrayInput['tag']);
215
            foreach ($arrayInput['data'] as $key => $value) {
216
                if ($key !== 'value') { // if is not value, must be an attribute
217
                    $this->objXmlWriter->writeAttribute($key, $value);
218
                }
219
            }
220
            $this->objXmlWriter->writeRaw($this->setNumericValue($arrayInput['tag'], $arrayInput['data']));
221
            $this->objXmlWriter->endElement();
222
        } else {
223
            $this->objXmlWriter->writeElement('cbc:' . $arrayInput['tag'], $arrayInput['data']);
224
        }
225
    }
226
227
    public function writeElectronicInvoice(string $strFile, array $inData, array $arrayFeatures): void
228
    {
229
        $this->getProcessingDetails();
230
        $arrayData = $this->loadSettingsAndManageDefaults($inData, $arrayFeatures);
231
        if (!array_key_exists('Ident', $arrayFeatures)) {
232
            $arrayFeatures['Ident'] = 4;
233
        }
234
        $this->setPrepareXml($strFile, $arrayFeatures['Ident'], $arrayData);
235
        $this->setHeaderCommonBasicComponents($arrayData['Header']['CommonBasicComponents-2']);
236
        $this->setProduceMiddleXml($arrayData['Header']['CommonAggregateComponents-2']);
237
        // multiple Lines
238
        $this->setMultipleElementsOrdered([
239
            'commentParentKey' => 'Lines',
240
            'data'             => $arrayData['Lines'],
241
            'tag'              => $arrayData['DocumentTagName'] . 'Line',
242
        ]);
243
        $this->objXmlWriter->endElement(); // Invoice or CreditNote
244
        $this->objXmlWriter->flush();
245
    }
246
}
247