Passed
Push — main ( d54aa7...985c98 )
by Daniel
02:04
created

setHeaderCommonBasicComponents()   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 $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 setPrepareXml(string $strFile): void
155
    {
156
        $this->objXmlWriter = new \XMLWriter();
157
        $this->objXmlWriter->openURI($strFile);
158
        $this->objXmlWriter->setIndent(true);
159
        $this->objXmlWriter->setIndentString(str_repeat(' ', 4));
160
        $this->objXmlWriter->startDocument('1.0', 'UTF-8');
161
    }
162
163
    private function setProduceMiddleXml(array $arrayData): void
164
    {
165
        $arrayAggregates             = $arrayData['Header']['CommonAggregateComponents-2'];
166
        $arrayOptionalElementsHeader = [
167
            'InvoicePeriod'               => 'Single',
168
            'OrderReference'              => 'Single',
169
            'BillingReference'            => 'Single',
170
            'DespatchDocumentReference'   => 'Single',
171
            'ReceiptDocumentReference'    => 'Single',
172
            'OriginatorDocumentReference' => 'Single',
173
            'ContractDocumentReference'   => 'Single',
174
            'ProjectReference'            => 'Single',
175
            'AdditionalDocumentReference' => 'Multiple',
176
            'AccountingSupplierParty'     => 'SingleCompany',
177
            'AccountingCustomerParty'     => 'SingleCompany',
178
            'PayeeParty'                  => 'Single',
179
            'TaxRepresentativeParty'      => 'Single',
180
            'Delivery'                    => 'Single',
181
            'PaymentTerms'                => 'Single',
182
            'PaymentMeans'                => 'Multiple',
183
            'AllowanceCharge'             => 'Multiple',
184
            'TaxTotal'                    => 'Single',
185
            'LegalMonetaryTotal'          => 'Single',
186
        ];
187
        foreach ($arrayOptionalElementsHeader as $key => $strLogicType) {
188
            if (array_key_exists($key, $arrayAggregates)) {
189
                switch ($strLogicType) {
190
                    case 'Multiple':
191
                        $this->setMultipleElementsOrdered([
192
                            'commentParentKey' => $key,
193
                            'data'             => $arrayAggregates[$key],
194
                            'tag'              => $key,
195
                        ]);
196
                        break;
197
                    case 'Single':
198
                        $this->setElementsOrdered([
199
                            'commentParentKey' => $key,
200
                            'data'             => $arrayAggregates[$key],
201
                            'tag'              => $key,
202
                        ]);
203
                        break;
204
                    case 'SingleCompany':
205
                        $this->setElementsOrdered([
206
                            'commentParentKey' => $key,
207
                            'data'             => $arrayAggregates[$key]['Party'],
208
                            'tag'              => $key,
209
                        ]);
210
                        break;
211
                }
212
            }
213
        }
214
    }
215
216
    private function setSingleComment(array $arrayInput): void
217
    {
218
        if (array_key_exists('commentParentKey', $arrayInput)) {
219
            $this->setElementComment(implode('_', [$arrayInput['commentParentKey'], $arrayInput['tag']]));
220
            if (str_ends_with($arrayInput['tag'], 'Quantity')) {
221
                $this->setElementComment(implode('_', [$arrayInput['commentParentKey'], $arrayInput['tag']
222
                    . 'UnitOfMeasure']));
223
            }
224
        }
225
    }
226
227
    private function setSingleElementWithAttribute(array $arrayInput): void
228
    {
229
        $this->setSingleComment($arrayInput);
230
        if (is_array($arrayInput['data']) && array_key_exists('value', $arrayInput['data'])) {
231
            $this->objXmlWriter->startElement('cbc:' . $arrayInput['tag']);
232
            foreach ($arrayInput['data'] as $key => $value) {
233
                if ($key != 'value') { // if is not value, must be an attribute
234
                    $this->objXmlWriter->writeAttribute($key, $value);
235
                }
236
            }
237
            $this->objXmlWriter->writeRaw($arrayInput['data']['value']);
238
            $this->objXmlWriter->endElement();
239
        } else {
240
            $this->objXmlWriter->writeElement('cbc:' . $arrayInput['tag'], $arrayInput['data']);
241
        }
242
    }
243
244
    public function writeElectronicInvoice(string $strFile, array $arrayDataIn, bool $bolComments, bool $bolSchemaLocation = false): void
245
    {
246
        $arrayData = $this->loadSettingsAndManageDefaults($arrayDataIn, $bolComments, $bolSchemaLocation);
247
        $this->setPrepareXml($strFile);
248
        $this->setDocumentTag($arrayData);
249
        $this->setHeaderCommonBasicComponents($arrayData['Header']['CommonBasicComponents-2']);
250
        $this->setProduceMiddleXml($arrayData);
251
        // multiple Lines
252
        $this->setMultipleElementsOrdered([
253
            'commentParentKey' => 'Lines',
254
            'data'             => $arrayData['Lines'],
255
            'tag'              => $arrayData['DocumentTagName'] . 'Line',
256
        ]);
257
        $this->objXmlWriter->endElement(); // Invoice or CreditNote
258
        $this->objXmlWriter->flush();
259
    }
260
}
261