Passed
Push — main ( 979f06...ddec1e )
by Daniel
02:04
created

loadSettingsAndManageDefaults()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 8
c 1
b 0
f 0
nc 3
nop 2
dl 0
loc 13
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 loadSettingsAndManageDefaults(array $arrayData, bool $bolComments): array
39
    {
40
        // if no DocumentNameSpaces seen take Default ones from local configuration
41
        $this->getSettingsFromFileIntoMemory($bolComments);
42
        $arrayDefaults      = $this->getDefaultsIntoDataSet($arrayData);
43
        if ($arrayDefaults !== []) {
44
            $arrayData = array_merge($arrayData, $arrayDefaults['Root']);
45
            if (!array_key_exists('CustomizationID', $arrayData['Header']['CommonBasicComponents-2'])) {
46
                $arrayData['Header']['CommonBasicComponents-2']['CustomizationID'] = $arrayDefaults['CIUS-RO'];
47
                $arrayData['Header']['CommonBasicComponents-2']['UBLVersionID']    = $arrayDefaults['UBL'];
48
            }
49
        }
50
        return $arrayData;
51
    }
52
53
    private function setDocumentTag(array $arrayDocumentData): void
54
    {
55
        $this->objXmlWriter->startElement($arrayDocumentData['DocumentTagName']);
56
        foreach ($arrayDocumentData['DocumentNameSpaces'] as $key => $value) {
57
            if ($key === '') {
58
                $strValue = sprintf($value, $arrayDocumentData['DocumentTagName']);
59
                $this->objXmlWriter->writeAttributeNS(NULL, 'xmlns', NULL, $strValue);
60
            } else {
61
                $this->objXmlWriter->writeAttributeNS('xmlns', $key, NULL, $value);
62
            }
63
        }
64
        if (array_key_exists('SchemaLocation', $arrayDocumentData)) {
65
            $this->objXmlWriter->writeAttribute('xsi:schemaLocation', $arrayDocumentData['SchemaLocation']);
66
        }
67
    }
68
69
    private function setElementsOrdered(array $arrayInput): void
