Passed
Push — main ( 34ca28...996ebb )
by Daniel
02:20
created

ElectornicInvoiceWrite::setSingleComment()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 5
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 7
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, 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, ['AdditionalItemProperty', 'CommodityClassification', 'StandardItemIdentification', 'TaxSubtotal'])) {
96
                    $this->setMultipleElementsOrdered([
97
                        'commentParentKey' => $key,
98
                        'data'             => $arrayInput['data'][$value],
99
                        'tag'              => $value,
100
                    ]);
101
                } elseif (($matches !== []) || !is_array($arrayInput['data'][$value]) || in_array($arrayInput['commentParentKey'], ['AccountingCustomerParty_PartyIdentification', 'AccountingSupplierParty_PartyIdentification', 'Lines_Item_SellersItemIdentification', 'Lines_Item_StandardItemIdentification', 'Lines_Item_CommodityClassification'])) {
102
                    $this->setSingleElementWithAttribute([
103
                        'commentParentKey' => $arrayInput['commentParentKey'],
104
                        'data'             => $arrayInput['data'][$value],
105
                        'tag'              => $value,
106
                    ]);
107
                } elseif (is_array($arrayInput['data'][$value])) {
108
                    $this->setElementsOrdered([
109
                        'commentParentKey' => $key,
110
                        'data'             => $arrayInput['data'][$value],
111
                        'tag'              => $value,
112
                    ]);
113
                }
114
            }
115
        }
116
        $this->setExtraElement($arrayInput, 'End');
117
        $this->objXmlWriter->endElement(); // $key
118
    }
119
120
    private function setExtraElement(array $arrayInput, string $strType): void
121
    {
122
        if (in_array($arrayInput['tag'], ['AccountingCustomerParty', 'AccountingSupplierParty'])) {
123
            switch ($strType) {
124
                case 'End':
125
                    $this->objXmlWriter->endElement();
126
                    break;
127
                case 'Start':
128
                    $this->objXmlWriter->startElement('cac:Party');
129
                    break;
130
            }
131
        }
132
    }
133
134
    private function setHeaderCommonBasicComponents(array $arrayElementWithData): void
135
    {
136
        $arrayCustomOrdered = $this->arraySettings['CustomOrder']['Header_CBC'];
137
        foreach ($arrayCustomOrdered as $value) {
138
            if (array_key_exists($value, $arrayElementWithData)) {
139
                $this->setElementComment($value);
140
                $this->objXmlWriter->writeElement('cbc:' . $value, $arrayElementWithData[$value]);
141
            }
142
        }
143
    }
144
145
    private function setManageComment(string $strCommentParentKey, array $arrayIn): string
146
    {
147
        if (str_starts_with($strCommentParentKey, 'AllowanceCharge')) {
148
            $arrayCommentPieces  = explode('_', $strCommentParentKey);
149
            array_splice($arrayCommentPieces, 0, 1, 'AllowanceCharge~ChargeIndicator'
150
                . ucfirst($arrayIn['ChargeIndicator'])); // carefully manage a child to decide on comment tag
151
            $strCommentParentKey = implode('_', $arrayCommentPieces);
152
        }
153
        return $strCommentParentKey;
154
    }
155
156
    private function setMultipleElementsOrdered(array $arrayData): void
157
    {
158
        foreach ($arrayData['data'] as $value) {
159
            $strCommentParentKey = $this->setManageComment($arrayData['commentParentKey'], $value);
160
            $this->setElementsOrdered([
161
                'commentParentKey' => $strCommentParentKey,
162
                'data'             => $value,
163
                'tag'              => $arrayData['tag'],
164
            ]);
165
        }
166
    }
167
168
    private function setPrepareXml(string $strFile): void
169
    {
170
        $this->objXmlWriter = new \XMLWriter();
171
        $this->objXmlWriter->openURI($strFile);
172
        $this->objXmlWriter->setIndent(true);
173
        $this->objXmlWriter->setIndentString(str_repeat(' ', 4));
174
        $this->objXmlWriter->startDocument('1.0', 'UTF-8');
175
    }
176
177
    private function setProduceMiddleXml(array $arrayData): void
