Passed
Push — master ( cd0859...506e18 )
by
unknown
03:20 queued 12s
created

Debit::sendRequest()   C

Complexity

Conditions 12
Paths 96

Size

Total Lines 60
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 12
eloc 36
c 1
b 0
f 0
nc 96
nop 3
dl 0
loc 60
rs 6.9666

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\Model\Api\Request;
28
29
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...
30
use Magento\Sales\Model\Order;
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\Sales\Model\Order\Creditmemo;
0 ignored issues
show
Bug introduced by
The type Magento\Sales\Model\Order\Creditmemo 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\Payment\Model\InfoInterface;
0 ignored issues
show
Bug introduced by
The type Magento\Payment\Model\InfoInterface 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
 * Class for the PAYONE Server API request "debit"
37
 */
38
class Debit extends Base
39
{
40
    /**
41
     * @var \Payone\Core\Model\Api\Invoice $invoiceGenerator
42
     */
43
    protected $invoiceGenerator;
44
45
    /**
46
     * PAYONE database helper
47
     *
48
     * @var \Payone\Core\Helper\Database
49
     */
50
    protected $databaseHelper;
51
52
    /**
53
     * PAYONE toolkit helper
54
     *
55
     * @var \Payone\Core\Helper\Toolkit
56
     */
57
    protected $toolkitHelper;
58
59
    /**
60
     * Constructor
61
     *
62
     * @param \Payone\Core\Helper\Shop                $shopHelper
63
     * @param \Payone\Core\Helper\Environment         $environmentHelper
64
     * @param \Payone\Core\Helper\Api                 $apiHelper
65
     * @param \Payone\Core\Model\ResourceModel\ApiLog $apiLog
66
     * @param \Payone\Core\Model\Api\Invoice          $invoiceGenerator
67
     * @param \Payone\Core\Helper\Database            $databaseHelper
68
     * @param \Payone\Core\Helper\Toolkit             $toolkitHelper
69
     */
70
    public function __construct(
71
        \Payone\Core\Helper\Shop $shopHelper,
72
        \Payone\Core\Helper\Environment $environmentHelper,
73
        \Payone\Core\Helper\Api $apiHelper,
74
        \Payone\Core\Model\ResourceModel\ApiLog $apiLog,
75
        \Payone\Core\Model\Api\Invoice $invoiceGenerator,
76
        \Payone\Core\Helper\Database $databaseHelper,
77
        \Payone\Core\Helper\Toolkit $toolkitHelper
78
    ) {
79
        parent::__construct($shopHelper, $environmentHelper, $apiHelper, $apiLog);
80
        $this->invoiceGenerator = $invoiceGenerator;
81
        $this->databaseHelper = $databaseHelper;
82
        $this->toolkitHelper = $toolkitHelper;
83
    }
84
85
    /**
86
     * Generate position list for invoice data transmission
87
     *
88
     * @param  Order      $oOrder
89
     * @param  Creditmemo $oCreditmemo
90
     * @return array|false
91
     */
92
    protected function getInvoiceList(Order $oOrder, Creditmemo $oCreditmemo)
93
    {
94
        $aPositions = [];
95
        $blFull = true;
96
        foreach ($oOrder->getAllItems() as $oItem) {
97
            $blFound = false;
98
            foreach ($oCreditmemo->getAllItems() as $oCreditMemoItem) {
99
                if ($oCreditMemoItem->getOrderItemId() == $oItem->getItemId() && $oCreditMemoItem->getQty() > 0) {
100
                    $blFound = true;
101
                    $aPositions[$oItem->getProductId().$oItem->getSku()] = $oCreditMemoItem->getQty();
102
                    if ($oCreditMemoItem->getQty() != $oItem->getQtyOrdered()) {
103
                        $blFull = false;
104
                    }
105
                }
106
            }
107
            if ($blFound === false) {
108
                $blFull = false;
109
            }
110
        }
111
112
        if ($oCreditmemo->getBaseShippingInclTax() != 0) {
113
            $aPositions['delcost'] = $oCreditmemo->getBaseShippingInclTax();
114
        }
115
        if ($blFull !== true && $oCreditmemo->getBaseDiscountAmount() != 0) {
116
            $aPositions['discount'] = $oCreditmemo->getBaseDiscountAmount();
117
            if ($this->shopHelper->getConfigParam('currency', 'global', 'payone_general', $this->storeCode) == 'display') {
118
                $aPositions['discount'] = $oCreditmemo->getDiscountAmount();
119
            }
120
        }
121
        if ($blFull === true && $oCreditmemo->getBaseShippingInclTax() == $oOrder->getBaseShippingInclTax()) {
122
            $aPositions = false; // false = full debit
123
        }
124
        return $aPositions;
125
    }
126
127
    /**
128
     * Send request "debit" to PAYONE server API
129
     *
130
     * @param  PayoneMethod  $oPayment
131
     * @param  InfoInterface $oPaymentInfo
132
     * @param  float         $dAmount
133
     * @return array
134
     */
135
    public function sendRequest(PayoneMethod $oPayment, InfoInterface $oPaymentInfo, $dAmount)
136
    {
137
        $oOrder = $oPaymentInfo->getOrder();
138
139
        $this->setStoreCode($oOrder->getStore()->getCode());
140
141
        $oCreditmemo = $oPaymentInfo->getCreditmemo();
142
        $aPositions = $this->getInvoiceList($oOrder, $oCreditmemo);
143
144
        if ($this->shopHelper->getConfigParam('currency', 'global', 'payone_general', $this->storeCode) == 'display') {
145
            $dAmount = $oCreditmemo->getGrandTotal(); // send display amount instead of base amount
146
        }
147
148
        $iTxid = $oPaymentInfo->getParentTransactionId();
149
        if (strpos($iTxid, '-') !== false) {
150
            $iTxid = substr($iTxid, 0, strpos($iTxid, '-')); // clean the txid from the magento-suffixes
151
        }
152
153
        $this->setOrderId($oOrder->getRealOrderId());
154
155
        $this->addParameter('request', 'debit'); // Request method
156
        $this->addParameter('mode', $oPayment->getOperationMode()); // PayOne Portal Operation Mode (live or test)
157
        $this->addParameter('txid', $iTxid); // PayOne Transaction ID
158
        $this->addParameter('sequencenumber', $this->databaseHelper->getSequenceNumber($iTxid));
159
160
        // Total order sum in smallest currency unit
161
        $this->addParameter('amount', number_format((-1 * $dAmount), 2, '.', '') * 100); // add price to request
162
        $this->addParameter('currency', $this->apiHelper->getCurrencyFromOrder($oOrder)); // add currency to request
163
164
        $this->addParameter('transactiontype', 'GT');
165
166
        $sRefundAppendix = $this->getRefundAppendix($oOrder, $oPayment);
167
        if (!empty($sRefundAppendix)) {
168
            $this->addParameter('invoiceappendix', $sRefundAppendix);
169
        }
170
171
        if ($this->apiHelper->isInvoiceDataNeeded($oPayment, $aPositions)) {
0 ignored issues
show
Bug introduced by
It seems like $aPositions can also be of type false; however, parameter $aPositions of Payone\Core\Helper\Api::isInvoiceDataNeeded() does only seem to accept array|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

171
        if ($this->apiHelper->isInvoiceDataNeeded($oPayment, /** @scrutinizer ignore-type */ $aPositions)) {
Loading history...
172
            $this->invoiceGenerator->addProductInfo($this, $oOrder, $aPositions, true); // add invoice parameters
0 ignored issues
show
Bug introduced by
It seems like $aPositions can also be of type false; however, parameter $aPositions of Payone\Core\Model\Api\Invoice::addProductInfo() does only seem to accept array, 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

172
            $this->invoiceGenerator->addProductInfo($this, $oOrder, /** @scrutinizer ignore-type */ $aPositions, true); // add invoice parameters
Loading history...
173
        }
174
175
        $sIban = false;
176
        $sBic = false;
177
        if (!empty($oOrder->getPayoneRefundIban()) && !empty($oOrder->getPayoneRefundBic())) {
178
            $sIban = $oOrder->getPayoneRefundIban();
179
            $sBic = $oOrder->getPayoneRefundBic();
180
        } elseif ($oCreditmemo->getPayoneIban() && $oCreditmemo->getPayoneBic()) {
181
            $sIban = $oCreditmemo->getPayoneIban();
182
            $sBic = $oCreditmemo->getPayoneBic();
183
        }
184
185
        if ($sIban !== false && $sBic !== false && $this->isSepaDataValid($sIban, $sBic)) {
186
            $this->addParameter('iban', $sIban);
187
            $this->addParameter('bic', $sBic);
188
        }
189
190
        $this->aParameters = array_merge($this->aParameters, $oPayment->getPaymentSpecificDebitParameters($oOrder));
191
192
        $aResponse = $this->send($oPayment);
193
194
        return $aResponse;
195
    }
196
197
    /**
198
     * Get substituted refund appendix text
199
     *
200
     * @param  Order        $oOrder
201
     * @param  PayoneMethod $oPayment
202
     * @return string
203
     */
204
    protected function getRefundAppendix(Order $oOrder, PayoneMethod $oPayment)
205
    {
206
        $sText = $this->shopHelper->getConfigParam('invoice_appendix_refund', 'invoicing', 'payone_general', $this->storeCode);
207
        $sCreditMemoIncrId = '';
208
        $sInvoiceIncrementId = '';
209
        $sInvoiceId = '';
210
211
        $oCreditmemo = $oPayment->getCreditmemo();
212
        if ($oCreditmemo) {
213
            $sCreditMemoIncrId = $oCreditmemo->getIncrementId();
214
            $oInvoice = $oCreditmemo->getInvoice();
215
            if ($oInvoice) {
216
                $sInvoiceIncrementId = $oInvoice->getIncrementId();
217
                $sInvoiceId = $oInvoice->getId();
218
            }
219
        }
220
221
        $aSubstitutionArray = [
222
            '{{order_increment_id}}' => $oOrder->getIncrementId(),
223
            '{{order_id}}' => $oOrder->getId(),
224
            '{{customer_id}}' => $oOrder->getCustomerId(),
225
            '{{creditmemo_increment_id}}' => $sCreditMemoIncrId,
226
            '{{invoice_increment_id}}' => $sInvoiceIncrementId,
227
            '{{invoice_id}}' => $sInvoiceId,
228
        ];
229
        $sRefundAppendix = $this->toolkitHelper->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

229
        $sRefundAppendix = $this->toolkitHelper->handleSubstituteReplacement($sText, /** @scrutinizer ignore-type */ $aSubstitutionArray, 255);
Loading history...
230
        return $sRefundAppendix;
231
    }
232
233
    /**
234
     * Validate IBAN
235
     *
236
     * @param  string $sIban
237
     * @return bool
238
     */
239
    protected function isIbanValid($sIban)
240
    {
241
        $sRegex = '/^[a-zA-Z]{2}[0-9]{2}[a-zA-Z0-9]{4}[0-9]{7}(?:[a-zA-Z0-9]?){0,16}$/';
242
        return $this->checkRegex($sRegex, $sIban);
243
    }
244
245
    /**
246
     * Check if the regex validates correctly
247
     *
248
     * @param  string $sRegex
249
     * @param  string $sValue
250
     * @return bool
251
     */
252
    protected function checkRegex($sRegex, $sValue)
253
    {
254
        preg_match($sRegex, str_replace(' ', '', $sValue), $aMatches);
255
        if (empty($aMatches)) {
256
            return false;
257
        }
258
        return true;
259
    }
260
261
    /**
262
     * Validate IBAN
263
     *
264
     * @param  string $sBic
265
     * @return bool
266
     */
267
    protected function isBicValid($sBic)
268
    {
269
        $sRegex = '/^([a-zA-Z]{4}[a-zA-Z]{2}[a-zA-Z0-9]{2}([a-zA-Z0-9]{3})?)$/';
270
        return $this->checkRegex($sRegex, $sBic);
271
    }
272
273
    /**
274
     * Check IBAN and BIC fields
275
     *
276
     * @param  string $sIban
277
     * @param  string $sBic
278
     * @return bool
279
     * @throws LocalizedException
280
     */
281
    public function isSepaDataValid($sIban, $sBic)
282
    {
283
        if (!$this->isIbanValid($sIban)) {
284
            throw new LocalizedException(__('The given IBAN is invalid!'));
0 ignored issues
show
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

284
            throw new LocalizedException(/** @scrutinizer ignore-call */ __('The given IBAN is invalid!'));
Loading history...
285
        }
286
        if (!$this->isBicValid($sBic)) {
287
            throw new LocalizedException(__('The given BIC is invalid!'));
288
        }
289
        return true;
290
    }
291
}
292