Passed
Push — main ( fcd80e...779a2b )
by Daniel
02:06
created

ElectornicInvoiceWrite   A

Complexity

Total Complexity 38

Size/Duplication

Total Lines 214
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 134
c 2
b 0
f 0
dl 0
loc 214
rs 9.36
wmc 38

10 Methods

Rating   Name   Duplication   Size   Complexity  
A setSingleComment() 0 7 3
A setHeaderCommonBasicComponents() 0 7 3
A setSingleElementWithAttribute() 0 14 5
B setElementsOrdered() 0 34 7
A setExtraElement() 0 10 4
A setManageComment() 0 9 2
B writeElectronicInvoice() 0 63 5
A loadSettingsAndManageDefaults() 0 14 3
A setMultipleElementsOrdered() 0 8 2
A setDocumentTag() 0 13 4
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
    {
40
        // if no DocumentNameSpaces seen take Default ones from local configuration
41
        $this->getSettingsFromFileIntoMemory($bolComments);
42
        $arrayDefaults = $this->getDefaultsIntoDataSet($arrayData, $bolSchemaLocation);
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'] = 'urn:cen.eu:en16931:2017'
47
                        . '#compliant#urn:efactura.mfinante.ro:CIUS-RO:' . $arrayDefaults['CIUS-RO'];
48
                $arrayData['Header']['CommonBasicComponents-2']['UBLVersionID']    = $arrayDefaults['UBL'];
49
            }
50
        }
51
        return $arrayData;
52
    }
53
54
    private function setDocumentTag(array $arrayDocumentData): void
55
    {
56
        $this->objXmlWriter->startElement($arrayDocumentData['DocumentTagName']);
57
        foreach ($arrayDocumentData['DocumentNameSpaces'] as $key => $value) {
58
            if ($key === '') {
59
                $strValue = sprintf($value, $arrayDocumentData['DocumentTagName']);
60
                $this->objXmlWriter->writeAttributeNS(NULL, 'xmlns', NULL, $strValue);
61
            } else {
62
                $this->objXmlWriter->writeAttributeNS('xmlns', $key, NULL, $value);
63
            }
64
        }
65
        if (array_key_exists('SchemaLocation', $arrayDocumentData)) {
66
            $this->objXmlWriter->writeAttribute('xsi:schemaLocation', $arrayDocumentData['SchemaLocation']);
67
        }
68
    }
69
70
    private function setElementsOrdered(array $arrayInput): void
71
    {
72
        $this->setElementComment($arrayInput['commentParentKey']);
73
        $this->objXmlWriter->startElement('cac:' . $arrayInput['tag']);
74
        $this->setExtraElement($arrayInput, 'Start');
75
        $arrayCustomOrder = $this->arraySettings['CustomOrder'][$arrayInput['commentParentKey']];
76
        foreach ($arrayCustomOrder as $value) { // get the values in expected order
77
            if (array_key_exists($value, $arrayInput['data'])) { // because certain value are optional
78
                $key     = implode('_', [$arrayInput['commentParentKey'], $value]);
79
                $matches = [];
80
                preg_match('/^(EndpointID|.*(Amount|Quantity))$/', $value, $matches, PREG_OFFSET_CAPTURE);
81
                if ($value === 'TaxSubtotal') {
82
                    $this->setMultipleElementsOrdered([
83
                        'commentParentKey' => $key,
84
                        'data'             => $arrayInput['data'][$value],
85
                        'tag'              => $value,
86
                    ]);
87
                } elseif (($matches !== []) || !is_array($arrayInput['data'][$value])) {
88
                    $this->setSingleElementWithAttribute([
89
                        'commentParentKey' => $arrayInput['commentParentKey'],
90
                        'data'             => $arrayInput['data'][$value],
91
                        'tag'              => $value,
92
                    ]);
93
                } elseif (is_array($arrayInput['data'][$value])) {
94
                    $this->setElementsOrdered([
95
                        'commentParentKey' => $key,
96
                        'data'             => $arrayInput['data'][$value],
97
                        'tag'              => $value,
98
                    ]);
99
                }
100
            }
101
        }
102
        $this->setExtraElement($arrayInput, 'End');
103
        $this->objXmlWriter->endElement(); // $key
104
    }
105
106
    private function setExtraElement(array $arrayInput, string $strType): void
107
    {
108
        if (in_array($arrayInput['tag'], ['AccountingCustomerParty', 'AccountingSupplierParty'])) {
109
            switch ($strType) {
110
                case 'End':
111
                    $this->objXmlWriter->endElement();
112
                    break;
113
                case 'Start':
114
                    $this->objXmlWriter->startElement('cac:Party');
115
                    break;
116
            }
117
        }
118
    }
119
120
    private function setHeaderCommonBasicComponents(array $arrayElementWithData): void
121
    {
122
        $arrayCustomOrdered = $this->arraySettings['CustomOrder']['Header_CBC'];
123
        foreach ($arrayCustomOrdered as $value) {
124
            if (array_key_exists($value, $arrayElementWithData)) {
125
                $this->setElementComment($value);
126
                $this->objXmlWriter->writeElement('cbc:' . $value, $arrayElementWithData[$value]);
127
            }
128
        }
129
    }
130
131
    private function setManageComment(string $strCommentParentKey, array $arrayIn): string
