Passed
Push — main ( 85abf7...38ac7b )
by Daniel
02:04
created

ElectornicInvoiceWrite::setElementsOrdered()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 33
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 26
c 1
b 0
f 0
nc 6
nop 1
dl 0
loc 33
rs 8.5706
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, bool $bolSchemaLocation): array {
39
        // if no DocumentNameSpaces seen take Default ones from local configuration
40
        $this->getSettingsFromFileIntoMemory($bolComments);
41
        $arrayDefaults = $this->getDefaultsIntoDataSet($arrayData, $bolSchemaLocation);
42
        if ($arrayDefaults !== []) {
43
            $arrayData = array_merge($arrayData, $arrayDefaults['Root']);
44
            if (!array_key_exists('CustomizationID', $arrayData['Header']['CommonBasicComponents-2'])) {
45
                $arrayData['Header']['CommonBasicComponents-2']['CustomizationID'] = 'urn:cen.eu:en16931:2017'
46
                    . '#compliant#urn:efactura.mfinante.ro:CIUS-RO:' . $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
        $this->objXmlWriter->startElement($arrayDocumentData['DocumentTagName']);
55
        foreach ($arrayDocumentData['DocumentNameSpaces'] as $key => $value) {
56
            if ($key === '') {
57
                $strValue = sprintf($value, $arrayDocumentData['DocumentTagName']);
58
                $this->objXmlWriter->writeAttributeNS(NULL, 'xmlns', NULL, $strValue);
59
            } else {
60
                $this->objXmlWriter->writeAttributeNS('xmlns', $key, NULL, $value);
61
            }
62
        }
63
        if (array_key_exists('SchemaLocation', $arrayDocumentData)) {
64
            $this->objXmlWriter->writeAttribute('xsi:schemaLocation', $arrayDocumentData['SchemaLocation']);
65
        }
66
    }
67
68
    private function setElementsOrdered(array $arrayInput): void {
69
        $this->setElementComment($arrayInput['commentParentKey']);
70
        $this->objXmlWriter->startElement('cac:' . $arrayInput['tag']);
71
        $this->setExtraElement($arrayInput, 'Start');
72
        $arrayCustomOrder = $this->arraySettings['CustomOrder'][$arrayInput['commentParentKey']];
73
        foreach ($arrayCustomOrder as $value) { // get the values in expected order
74
            if (array_key_exists($value, $arrayInput['data'])) { // because certain value are optional
75
                $key     = implode('_', [$arrayInput['commentParentKey'], $value]);
76
                $matches = [];
77
                preg_match('/^(EndpointID|.*(Amount|Quantity))$/', $value, $matches, PREG_OFFSET_CAPTURE);
78
                if ($value === 'TaxSubtotal') {
79
                    $this->setMultipleElementsOrdered([
80
                        'commentParentKey' => $key,
81
                        'data'             => $arrayInput['data'][$value],
82
                        'tag'              => $value,
83
                    ]);
84
                } elseif (($matches !== []) || !is_array($arrayInput['data'][$value])) {
85
                    $this->setSingleElementWithAttribute([
86
                        'commentParentKey' => $arrayInput['commentParentKey'],
87
                        'data'             => $arrayInput['data'][$value],
88
                        'tag'              => $value,
89
                    ]);
90
                } elseif (is_array($arrayInput['data'][$value])) {
91
                    $this->setElementsOrdered([
92
                        'commentParentKey' => $key,
93
                        'data'             => $arrayInput['data'][$value],
94
                        'tag'              => $value,
95
                    ]);
96
                }
97
            }
98
        }
99
        $this->setExtraElement($arrayInput, 'End');
100
        $this->objXmlWriter->endElement(); // $key
101
    }
102
103
    private function setExtraElement(array $arrayInput, string $strType): void {
104
        if (in_array($arrayInput['tag'], ['AccountingCustomerParty', 'AccountingSupplierParty'])) {
105
            switch ($strType) {
106
                case 'End':
107
                    $this->objXmlWriter->endElement();
108
                    break;
109
                case 'Start':
110
                    $this->objXmlWriter->startElement('cac:Party');
111
                    break;
112
            }
113
        }
114
    }
115
116
    private function setHeaderCommonBasicComponents(array $arrayElementWithData): void {
117
        $arrayCustomOrdered = $this->arraySettings['CustomOrder']['Header_CBC'];
118
        foreach ($arrayCustomOrdered as $value) {
119
            if (array_key_exists($value, $arrayElementWithData)) {
120
                $this->setElementComment($value);
121
                $this->objXmlWriter->writeElement('cbc:' . $value, $arrayElementWithData[$value]);
122
            }
123
        }
124
    }
125
126
    private function setMultipleElementsOrdered(array $arrayData): void {
127
        foreach ($arrayData['data'] as $value) {
128
            $this->setElementsOrdered([
129
                'commentParentKey' => $arrayData['commentParentKey'],
130
                'data'             => $value,
131
                'tag'              => $arrayData['tag'],
132
            ]);
133
        }
134
    }
135
136
    private function setSingleComment(array $arrayInput): void {
137
        if (array_key_exists('commentParentKey', $arrayInput)) {
138
            $this->setElementComment(implode('_', [$arrayInput['commentParentKey'], $arrayInput['tag']]));
139
            if (str_ends_with($arrayInput['tag'], 'Quantity')) {
140
                $this->setElementComment(implode('_', [$arrayInput['commentParentKey'], $arrayInput['tag']
141
                    . 'UnitOfMeasure']));
142
            }
143
        }
144
    }
145
146
    private function setSingleElementWithAttribute(array $arrayInput): void {
147
        $this->setSingleComment($arrayInput);
148
        if (is_array($arrayInput['data']) && array_key_exists('value', $arrayInput['data'])) {
149
            $this->objXmlWriter->startElement('cbc:' . $arrayInput['tag']);
150
            foreach ($arrayInput['data'] as $key => $value) {
151
                if ($key != 'value') { // if is not value, must be an attribute
152
                    $this->objXmlWriter->writeAttribute($key, $value);
153
                }
154
            }
155
            $this->objXmlWriter->writeRaw($arrayInput['data']['value']);
156
            $this->objXmlWriter->endElement();
157
        } else {
158
            $this->objXmlWriter->writeElement('cbc:' . $arrayInput['tag'], $arrayInput['data']);
159
        }
160
    }
161
162
    public function writeElectronicInvoice(string $strFile, array $arrayDataIn, bool $bolComments, bool $bolSchemaLocation = false): void {
163
        $this->objXmlWriter = new \XMLWriter();
164
        $this->objXmlWriter->openURI($strFile);
165
        $this->objXmlWriter->setIndent(true);
166
        $this->objXmlWriter->setIndentString(str_repeat(' ', 4));
167
        $this->objXmlWriter->startDocument('1.0', 'UTF-8');
168
        $arrayData          = $this->loadSettingsAndManageDefaults($arrayDataIn, $bolComments, $bolSchemaLocation);
169
        $this->setDocumentTag($arrayData);
170
        $this->setHeaderCommonBasicComponents($arrayData['Header']['CommonBasicComponents-2']);
171
        $arrayAggregates    = $arrayData['Header']['CommonAggregateComponents-2'];
172
        foreach (['AccountingSupplierParty', 'AccountingCustomerParty'] as $strCompanyType) {
173
            $this->setElementsOrdered([
174
                'commentParentKey' => $strCompanyType,
175
                'data'             => $arrayAggregates[$strCompanyType]['Party'],
176
                'tag'              => $strCompanyType,
177
            ]);
178
        }
179
        // multiple accounts
180
        $this->setMultipleElementsOrdered([
181
            'commentParentKey' => 'PaymentMeans',
182
            'data'             => $arrayAggregates['PaymentMeans'],
183
            'tag'              => 'PaymentMeans',
184
        ]);
185
        foreach (['TaxTotal', 'LegalMonetaryTotal'] as $strTotal) {
186
            $this->setElementsOrdered([
187
                'commentParentKey' => $strTotal,
188
                'data'             => $arrayAggregates[$strTotal],
189
                'tag'              => $strTotal,
190
            ]);
191
        }
192
        // multiple Lines
193
        $this->setMultipleElementsOrdered([
194
            'commentParentKey' => 'Lines',
195
            'data'             => $arrayData['Lines'],
196
            'tag'              => $arrayData['DocumentTagName'] . 'Line',
197
        ]);
198
        $this->objXmlWriter->endElement(); // Invoice or CreditNote
199
        $this->objXmlWriter->flush();
200
    }
201
}
202