Passed
Push — main ( 0e8285...ab6841 )
by Daniel
02:04
created

ElectornicInvoiceWrite::setExtraElement()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 10
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 8
c 1
b 0
f 0
nc 4
nop 2
dl 0
loc 10
rs 10
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->setElementsOrdered([
93
                                        'commentParentKey' => implode('_', [$key, $valueOrd2]),
94
                                        'data'             => $arrayInput['data'][$value][$valueOrd2],
95
                                        'tag'              => $valueOrd2,
96
                                    ]);
97
                                } else {
98
                                    $this->setSingleElementWithAttribute([
99
                                        'commentParentKey' => $key,
100
                                        'data'             => $arrayInput['data'][$value][$valueOrd2],
101
                                        'tag'              => $valueOrd2,
102
                                    ]);
103
                                }
104
                            }
105
                        }
106
                        $this->objXmlWriter->endElement();
107
                    } else {
108
                        $this->setSingleElementWithAttribute([
109
                            'commentParentKey' => $arrayInput['commentParentKey'],
110
                            'data'             => $arrayInput['data'][$value],
111
                            'tag'              => $value,
112
                        ]);
113
                    }
114
                }
115
            }
116
        }
117
        $this->setExtraElement($arrayInput, 'End');
118
        $this->objXmlWriter->endElement(); // $key
119
    }
120
121
    private function setExtraElement(array $arrayInput, string $strType): void
122
    {
123
        if (in_array($arrayInput['tag'], ['AccountingCustomerParty', 'AccountingSupplierParty'])) {
124
            switch ($strType) {
125
                case 'End':
126
                    $this->objXmlWriter->endElement();
127
                    break;
128
                case 'Start':
129
                    $this->objXmlWriter->startElement('cac:Party');
130
                    break;
131
            }
132
        }
133
    }
134
135
    private function setHeaderCommonBasicComponents(array $arrayElementWithData): void
136
    {
137
        $arrayCustomOrdered = $this->arraySettings['CustomOrder']['Header_CBC'];
138
        foreach ($arrayCustomOrdered as $value) {
139
            $this->setElementComment($value);
140
            $this->objXmlWriter->writeElement('cbc:' . $value, $arrayElementWithData[$value]);
141
        }
142
    }
143
144
    private function setSingleComment(array $arrayInput): void
145
    {
146
        if (array_key_exists('commentParentKey', $arrayInput)) {
147
            $this->setElementComment(implode('_', [$arrayInput['commentParentKey'], $arrayInput['tag']]));
148
            if (str_ends_with($arrayInput['tag'], 'Quantity')) {
149
                $this->setElementComment(implode('_', [$arrayInput['commentParentKey'], $arrayInput['tag']
150
                        . 'UnitOfMeasure']));
151
            }
152
        }
153
    }
154
155
    private function setSingleElementWithAttribute(array $arrayInput): void
156
    {
157
        $this->setSingleComment($arrayInput);
158
        if (is_array($arrayInput['data']) && array_key_exists('value', $arrayInput['data'])) {
159
            $this->objXmlWriter->startElement('cbc:' . $arrayInput['tag']);
160
            foreach ($arrayInput['data'] as $key => $value) {
161
                if ($key != 'value') { // if is not value, must be an attribute
162
                    $this->objXmlWriter->writeAttribute($key, $value);
163
                }
164
            }
165
            $this->objXmlWriter->writeRaw($arrayInput['data']['value']);
166
            $this->objXmlWriter->endElement();
167
        } else {
168
            $this->objXmlWriter->writeElement('cbc:' . $arrayInput['tag'], $arrayInput['data']);
169
        }
170
    }
171
172
    public function writeElectronicInvoice(string $strFile, array $arrayData, bool $bolComments): void
173
    {
174
        $this->objXmlWriter = new \XMLWriter();
175
        $this->objXmlWriter->openURI($strFile);
176
        $this->objXmlWriter->setIndent(true);
177
        $this->objXmlWriter->setIndentString(str_repeat(' ', 4));
178
        $this->objXmlWriter->startDocument('1.0', 'UTF-8');
179
        // if no DocumentNameSpaces seen take Default ones from local configuration
180
        $this->getSettingsFromFileIntoMemory($bolComments);
181
        $arrayDefaults      = $this->getDefaultsIntoDataSet($arrayData);
182
        if ($arrayDefaults !== []) {
183
            $arrayData = array_merge($arrayData, $arrayDefaults['Root']);
184
            if (!array_key_exists('CustomizationID', $arrayData['Header']['CommonBasicComponents-2'])) {
185
                $arrayData['Header']['CommonBasicComponents-2']['CustomizationID'] = $arrayDefaults['CIUS-RO'];
186
                $arrayData['Header']['CommonBasicComponents-2']['UBLVersionID']    = $arrayDefaults['UBL'];
187
            }
188
        }
189
        $this->setDocumentTag($arrayData);
190
        $this->setHeaderCommonBasicComponents($arrayData['Header']['CommonBasicComponents-2']);
191
        $arrayAggegateComponents = $arrayData['Header']['CommonAggregateComponents-2'];
192
        foreach (['AccountingSupplierParty', 'AccountingCustomerParty'] as $strCompanyType) {
193
            $this->setElementsOrdered([
194
                'commentParentKey' => $strCompanyType,
195
                'data'             => $arrayAggegateComponents[$strCompanyType]['Party'],
196
                'tag'              => $strCompanyType,
197
            ]);
198
        }
199
        // multiple accounts can be specified within PaymentMeans
200
        if ($arrayData['DocumentTagName'] === 'Invoice') {
201
            foreach ($arrayAggegateComponents['PaymentMeans'] as $value) {
202
                $this->setElementsOrdered([
203
                    'commentParentKey' => 'PaymentMeans',
204
                    'data'             => $value,
205
                    'tag'              => 'PaymentMeans',
206
                ]);
207
            }
208
        }
209
        foreach (['TaxTotal', 'LegalMonetaryTotal'] as $strTotal) {
210
            $this->setElementsOrdered([
211
                'commentParentKey' => $strTotal,
212
                'data'             => $arrayAggegateComponents[$strTotal],
213
                'tag'              => $strTotal,
214
            ]);
215
        }
216
        // multiple Lines
217
        foreach ($arrayData['Lines'] as $value) {
218
            $this->setElementsOrdered([
219
                'commentParentKey' => 'Lines',
220
                'data'             => $value,
221
                'tag'              => $arrayData['DocumentTagName'] . 'Line',
222
            ]);
223
        }
224
        $this->objXmlWriter->endElement(); // Invoice or CreditNote
225
        $this->objXmlWriter->flush();
226
    }
227
}
228