132
    {
133
        if (str_starts_with($strCommentParentKey, 'AllowanceCharge')) {
134
            $arrayCommentPieces  = explode('_', $strCommentParentKey);
135
            array_splice($arrayCommentPieces, 0, 1, 'AllowanceCharge~ChargeIndicator'
136
                    . ucfirst($arrayIn['ChargeIndicator'])); // carefully manage a child to decide on comment tag
137
            $strCommentParentKey = implode('_', $arrayCommentPieces);
138
        }
139
        return $strCommentParentKey;
140
    }
141
142
    private function setMultipleElementsOrdered(array $arrayData): void
143
    {
144
        foreach ($arrayData['data'] as $value) {
145
            $strCommentParentKey = $this->setManageComment($arrayData['commentParentKey'], $value);
146
            $this->setElementsOrdered([
147
                'commentParentKey' => $strCommentParentKey,
148
                'data'             => $value,
149
                'tag'              => $arrayData['tag'],
150
            ]);
151
        }
152
    }
153
154
    private function setSingleComment(array $arrayInput): void
155
    {
156
        if (array_key_exists('commentParentKey', $arrayInput)) {
157
            $this->setElementComment(implode('_', [$arrayInput['commentParentKey'], $arrayInput['tag']]));
158
            if (str_ends_with($arrayInput['tag'], 'Quantity')) {
159
                $this->setElementComment(implode('_', [$arrayInput['commentParentKey'], $arrayInput['tag']
160
                    . 'UnitOfMeasure']));
161
            }
162
        }
163
    }
164
165
    private function setSingleElementWithAttribute(array $arrayInput): void
166
    {
167
        $this->setSingleComment($arrayInput);
168
        if (is_array($arrayInput['data']) && array_key_exists('value', $arrayInput['data'])) {
169
            $this->objXmlWriter->startElement('cbc:' . $arrayInput['tag']);
170
            foreach ($arrayInput['data'] as $key => $value) {
171
                if ($key != 'value') { // if is not value, must be an attribute
172
                    $this->objXmlWriter->writeAttribute($key, $value);
173
                }
174
            }
175
            $this->objXmlWriter->writeRaw($arrayInput['data']['value']);
176
            $this->objXmlWriter->endElement();
177
        } else {
178
            $this->objXmlWriter->writeElement('cbc:' . $arrayInput['tag'], $arrayInput['data']);
179
        }
180
    }
181
182
    public function writeElectronicInvoice(string $strFile, array $arrayDataIn, bool $bolComments, bool $bolSchemaLocation = false): void
183
    {
184
        $this->objXmlWriter = new \XMLWriter();
185
        $this->objXmlWriter->openURI($strFile);
186
        $this->objXmlWriter->setIndent(true);
187
        $this->objXmlWriter->setIndentString(str_repeat(' ', 4));
188
        $this->objXmlWriter->startDocument('1.0', 'UTF-8');
189
        $arrayData          = $this->loadSettingsAndManageDefaults($arrayDataIn, $bolComments, $bolSchemaLocation);
190
        $this->setDocumentTag($arrayData);
191
        $this->setHeaderCommonBasicComponents($arrayData['Header']['CommonBasicComponents-2']);
192
        foreach (['InvoicePeriod', 'OrderReference', 'BillingReference', 'DespatchDocumentReference', 'ReceiptDocumentReference', 'OriginatorDocumentReference', 'ContractDocumentReference', 'ProjectReference'] as $strElement) {
193
            $this->setElementsOrdered([
194
                'commentParentKey' => $strElement,
195
                'data'             => $arrayDataIn[$strElement],
196
                'tag'              => $strElement,
197
            ]);
198
        }
199
        $this->setMultipleElementsOrdered([
200
            'commentParentKey' => 'AdditionalDocumentReference',
201
            'data'             => $arrayDataIn['AdditionalDocumentReference'],
202
            'tag'              => 'AdditionalDocumentReference',
203
        ]);
204
        $arrayAggregates = $arrayData['Header']['CommonAggregateComponents-2'];
205
        foreach (['AccountingSupplierParty', 'AccountingCustomerParty'] as $strCompanyType) {
206
            $this->setElementsOrdered([
207
                'commentParentKey' => $strCompanyType,
208
                'data'             => $arrayAggregates[$strCompanyType]['Party'],
209
                'tag'              => $strCompanyType,
210
            ]);
211
        }
212
        foreach (['PayeeParty', 'TaxRepresentativeParty', 'Delivery', 'PaymentTerms'] as $strElement) {
213
            $this->setElementsOrdered([
214
                'commentParentKey' => $strElement,
215
                'data'             => $arrayDataIn[$strElement],
216
                'tag'              => $strElement,
217
            ]);
218
        }
219
        // multiple accounts
220
        $this->setMultipleElementsOrdered([
221
            'commentParentKey' => 'PaymentMeans',
222
            'data'             => $arrayAggregates['PaymentMeans'],
223
            'tag'              => 'PaymentMeans',
224
        ]);
225
        $this->setMultipleElementsOrdered([
226
            'commentParentKey' => 'AllowanceCharge',
227
            'data'             => $arrayAggregates['AllowanceCharge'],
228
            'tag'              => 'AllowanceCharge',
229
        ]);
230
        foreach (['TaxTotal', 'LegalMonetaryTotal'] as $strTotal) {
231
            $this->setElementsOrdered([
232
                'commentParentKey' => $strTotal,
233
                'data'             => $arrayAggregates[$strTotal],
234
                'tag'              => $strTotal,
235
            ]);
236
        }
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