Test Failed
Push — main ( 2ad17d...7bbdc7 )
by Daniel
02:34
created

ElectornicInvoiceWrite::setNumericValue()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 11
c 0
b 0
f 0
nc 3
nop 2
dl 0
loc 16
rs 9.9
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;
35
36
    protected \XMLWriter $objXmlWriter;
37
38
    private function loadSettingsAndManageDefaults(array $arrayData, bool $bolComments, bool $bolSchemaLctn): array
39
    {
40
        // if no DocumentNameSpaces seen take Default ones from local configuration
41
        $this->getSettingsFromFileIntoMemory($bolComments);
42
        $arrayDefaults = $this->getDefaultsIntoDataSet($arrayData, $bolSchemaLctn);
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 setElementComment(string $strKey): void
71
    {
72
        if (array_key_exists($strKey, $this->arraySettings['Comments'])) {
73
            $elementComment = $this->arraySettings['Comments'][$strKey];
74
            if (is_array($elementComment)) {
75
                foreach ($elementComment as $value) {
76
                    $this->objXmlWriter->writeComment($value);
77
                }
78
            } else {
79
                $this->objXmlWriter->writeComment($elementComment);
80
            }
81
        }
82
    }
83
84
    private function setElementsOrdered(array $arrayInput): void
85
    {
86
        $this->setElementComment($arrayInput['commentParentKey']);
87
        $this->objXmlWriter->startElement('cac:' . $arrayInput['tag']);
88
        $this->setExtraElement($arrayInput, 'Start');
89
        $arrayCustomOrder = $this->arraySettings['CustomOrder'][$arrayInput['commentParentKey']];
90
        foreach ($arrayCustomOrder as $value) { // get the values in expected order
91
            if (array_key_exists($value, $arrayInput['data'])) { // because certain value are optional
92
                $key     = implode('_', [$arrayInput['commentParentKey'], $value]);
93
                $matches = [];
94
                preg_match('/^.*(Amount|Quantity)$/', $value, $matches, PREG_OFFSET_CAPTURE);
95
                if (in_array($value, ['EmbeddedDocumentBinaryObject', 'EndpointID'])) {
96
                    $this->setSingleElementWithAttribute([
97
                        'commentParentKey' => $arrayInput['commentParentKey'],
98
                        'data'             => $arrayInput['data'][$value],
99
                        'tag'              => $value,
100
                    ]);
101
                } elseif (in_array($value, ['AdditionalItemProperty', 'CommodityClassification', 'PartyTaxScheme', 'StandardItemIdentification', 'TaxSubtotal'])) {
102
                    $this->setMultipleElementsOrdered([
103
                        'commentParentKey' => $key,
104
                        'data'             => $arrayInput['data'][$value],
105
                        'tag'              => $value,
106
                    ]);
107
                } elseif (($matches !== []) || !is_array($arrayInput['data'][$value]) || in_array($arrayInput['commentParentKey'], ['AccountingCustomerParty_PartyIdentification', 'AccountingSupplierParty_PartyIdentification', 'Lines_Item_SellersItemIdentification', 'Lines_Item_StandardItemIdentification', 'Lines_Item_CommodityClassification'])) {
108
                    $this->setSingleElementWithAttribute([
109
                        'commentParentKey' => $arrayInput['commentParentKey'],
110
                        'data'             => $arrayInput['data'][$value],
111
                        'tag'              => $value,
112
                    ]);
113
                } elseif (is_array($arrayInput['data'][$value])) {
114
                    $this->setElementsOrdered([
115
                        'commentParentKey' => $key,
116
                        'data'             => $arrayInput['data'][$value],
117
                        'tag'              => $value,
118
                    ]);
119
                }
120
            }
121
        }
122
        $this->setExtraElement($arrayInput, 'End');
123
        $this->objXmlWriter->endElement(); // $key
124
    }
125
126
    private function setExtraElement(array $arrayInput, string $strType): void
127
    {
128
        if (in_array($arrayInput['tag'], ['AccountingCustomerParty', 'AccountingSupplierParty'])) {
129
            switch ($strType) {
130
                case 'End':
131
                    $this->objXmlWriter->endElement();
132
                    break;
133
                case 'Start':
134
                    $this->objXmlWriter->startElement('cac:Party');
135
                    break;
136
            }
137
        }
138
    }
139
140
    private function setHeaderCommonBasicComponents(array $arrayElementWithData): void
141
    {
142
        $arrayCustomOrdered = $this->arraySettings['CustomOrder']['Header_CBC'];
143
        foreach ($arrayCustomOrdered as $value) {
144
            if (array_key_exists($value, $arrayElementWithData)) {
145
                $this->setElementComment($value);
146
                $this->objXmlWriter->writeElement('cbc:' . $value, $arrayElementWithData[$value]);
147
            }
148
        }
149
    }
150
151
    private function setManageComment(string $strCommentParentKey, array $arrayIn): string
152
    {
153
        if (str_starts_with($strCommentParentKey, 'AllowanceCharge')) {
154
            $arrayCommentPieces  = explode('_', $strCommentParentKey);
155
            array_splice($arrayCommentPieces, 0, 1, 'AllowanceCharge~ChargeIndicator'
156
                . ucfirst($arrayIn['ChargeIndicator'])); // carefully manage a child to decide on comment tag
157
            $strCommentParentKey = implode('_', $arrayCommentPieces);
158
        }
159
        return $strCommentParentKey;
160
    }
161
162
    private function setMultipleElementsOrdered(array $arrayData): void
163
    {
164
        foreach ($arrayData['data'] as $value) {
165
            $strCommentParentKey = $this->setManageComment($arrayData['commentParentKey'], $value);
166
            $this->setElementsOrdered([
167
                'commentParentKey' => $strCommentParentKey,
168
                'data'             => $value,
169
                'tag'              => $arrayData['tag'],
170
            ]);
171
        }
172
    }
173
174
    protected function setNumericValue(string $strTag, array $arrayDataIn): string|float
175
    {
176
        $sReturn      = $arrayDataIn['value'];
177
        $arrayRawTags = ['CreditedQuantity', 'EndpointID', 'InvoicedQuantity', 'PriceAmount'];
178
        if (is_numeric($arrayDataIn['value']) && !in_array($strTag, $arrayRawTags)) {
179
            $fmt = new \NumberFormatter('en_US', \NumberFormatter::DECIMAL);
180
            $fmt->setAttribute(\NumberFormatter::GROUPING_USED, 0);
181
            $fmt->setAttribute(\NumberFormatter::MIN_FRACTION_DIGITS, 0);
182
            // if contains currencyID consider 2 decimals as minimum
183
            if (in_array('currencyID', array_keys($arrayDataIn))) {
184
                $fmt->setAttribute(\NumberFormatter::MIN_FRACTION_DIGITS, 2);
185
            }
186
            $fmt->setAttribute(\NumberFormatter::MAX_FRACTION_DIGITS, 2);
187
            $sReturn = $fmt->format($arrayDataIn['value']);
188
        }
189
        return $sReturn;
190
    }
191
192
    private function setPrepareXml(string $strFile): void
193
    {
194
        $this->objXmlWriter = new \XMLWriter();
195
        $this->objXmlWriter->openURI($strFile);
196
        $this->objXmlWriter->setIndent(true);
197
        $this->objXmlWriter->setIndentString(str_repeat(' ', 4));
198
        $this->objXmlWriter->startDocument('1.0', 'UTF-8');
199
    }
200
201
    private function setProduceMiddleXml(array $arrayData): void
202
    {
203
        $arrayAggregates             = $arrayData['Header']['CommonAggregateComponents-2'];
204
        $arrayOptionalElementsHeader = [
205
            'InvoicePeriod'               => 'Single',
206
            'OrderReference'              => 'Single',
207
            'BillingReference'            => 'Single',
208
            'DespatchDocumentReference'   => 'Single',
209
            'ReceiptDocumentReference'    => 'Single',
210
            'OriginatorDocumentReference' => 'Single',
211
            'ContractDocumentReference'   => 'Single',
212
            'AdditionalDocumentReference' => 'Multiple',
213
            'ProjectReference'            => 'Single',
214
            'AccountingSupplierParty'     => 'SingleCompany',
215
            'AccountingCustomerParty'     => 'SingleCompany',
216
            'PayeeParty'                  => 'Single',
217
            'TaxRepresentativeParty'      => 'Single',
218
            'Delivery'                    => 'Single',
219
            'PaymentMeans'                => 'Multiple',
220
            'PaymentTerms'                => 'Single',
221
            'DocumentReference'           => 'Single',
222
            'AllowanceCharge'             => 'Multiple',
223
            'TaxTotal'                    => 'Multiple',
224
            'LegalMonetaryTotal'          => 'Single',
225
        ];
226
        foreach ($arrayOptionalElementsHeader as $key => $strLogicType) {
227
            if (array_key_exists($key, $arrayAggregates)) {
228
                switch ($strLogicType) {
229
                    case 'Multiple':
230
                        $this->setMultipleElementsOrdered([
231
                            'commentParentKey' => $key,
232
                            'data'             => $arrayAggregates[$key],
233
                            'tag'              => $key,
234
                        ]);
235
                        break;
236
                    case 'Single':
237
                        $this->setElementsOrdered([
238
                            'commentParentKey' => $key,
239
                            'data'             => $arrayAggregates[$key],
240
                            'tag'              => $key,
241
                        ]);
242
                        break;
243
                    case 'SingleCompany':
244
                        $this->setElementsOrdered([
245
                            'commentParentKey' => $key,
246
                            'data'             => $arrayAggregates[$key]['Party'],
247
                            'tag'              => $key,
248
                        ]);
249
                        break;
250
                }
251
            }
252
        }
253
    }
254
255
    private function setSingleComment(array $arrayInput): void
256
    {
257
        if (array_key_exists('commentParentKey', $arrayInput)) {
258
            $this->setElementComment(implode('_', [$arrayInput['commentParentKey'], $arrayInput['tag']]));
259
            if (str_ends_with($arrayInput['tag'], 'Quantity')) {
260
                $this->setElementComment(implode('_', [$arrayInput['commentParentKey'], $arrayInput['tag']
261
                    . 'UnitOfMeasure']));
262
            }
263
        }
264
    }
265
266
    private function setSingleElementWithAttribute(array $arrayInput): void
267
    {
268
        $this->setSingleComment($arrayInput);
269
        if (is_array($arrayInput['data']) && array_key_exists('value', $arrayInput['data'])) {
270
            $this->objXmlWriter->startElement('cbc:' . $arrayInput['tag']);
271
            foreach ($arrayInput['data'] as $key => $value) {
272
                if ($key !== 'value') { // if is not value, must be an attribute
273
                    $this->objXmlWriter->writeAttribute($key, $value);
274
                }
275
            }
276
            $this->objXmlWriter->writeRaw($this->setNumericValue($arrayInput['tag'], $arrayInput['data']));
277
            $this->objXmlWriter->endElement();
278
        } else {
279
            $this->objXmlWriter->writeElement('cbc:' . $arrayInput['tag'], $arrayInput['data']);
280
        }
281
    }
282
283
    public function writeElectronicInvoice(string $strFile, array $inData, bool $bolCmnts, bool $bolScLc = false): void
284
    {
285
        $arrayData = $this->loadSettingsAndManageDefaults($inData, $bolCmnts, $bolScLc);
286
        $this->setPrepareXml($strFile);
287
        $this->setDocumentTag($arrayData);
288
        $this->setHeaderCommonBasicComponents($arrayData['Header']['CommonBasicComponents-2']);
289
        $this->setProduceMiddleXml($arrayData);
290
        // multiple Lines
291
        $this->setMultipleElementsOrdered([
292
            'commentParentKey' => 'Lines',
293
            'data'             => $arrayData['Lines'],
294
            'tag'              => $arrayData['DocumentTagName'] . 'Line',
295
        ]);
296
        $this->objXmlWriter->endElement(); // Invoice or CreditNote
297
        $this->objXmlWriter->flush();
298
    }
299
}
300