70
    {
71
        $this->setElementComment($arrayInput['commentParentKey']);
72
        $this->objXmlWriter->startElement('cac:' . $arrayInput['tag']);
73
        $this->setExtraElement($arrayInput, 'Start');
74
        $arrayCustomOrder = $this->arraySettings['CustomOrder'][$arrayInput['commentParentKey']];
75
        foreach ($arrayCustomOrder as $value) { // get the values in expected order
76
            if (array_key_exists($value, $arrayInput['data'])) { // because certain value are optional
77
                $key = implode('_', [$arrayInput['commentParentKey'], $value]);
78
                if ($value === 'TaxSubtotal') {
79
                    foreach ($arrayInput['data'][$value] as $value2) { // multiple subt-totals
80
                        $this->setElementsOrdered([
81
                            'commentParentKey' => $key,
82
                            'data'             => $value2,
83
                            'tag'              => $value,
84
                        ]);
85
                    }
86
                } elseif (in_array($value, ['AdditionalCharge', 'AllowanceCharge', 'Item', 'Price'])) {
87
                    $this->setElementsOrdered([
88
                        'commentParentKey' => $key,
89
                        'data'             => $arrayInput['data'][$value],
90
                        'tag'              => $value,
91
                    ]);
92
                } else {
93
                    $matches = []; // scan for special values
94
                    preg_match('/^(EndpointID|.*(Amount|Quantity))$/', $value, $matches, PREG_OFFSET_CAPTURE);
95
                    if ($matches !== []) {
96
                        $this->setSingleElementWithAttribute([
97
                            'commentParentKey' => $arrayInput['commentParentKey'],
98
                            'data'             => $arrayInput['data'][$value],
99
                            'tag'              => $value,
100
                        ]);
101
                    } elseif (is_array($arrayInput['data'][$value])) {
102
                        $this->setElementsOrdered([
103
                            'commentParentKey' => $key,
104
                            'data'             => $arrayInput['data'][$value],
105
                            'tag'              => $value,
106
                        ]);
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 setPaymentMeans(array $arrayData, string $strDocumentTagName): void
145
    {
146
        // multiple accounts can be specified within PaymentMeans
147
        if ($strDocumentTagName === 'Invoice') {
148
            foreach ($arrayData as $value) {
149
                $this->setElementsOrdered([
150
                    'commentParentKey' => 'PaymentMeans',
151
                    'data'             => $value,
152
                    'tag'              => 'PaymentMeans',
153
                ]);
154
            }
155
        }
156
    }
157
158
    private function setSingleComment(array $arrayInput): void
159
    {
160
        if (array_key_exists('commentParentKey', $arrayInput)) {
161
            $this->setElementComment(implode('_', [$arrayInput['commentParentKey'], $arrayInput['tag']]));
162
            if (str_ends_with($arrayInput['tag'], 'Quantity')) {
163
                $this->setElementComment(implode('_', [$arrayInput['commentParentKey'], $arrayInput['tag']
164
                        . 'UnitOfMeasure']));
165
            }
166
        }
167
    }
168
169
    private function setSingleElementWithAttribute(array $arrayInput): void
170
    {
171
        $this->setSingleComment($arrayInput);
172
        if (is_array($arrayInput['data']) && array_key_exists('value', $arrayInput['data'])) {
173
            $this->objXmlWriter->startElement('cbc:' . $arrayInput['tag']);
174
            foreach ($arrayInput['data'] as $key => $value) {
175
                if ($key != 'value') { // if is not value, must be an attribute
176
                    $this->objXmlWriter->writeAttribute($key, $value);
177
                }
178
            }
179
            $this->objXmlWriter->writeRaw($arrayInput['data']['value']);
180
            $this->objXmlWriter->endElement();
181
        } else {
182
            $this->objXmlWriter->writeElement('cbc:' . $arrayInput['tag'], $arrayInput['data']);
183
        }
184
    }
185
186
    public function writeElectronicInvoice(string $strFile, array $arrayDataIn, bool $bolComments): void
187
    {
188
        $this->objXmlWriter = new \XMLWriter();
189
        $this->objXmlWriter->openURI($strFile);
190
        $this->objXmlWriter->setIndent(true);
191
        $this->objXmlWriter->setIndentString(str_repeat(' ', 4));
192
        $this->objXmlWriter->startDocument('1.0', 'UTF-8');
193
        $arrayData = $this->loadSettingsAndManageDefaults($arrayDataIn, $bolComments);
194
        $this->setDocumentTag($arrayDataFinal);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $arrayDataFinal does not exist. Did you maybe mean $arrayData?
Loading history...
195
        $this->setHeaderCommonBasicComponents($arrayData['Header']['CommonBasicComponents-2']);
196
        $arrayAggregates = $arrayData['Header']['CommonAggregateComponents-2'];
197
        foreach (['AccountingSupplierParty', 'AccountingCustomerParty'] as $strCompanyType) {
198
            $this->setElementsOrdered([
199
                'commentParentKey' => $strCompanyType,
200
                'data'             => $arrayAggregates[$strCompanyType]['Party'],
201
                'tag'              => $strCompanyType,
202
            ]);
203
        }
204
        $this->setPaymentMeans($arrayAggregates['PaymentMeans'], $arrayData['DocumentTagName']);
205
        foreach (['TaxTotal', 'LegalMonetaryTotal'] as $strTotal) {
206
            $this->setElementsOrdered([
207
                'commentParentKey' => $strTotal,
208
                'data'             => $arrayAggregates[$strTotal],
209
                'tag'              => $strTotal,
210
            ]);
211
        }
212
        // multiple Lines
213
        foreach ($arrayData['Lines'] as $value) {
214
            $this->setElementsOrdered([
215
                'commentParentKey' => 'Lines',
216
                'data'             => $value,
217
                'tag'              => $arrayData['DocumentTagName'] . 'Line',
218
            ]);
219
        }
220
        $this->objXmlWriter->endElement(); // Invoice or CreditNote
221
        $this->objXmlWriter->flush();
222
    }
223
}
224