178
    {
179
        $arrayAggregates             = $arrayData['Header']['CommonAggregateComponents-2'];
180
        $arrayOptionalElementsHeader = [
181
            'InvoicePeriod'               => 'Single',
182
            'OrderReference'              => 'Single',
183
            'BillingReference'            => 'Single',
184
            'DespatchDocumentReference'   => 'Single',
185
            'ReceiptDocumentReference'    => 'Single',
186
            'OriginatorDocumentReference' => 'Single',
187
            'ContractDocumentReference'   => 'Single',
188
            'ProjectReference'            => 'Single',
189
            'AdditionalDocumentReference' => 'Multiple',
190
            'AccountingSupplierParty'     => 'SingleCompany',
191
            'AccountingCustomerParty'     => 'SingleCompany',
192
            'PayeeParty'                  => 'Single',
193
            'TaxRepresentativeParty'      => 'Single',
194
            'Delivery'                    => 'Single',
195
            'PaymentMeans'                => 'Multiple',
196
            'PaymentTerms'                => 'Single',
197
            'AllowanceCharge'             => 'Multiple',
198
            'TaxTotal'                    => 'Single',
199
            'LegalMonetaryTotal'          => 'Single',
200
        ];
201
        foreach ($arrayOptionalElementsHeader as $key => $strLogicType) {
202
            if (array_key_exists($key, $arrayAggregates)) {
203
                switch ($strLogicType) {
204
                    case 'Multiple':
205
                        $this->setMultipleElementsOrdered([
206
                            'commentParentKey' => $key,
207
                            'data'             => $arrayAggregates[$key],
208
                            'tag'              => $key,
209
                        ]);
210
                        break;
211
                    case 'Single':
212
                        $this->setElementsOrdered([
213
                            'commentParentKey' => $key,
214
                            'data'             => $arrayAggregates[$key],
215
                            'tag'              => $key,
216
                        ]);
217
                        break;
218
                    case 'SingleCompany':
219
                        $this->setElementsOrdered([
220
                            'commentParentKey' => $key,
221
                            'data'             => $arrayAggregates[$key]['Party'],
222
                            'tag'              => $key,
223
                        ]);
224
                        break;
225
                }
226
            }
227
        }
228
    }
229
230
    private function setSingleComment(array $arrayInput): void
231
    {
232
        if (array_key_exists('commentParentKey', $arrayInput)) {
233
            $this->setElementComment(implode('_', [$arrayInput['commentParentKey'], $arrayInput['tag']]));
234
            if (str_ends_with($arrayInput['tag'], 'Quantity')) {
235
                $this->setElementComment(implode('_', [$arrayInput['commentParentKey'], $arrayInput['tag']
236
                    . 'UnitOfMeasure']));
237
            }
238
        }
239
    }
240
241
    private function setSingleElementWithAttribute(array $arrayInput): void
242
    {
243
        $this->setSingleComment($arrayInput);
244
        if (is_array($arrayInput['data']) && array_key_exists('value', $arrayInput['data'])) {
245
            $this->objXmlWriter->startElement('cbc:' . $arrayInput['tag']);
246
            $fmt = new \NumberFormatter('en_US', \NumberFormatter::DECIMAL);
247
            $fmt->setAttribute(\NumberFormatter::GROUPING_USED, 0);
248
            $fmt->setAttribute(\NumberFormatter::MIN_FRACTION_DIGITS, 0);
249
            $fmt->setAttribute(\NumberFormatter::MAX_FRACTION_DIGITS, 2);
250
            foreach ($arrayInput['data'] as $key => $value) {
251
                if ($key !== 'value') { // if is not value, must be an attribute
252
                    $this->objXmlWriter->writeAttribute($key, $value);
253
                }
254
                if ($key === 'currencyID') {
255
                    $fmt->setAttribute(\NumberFormatter::MIN_FRACTION_DIGITS, 2);
256
                }
257
            }
258
            if ($arrayInput['tag'] === 'PriceAmount') {
259
                $this->objXmlWriter->writeRaw($arrayInput['data']['value']);
260
            } else {
261
                $this->objXmlWriter->writeRaw($fmt->format($arrayInput['data']['value']));
262
            }
263
            $this->objXmlWriter->endElement();
264
        } else {
265
            $this->objXmlWriter->writeElement('cbc:' . $arrayInput['tag'], $arrayInput['data']);
266
        }
267
    }
268
269
    public function writeElectronicInvoice(string $strFile, array $inData, bool $bolCmnts, bool $bolScLc = false): void
270
    {
271
        $arrayData = $this->loadSettingsAndManageDefaults($inData, $bolCmnts, $bolScLc);
272
        $this->setPrepareXml($strFile);
273
        $this->setDocumentTag($arrayData);
274
        $this->setHeaderCommonBasicComponents($arrayData['Header']['CommonBasicComponents-2']);
275
        $this->setProduceMiddleXml($arrayData);
276
        // multiple Lines
277
        $this->setMultipleElementsOrdered([
278
            'commentParentKey' => 'Lines',
279
            'data'             => $arrayData['Lines'],
280
            'tag'              => $arrayData['DocumentTagName'] . 'Line',
281
        ]);
282
        $this->objXmlWriter->endElement(); // Invoice or CreditNote
283
        $this->objXmlWriter->flush();
284
    }
285
}
286