Passed
Pull Request — master (#427)
by
unknown
03:22
created

Toolkit::serialize()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * PAYONE Magento 2 Connector is free software: you can redistribute it and/or modify
5
 * it under the terms of the GNU Lesser General Public License as published by
6
 * the Free Software Foundation, either version 3 of the License, or
7
 * (at your option) any later version.
8
 *
9
 * PAYONE Magento 2 Connector is distributed in the hope that it will be useful,
10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
 * GNU Lesser General Public License for more details.
13
 *
14
 * You should have received a copy of the GNU Lesser General Public License
15
 * along with PAYONE Magento 2 Connector. If not, see <http://www.gnu.org/licenses/>.
16
 *
17
 * PHP version 5
18
 *
19
 * @category  Payone
20
 * @package   Payone_Magento2_Plugin
21
 * @author    FATCHIP GmbH <[email protected]>
22
 * @copyright 2003 - 2016 Payone GmbH
23
 * @license   <http://www.gnu.org/licenses/> GNU Lesser General Public License
24
 * @link      http://www.payone.de
25
 */
26
27
namespace Payone\Core\Helper;
28
29
use Magento\Framework\DataObject;
0 ignored issues
show
Bug introduced by
The type Magento\Framework\DataObject was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
30
use Magento\Sales\Model\Order as SalesOrder;
0 ignored issues
show
Bug introduced by
The type Magento\Sales\Model\Order was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
31
use Magento\Store\Model\Store;
0 ignored issues
show
Bug introduced by
The type Magento\Store\Model\Store was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
32
use Payone\Core\Model\Methods\PayoneMethod;
33
use Magento\Framework\Exception\LocalizedException;
0 ignored issues
show
Bug introduced by
The type Magento\Framework\Exception\LocalizedException was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
34
35
/**
36
 * Toolkit class for methods that dont fit in a certain drawer
37
 */
38
class Toolkit extends \Payone\Core\Helper\Base
39
{
40
    /**
41
     * @var \Magento\Framework\Serialize\Serializer\Serialize
0 ignored issues
show
Bug introduced by
The type Magento\Framework\Serialize\Serializer\Serialize was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
42
     */
43
    protected $serialize;
44
45
    /**
46
     * Constructor
47
     *
48
     * @param \Magento\Framework\App\Helper\Context             $context
49
     * @param \Magento\Store\Model\StoreManagerInterface        $storeManager
50
     * @param \Payone\Core\Helper\Shop                          $shopHelper
51
     * @param \Magento\Framework\Serialize\Serializer\Serialize $serialize
52
     */
53
    public function __construct(
54
        \Magento\Framework\App\Helper\Context $context,
0 ignored issues
show
Bug introduced by
The type Magento\Framework\App\Helper\Context was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
55
        \Magento\Store\Model\StoreManagerInterface $storeManager,
0 ignored issues
show
Bug introduced by
The type Magento\Store\Model\StoreManagerInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
56
        \Payone\Core\Helper\Shop $shopHelper,
57
        \Magento\Framework\Serialize\Serializer\Serialize $serialize
58
    ) {
59
        parent::__construct($context, $storeManager, $shopHelper);
60
        $this->serialize = $serialize;
61
    }
62
63
    /**
64
     * Get security keys for all payment types for the given store code
65
     *
66
     * @param  string $sStoreCode
67
     * @return array
68
     */
69
    protected function getAllPayoneSecurityKeysByStoreCode($sStoreCode)
70
    {
71
        $aKeys = [];
72
        foreach (Payment::$aAvailablePayments as $sPaymentCode) {
73
            $iUseGlobal = $this->getConfigParam('use_global', $sPaymentCode, 'payone_payment', $sStoreCode);
74
            if ($iUseGlobal == '0') {
75
                $aKeys[] = $this->getConfigParam('key', $sPaymentCode, 'payone_payment', $sStoreCode);
76
            }
77
        }
78
        return $aKeys;
79
    }
80
81
    /**
82
     * Get the configured security keys for all available stores
83
     * and payment types - since every payment-type can have its own
84
     *
85
     * @return array
86
     */
87
    public function getAllPayoneSecurityKeys()
88
    {
89
        $aKeys = $this->getConfigParamAllStores('key');
90
        $aShopIds = $this->storeManager->getStores(false, true);
91
        foreach ($aShopIds as $sStoreCode => $oStore) {
92
            $aKeys = array_merge($aKeys, $this->getAllPayoneSecurityKeysByStoreCode($sStoreCode));
93
        }
94
        return array_unique($aKeys);
95
    }
96
97
    /**
98
     * Check wheither the given key is configured in the shop and thus valid
99
     *
100
     * @param  string $sKey
101
     * @return bool
102
     */
103
    public function isKeyValid($sKey)
104
    {
105
        $aKeyValues = $this->getAllPayoneSecurityKeys();
106
        foreach ($aKeyValues as $sConfigKey) {
107
            if (hash("md5",$sConfigKey) == $sKey) {
108
                return true;
109
            }
110
        }
111
        return false;
112
    }
113
114
    /**
115
     * Replace substitutes in a given text with the given replacements
116
     *
117
     * @param  string   $sText
118
     * @param  string   $aSubstitutionArray
119
     * @param  int|bool $iMaxLength
120
     * @return string
121
     */
122
    public function handleSubstituteReplacement($sText, $aSubstitutionArray, $iMaxLength = false)
123
    {
124
        if (!empty($sText)) {
125
            $sText = str_replace(array_keys($aSubstitutionArray), array_values($aSubstitutionArray), $sText);
0 ignored issues
show
Bug introduced by
$aSubstitutionArray of type string is incompatible with the type array expected by parameter $array of array_values(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

125
            $sText = str_replace(array_keys($aSubstitutionArray), array_values(/** @scrutinizer ignore-type */ $aSubstitutionArray), $sText);
Loading history...
Bug introduced by
$aSubstitutionArray of type string is incompatible with the type array expected by parameter $array of array_keys(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

125
            $sText = str_replace(array_keys(/** @scrutinizer ignore-type */ $aSubstitutionArray), array_values($aSubstitutionArray), $sText);
Loading history...
126
            if ($iMaxLength !== false && strlen($sText) > $iMaxLength) {
127
                $sText = substr($sText, 0, $iMaxLength); // shorten text if too long
0 ignored issues
show
Bug introduced by
It seems like $iMaxLength can also be of type true; however, parameter $length of substr() does only seem to accept integer|null, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

127
                $sText = substr($sText, 0, /** @scrutinizer ignore-type */ $iMaxLength); // shorten text if too long
Loading history...
128
            }
129
            return $sText;
130
        }
131
        return '';
132
    }
133
134
    /**
135
     * Get substituted invoice appendix text
136
     *
137
     * @param  SalesOrder $oOrder
138
     * @return string
139
     */
140
    public function getInvoiceAppendix(SalesOrder $oOrder)
141
    {
142
        $sText = $this->getConfigParam('invoice_appendix', 'invoicing'); // get invoice appendix from config
143
        $aSubstitutionArray = [
144
            '{{order_increment_id}}' => $oOrder->getIncrementId(),
145
            '{{customer_id}}' => $oOrder->getCustomerId(),
146
        ];
147
        $sInvoiceAppendix = $this->handleSubstituteReplacement($sText, $aSubstitutionArray, 255);
0 ignored issues
show
Bug introduced by
$aSubstitutionArray of type array is incompatible with the type string expected by parameter $aSubstitutionArray of Payone\Core\Helper\Toolk...SubstituteReplacement(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

147
        $sInvoiceAppendix = $this->handleSubstituteReplacement($sText, /** @scrutinizer ignore-type */ $aSubstitutionArray, 255);
Loading history...
148
        return $sInvoiceAppendix;
149
    }
150
151
    /**
152
     * Returns narrative text for authorization request
153
     *
154
     * @param  SalesOrder   $oOrder
155
     * @param  PayoneMethod $oPayment
156
     * @return string
157
     */
158
    public function getNarrativeText(SalesOrder $oOrder, PayoneMethod $oPayment)
159
    {
160
        $sText = $this->getConfigParam('narrative_text', $oPayment->getCode(), 'payone_payment'); // get narrative text for payment from config
161
        $aSubstitutionArray = [
162
            '{{order_increment_id}}' => $oOrder->getIncrementId(),
163
        ];
164
        $sNarrativeText = $this->handleSubstituteReplacement($sText, $aSubstitutionArray, $oPayment->getNarrativeTextMaxLength());
0 ignored issues
show
Bug introduced by
$aSubstitutionArray of type array is incompatible with the type string expected by parameter $aSubstitutionArray of Payone\Core\Helper\Toolk...SubstituteReplacement(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

164
        $sNarrativeText = $this->handleSubstituteReplacement($sText, /** @scrutinizer ignore-type */ $aSubstitutionArray, $oPayment->getNarrativeTextMaxLength());
Loading history...
165
        return $sNarrativeText;
166
    }
167
168
    /**
169
     * Format a price to the XX.YY format
170
     *
171
     * @param  double $dPrice    price of any sort
172
     * @param  int    $iDecimals number of digits behind the decimal point
173
     * @return string
174
     */
175
    public function formatNumber($dPrice, $iDecimals = 2)
176
    {
177
        return number_format($dPrice, $iDecimals, '.', '');
178
    }
179
180
    /**
181
     * Masks IBAN
182
     *
183
     * @param string $sUnmasked
184
     * @return string
185
     */
186
    public function maskIban($sUnmasked)
187
    {
188
        $sMasked = '';
189
        for ($i = 0; $i < strlen($sUnmasked); $i++) {
190
            if ($i == 2 || ((strlen($sUnmasked) - 2) % 4 == 0 && (($i - 2) % 4 == 0))) {
191
                $sMasked .= ' ';
192
            }
193
194
            if ($i < 4 || $i >= (strlen($sUnmasked) - 4)) {
195
                $sMasked .= $sUnmasked[$i];
196
            } else {
197
                $sMasked .= 'x';
198
            }
199
        }
200
        return $sMasked;
201
    }
202
203
    /**
204
     * Checks if given string is utf8 encoded
205
     *
206
     * @param  string $sString
207
     * @return bool
208
     */
209
    public function isUTF8($sString)
210
    {
211
        return $sString === mb_convert_encoding(mb_convert_encoding($sString, "UTF-32", "UTF-8"), "UTF-8", "UTF-32");
212
    }
213
214
    /**
215
     * Handle the serialization of strings depending on the Magento version
216
     *
217
     * @param  mixed $mValue
218
     * @return string
219
     */
220
    public function serialize($mValue)
221
    {
222
        if (version_compare($this->shopHelper->getMagentoVersion(), '2.2.0', '>=')) { // Magento 2.2.0 and above
223
            return json_encode($mValue);
224
        }
225
        return $this->serialize->serialize($mValue);
226
    }
227
228
    /**
229
     * @param  string $sValue
230
     * @return mixed
231
     */
232
    public function unserialize($sValue)
233
    {
234
        if ($this->isJson($sValue)) {
235
            return json_decode($sValue, true);
236
        }
237
        return $this->serialize->unserialize($sValue);
238
    }
239
240
    /**
241
     * Return data from data-object
242
     * Needed because of different ways to read from it for different magento versions
243
     *
244
     * @param  DataObject $oData
245
     * @param  string     $sKey
246
     * @return string|null
247
     */
248
    public function getAdditionalDataEntry(DataObject $oData, $sKey)
249
    {
250
        // The way to read the form-parameters changed with version 2.0.6
251
        if (version_compare($this->shopHelper->getMagentoVersion(), '2.0.6', '>=')) { // Magento 2.0.6 and above
252
            $aAdditionalData = $oData->getAdditionalData();
253
            if (isset($aAdditionalData[$sKey])) {
254
                return $aAdditionalData[$sKey];
255
            }
256
            return null;
257
        }
258
        // everything below 2.0.6
259
        return $oData->getData($sKey);
260
    }
261
}
262