Passed
Push — main ( ace841...0e8285 )
by Daniel
02:07
created

setSingleElementWithAttribute()   B

Complexity

Conditions 7
Paths 12

Size

Total Lines 20
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 14
c 0
b 0
f 0
nc 12
nop 1
dl 0
loc 20
rs 8.8333
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 ElectornicInvoiceWrite
32
{
33
34
    use TraitVersions;
0 ignored issues
show
introduced by
The trait danielgp\efactura\TraitVersions requires some properties which are not provided by danielgp\efactura\ElectornicInvoiceWrite: $currencyID, $unitCode
Loading history...
35
36
    protected \XMLWriter $objXmlWriter;
37
38
    private function setDocumentTag(array $arrayDocumentData): void
39
    {
40
        $this->objXmlWriter->startElement($arrayDocumentData['DocumentTagName']);
41
        foreach ($arrayDocumentData['DocumentNameSpaces'] as $key => $value) {
42
            if ($key === '') {
43
                $strValue = sprintf($value, $arrayDocumentData['DocumentTagName']);
44
                $this->objXmlWriter->writeAttributeNS(NULL, 'xmlns', NULL, $strValue);
45
            } else {
46
                $this->objXmlWriter->writeAttributeNS('xmlns', $key, NULL, $value);
47
            }
48
        }
49
        if (array_key_exists('SchemaLocation', $arrayDocumentData)) {
50
            $this->objXmlWriter->writeAttribute('xsi:schemaLocation', $arrayDocumentData['SchemaLocation']);
51
        }
52
    }
53
54
    private function setElementsOrdered(array $arrayInput): void
55
    {
56
        $this->setElementComment($arrayInput['commentParentKey']);
57
        $this->objXmlWriter->startElement('cac:' . $arrayInput['tag']);
58
        $this->setExtraElement($arrayInput, 'Start');
59
        $arrayCustomOrder = $this->arraySettings['CustomOrder'][$arrayInput['commentParentKey']];
60
        foreach ($arrayCustomOrder as $value) { // get the values in expected order
61
            if (array_key_exists($value, $arrayInput['data'])) { // because certain value are optional
62
                $key = implode('_', [$arrayInput['commentParentKey'], $value]);
63
                if ($value === 'TaxSubtotal') {
64
                    foreach ($arrayInput['data'][$value] as $value2) { // multiple subt-totals
65
                        $this->setElementsOrdered([
66
                            'commentParentKey' => $key,
67
                            'data'             => $value2,
68
                            'tag'              => $value,
69
                        ]);
70
                    }
71
                } elseif (in_array($value, ['AdditionalCharge', 'AllowanceCharge', 'Item', 'Price'])) {
72
                    $this->setElementsOrdered([
73
                        'commentParentKey' => $key,
74
                        'data'             => $arrayInput['data'][$value],
75
                        'tag'              => $value,
76
                    ]);
77
                } else {
78
                    $matches = []; // scan for special values
79
                    preg_match('/^(EndpointID|.*(Amount|Quantity))$/', $value, $matches, PREG_OFFSET_CAPTURE);
80
                    if ($matches !== []) {
81
                        $this->setSingleElementWithAttribute([
82
                            'commentParentKey' => $arrayInput['commentParentKey'],
83
                            'data'             => $arrayInput['data'][$value],
84
                            'tag'              => $value,
85
                        ]);
86
                    } elseif (is_array($arrayInput['data'][$value])) {
87
                        $this->objXmlWriter->startElement('cac:' . $value);
88
                        $arrayCustomOrder2 = $this->arraySettings['CustomOrder'][$key];
89
                        foreach ($arrayCustomOrder2 as $valueOrd2) {
90
                            if (array_key_exists($valueOrd2, $arrayInput['data'][$value])) { // 4 optional values
91
                                if (is_array($arrayInput['data'][$value][$valueOrd2])) {
92
                                    $this->objXmlWriter->startElement('cac:' . $valueOrd2);
93
                                    foreach ($arrayInput['data'][$value][$valueOrd2] as $key2 => $value2) {
94
                                        $this->setSingleElementWithAttribute([
95
                                            'commentParentKey' => implode('_', [$key, $valueOrd2]),
96
                                            'data'             => $value2,
97
                                            'tag'              => $key2,
98
                                        ]);
99
                                    }
100
                                    $this->objXmlWriter->endElement();
101
                                } else {
102
                                    $this->setSingleElementWithAttribute([
103
                                        'commentParentKey' => $key,
104
                                        'data'             => $arrayInput['data'][$value][$valueOrd2],
105
                                        'tag'              => $valueOrd2,
106
                                    ]);
107
                                }
108
                            }
109
                        }
110
                        $this->objXmlWriter->endElement();
111
                    } else {
112
                        $this->setSingleElementWithAttribute([
113
                            'commentParentKey' => $arrayInput['commentParentKey'],
114
                            'data'             => $arrayInput['data'][$value],
115
                            'tag'              => $value,
116
                        ]);
117
                    }
118
                }
119
            }
120
        }
121
        $this->setExtraElement($arrayInput, 'End');
122
        $this->objXmlWriter->endElement(); // $key
123
    }
124
125
    private function setExtraElement(array $arrayInput, string $strType): void
126
    {
127
        if (in_array($arrayInput['tag'], ['AccountingCustomerParty', 'AccountingSupplierParty'])) {
128
            switch ($strType) {
129
                case 'End':
130
                    $this->objXmlWriter->endElement();
131
                    break;
132
                case 'Start':
133
                    $this->objXmlWriter->startElement('cac:Party');
134
                    break;
135
            }
136
        }
137
    }
138
139
    private function setHeaderCommonBasicComponents(array $arrayElementWithData): void
140
    {
141
        $arrayCustomOrdered = $this->arraySettings['CustomOrder']['Header_CBC'];
142
        foreach ($arrayCustomOrdered as $value) {
143
            $this->setElementComment($value);
144
            $this->objXmlWriter->writeElement('cbc:' . $value, $arrayElementWithData[$value]);
145
        }
146
    }
147
148
    private function setSingleElementWithAttribute(array $arrayInput): void
149
    {
150
        if (array_key_exists('commentParentKey', $arrayInput)) {
151
            $this->setElementComment(implode('_', [$arrayInput['commentParentKey'], $arrayInput['tag']]));
152
            if (str_ends_with($arrayInput['tag'], 'Quantity')) {
153
                $this->setElementComment(implode('_', [$arrayInput['commentParentKey'], $arrayInput['tag']
154
                    . 'UnitOfMeasure']));
155
            }
156
        }
157
        if (is_array($arrayInput['data']) && array_key_exists('value', $arrayInput['data'])) {
158
            $this->objXmlWriter->startElement('cbc:' . $arrayInput['tag']);
159
            foreach ($arrayInput['data'] as $key => $value) {
160
                if ($key != 'value') { // if is not value, must be an attribute
161
                    $this->objXmlWriter->writeAttribute($key, $value);
162
                }
163
            }
164
            $this->objXmlWriter->writeRaw($arrayInput['data']['value']);
165
            $this->objXmlWriter->endElement();
166
        } else {
167
            $this->objXmlWriter->writeElement('cbc:' . $arrayInput['tag'], $arrayInput['data']);
168
        }
169
    }
170
171
    public function writeElectronicInvoice(string $strFile, array $arrayData, bool $bolComments): void
172
    {
173
        $this->objXmlWriter = new \XMLWriter();
174
        $this->objXmlWriter->openURI($strFile);
175
        $this->objXmlWriter->setIndent(true);
176
        $this->objXmlWriter->setIndentString(str_repeat(' ', 4));
177
        $this->objXmlWriter->startDocument('1.0', 'UTF-8');
178
        // if no DocumentNameSpaces seen take Default ones from local configuration
179
        $this->getSettingsFromFileIntoMemory($bolComments);
180
        $arrayDefaults      = $this->getDefaultsIntoDataSet($arrayData);
181
        if ($arrayDefaults !== []) {
182
            $arrayData = array_merge($arrayData, $arrayDefaults['Root']);
183
            if (!array_key_exists('CustomizationID', $arrayData['Header']['CommonBasicComponents-2'])) {
184
                $arrayData['Header']['CommonBasicComponents-2']['CustomizationID'] = $arrayDefaults['CIUS-RO'];
185
                $arrayData['Header']['CommonBasicComponents-2']['UBLVersionID']    = $arrayDefaults['UBL'];
186
            }
187
        }
188
        $this->setDocumentTag($arrayData);
189
        $this->setHeaderCommonBasicComponents($arrayData['Header']['CommonBasicComponents-2']);
190
        $arrayAggegateComponents = $arrayData['Header']['CommonAggregateComponents-2'];
191
        foreach (['AccountingSupplierParty', 'AccountingCustomerParty'] as $strCompanyType) {
192
            $this->setElementsOrdered([
193
                'commentParentKey' => $strCompanyType,
194
                'data'             => $arrayAggegateComponents[$strCompanyType]['Party'],
195
                'tag'              => $strCompanyType,
196
            ]);
197
        }
198
        // multiple accounts can be specified within PaymentMeans
199
        if ($arrayData['DocumentTagName'] === 'Invoice') {
200
            foreach ($arrayAggegateComponents['PaymentMeans'] as $value) {
201
                $this->setElementsOrdered([
202
                    'commentParentKey' => 'PaymentMeans',
203
                    'data'             => $value,
204
                    'tag'              => 'PaymentMeans',
205
                ]);
206
            }
207
        }
208
        foreach (['TaxTotal', 'LegalMonetaryTotal'] as $strTotal) {
209
            $this->setElementsOrdered([
210
                'commentParentKey' => $strTotal,
211
                'data'             => $arrayAggegateComponents[$strTotal],
212
                'tag'              => $strTotal,
213
            ]);
214
        }
215
        // multiple Lines
216
        foreach ($arrayData['Lines'] as $value) {
217
            $this->setElementsOrdered([
218
                'commentParentKey' => 'Lines',
219
                'data'             => $value,
220
                'tag'              => $arrayData['DocumentTagName'] . 'Line',
221
            ]);
222
        }
223
        $this->objXmlWriter->endElement(); // Invoice or CreditNote
224
        $this->objXmlWriter->flush();
225
    }
226
}
227