Passed
Push — main ( 45a540...bf08fb )
by Daniel
02:14
created

TraitVersions   A

Complexity

Total Complexity 31

Size/Duplication

Total Lines 154
Duplicated Lines 0 %

Importance

Changes 6
Bugs 0 Features 0
Metric Value
eloc 97
dl 0
loc 154
rs 9.92
c 6
b 0
f 0
wmc 31

8 Methods

Rating   Name   Duplication   Size   Complexity  
A establishCurrentVersion() 0 15 4
A getDefaultsIntoDataSet() 0 22 4
A getSettingsFromFileIntoMemory() 0 10 2
A getCommentsFromFileIntoSetting() 0 21 5
A setManageComment() 0 17 3
A loadSettingsAndManageDefaults() 0 14 3
A setNumericValue() 0 16 4
A setCategorizedVerifications() 0 19 6
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
trait TraitVersions
32
{
33
34
    use TraitBasic;
35
36
    private function establishCurrentVersion(array $arrayKnownVersions): array
37
    {
38
        $arrayVersionToReturn = [];
39
        foreach ($arrayKnownVersions as $value) {
40
            $dtValidityStart = new \DateTime($value['Validity']['Start']);
41
            $dtValidityEnd   = new \DateTime($value['Validity']['End']);
42
            $dtValidityNow   = new \DateTime();
43
            if (($dtValidityNow >= $dtValidityStart) && ($dtValidityNow <= $dtValidityEnd)) {
44
                $arrayVersionToReturn = [
45
                    'UBL'     => $value['UBL'],
46
                    'CIUS-RO' => $value['CIUS-RO'],
47
                ];
48
            }
49
        }
50
        return $arrayVersionToReturn;
51
    }
52
53
    private function getDefaultsIntoDataSet(array $arrayDocumentData, bool $bolSchemaLocation): array
54
    {
55
        $arrayVersions = $this->establishCurrentVersion($this->arraySettings['Versions']);
56
        $arrayOutput   = [];
57
        if (!array_key_exists('DocumentNameSpaces', $arrayDocumentData)) {
58
            $arrayOutput = [
59
                'Root'    => [
60
                    'DocumentNameSpaces' => $this->arraySettings['Defaults']['DocumentNameSpaces'],
61
                ],
62
                'UBL'     => $arrayVersions['UBL'],
63
                'CIUS-RO' => $arrayVersions['CIUS-RO'],
64
            ];
65
        }
66
        if ($bolSchemaLocation && !array_key_exists('SchemaLocation', $arrayDocumentData)) {
67
            $arrayOutput['Root']['SchemaLocation'] = vsprintf($this->arraySettings['Defaults']['SchemaLocation'], [
68
                $arrayDocumentData['DocumentTagName'],
69
                $arrayVersions['UBL'],
70
                $arrayDocumentData['DocumentTagName'],
71
                $arrayVersions['UBL'],
72
            ]);
73
        }
74
        return $arrayOutput;
75
    }
76
77
    private function getSettingsFromFileIntoMemory(bool $bolComments): void
78
    {
79
        $this->arraySettings             = $this->getJsonFromFile('json/ElectronicInvoiceSettings.json');
80
        $this->getHierarchyTagOrder();
81
        $this->arraySettings['Comments'] = [
82
            'CAC' => [],
83
            'CBC' => [],
84
        ];
85
        if ($bolComments) {
86
            $this->getCommentsFromFileIntoSetting();
87
        }
88
    }
89
90
    private function getCommentsFromFileIntoSetting(): void
91
    {
92
        $strGlue                = ' | ';
93
        $arrayFlattenedComments = [];
94
        $arrayComments          = $this->getCommentsFromFileAsArray();
95
        foreach ($arrayComments as $key => $value) {
96
            $strComment = implode($strGlue, [
97
                    $key,
98
                    $value['OperationalTerm']['ro_RO'],
99
                    $value['RequirementID'],
100
                ])
101
                . (array_key_exists('SemanticDataType', $value) ? $strGlue . $value['SemanticDataType'] : '');
102
            if (is_array($value['HierarchycalTagName'])) {
103
                foreach ($value['HierarchycalTagName'] as $value2) {
104
                    $arrayFlattenedComments[$value2] = $strComment;
105
                }
106
            } else {
107
                $arrayFlattenedComments[$value['HierarchycalTagName']] = $strComment;
108
            }
109
        }
110
        $this->arraySettings['Comments'] = $arrayFlattenedComments;
111
    }
112
113
    private function loadSettingsAndManageDefaults(array $arrayData, array $arrayFeatures): array
114
    {
115
        // if no DocumentNameSpaces seen take Default ones from local configuration
116
        $this->getSettingsFromFileIntoMemory($arrayFeatures['Comments']);
117
        $arrayDefaults = $this->getDefaultsIntoDataSet($arrayData, $arrayFeatures['SchemaLocation']);
118
        if ($arrayDefaults !== []) {
119
            $arrayData = array_merge($arrayData, $arrayDefaults['Root']);
120
            if (!array_key_exists('CustomizationID', $arrayData['Header']['CommonBasicComponents-2'])) {
121
                $arrayData['Header']['CommonBasicComponents-2']['CustomizationID'] = 'urn:cen.eu:en16931:2017'
122
                    . '#compliant#urn:efactura.mfinante.ro:CIUS-RO:' . $arrayDefaults['CIUS-RO'];
123
                $arrayData['Header']['CommonBasicComponents-2']['UBLVersionID']    = $arrayDefaults['UBL'];
124
            }
125
        }
126
        return $arrayData;
127
    }
128
129
    private function setCategorizedVerifications(array $arrayDataIn)
130
    {
131
        $strCategoryToReturn = '';
132
        $key                 = implode('_', [$arrayDataIn['commentParentKey'], $arrayDataIn['tag']]);
133
        $arrayVarious        = $this->arrayProcessingDetails['WritingCatgoryization'];
134
        if (array_key_exists($key, $arrayVarious['Key'])) {
135
            $strCategoryToReturn = $arrayVarious['Key'][$key];
136
        } elseif (array_key_exists($arrayDataIn['tag'], $arrayVarious['Tag'])) {
137
            $strCategoryToReturn = $arrayVarious['Tag'][$arrayDataIn['tag']];
138
        } elseif (in_array($arrayDataIn['commentParentKey'], $arrayVarious['CommentParrentKey'])) {
139
            $strCategoryToReturn = 'SingleElementWithAttribute';
140
        } elseif ($arrayDataIn['matches'] !== []) {
141
            $strCategoryToReturn = 'SingleElementWithAttribute';
142
        } elseif (is_array($arrayDataIn['data'])) {
143
            $strCategoryToReturn = 'ElementsOrdered';
144
        } else {
145
            $strCategoryToReturn = 'SingleElementWithAttribute';
146
        }
147
        return $strCategoryToReturn;
148
    }
149
150
    private function setManageComment(string $strCommentParentKey, array $arrayIn): string
151
    {
152
        if (str_starts_with($strCommentParentKey, 'AllowanceCharge')) {
153
            $arrayCommentPieces = explode('_', $strCommentParentKey);
154
            // carefully manage a child to decide on comment tag
155
            $strChargeIndicator = $arrayIn['ChargeIndicator'];
156
            if (in_array($strChargeIndicator, ['0', '1'])) {
157
                $strChargeIndicator = [
158
                    '0' => 'false',
159
                    '1' => 'true',
160
                    ][$arrayIn['ChargeIndicator']];
161
            }
162
            array_splice($arrayCommentPieces, 0, 1, 'AllowanceCharge~ChargeIndicator'
163
                . ucfirst($strChargeIndicator));
164
            $strCommentParentKey = implode('_', $arrayCommentPieces);
165
        }
166
        return $strCommentParentKey;
167
    }
168
169
    protected function setNumericValue(string $strTag, array $arrayDataIn): string|float
170
    {
171
        $sReturn      = $arrayDataIn['value'];
172
        $arrayRawTags = ['CreditedQuantity', 'EndpointID', 'InvoicedQuantity', 'ItemClassificationCode', 'PriceAmount'];
173
        if (is_numeric($arrayDataIn['value']) && !in_array($strTag, $arrayRawTags)) {
174
            $fmt = new \NumberFormatter('en_US', \NumberFormatter::DECIMAL);
175
            $fmt->setAttribute(\NumberFormatter::GROUPING_USED, 0);
176
            $fmt->setAttribute(\NumberFormatter::MIN_FRACTION_DIGITS, 0);
177
            // if contains currencyID consider 2 decimals as minimum
178
            if (in_array('currencyID', array_keys($arrayDataIn))) {
179
                $fmt->setAttribute(\NumberFormatter::MIN_FRACTION_DIGITS, 2);
180
            }
181
            $fmt->setAttribute(\NumberFormatter::MAX_FRACTION_DIGITS, 2);
182
            $sReturn = $fmt->format($arrayDataIn['value']);
183
        }
184
        return $sReturn;
185
    }
186
}
187