Passed
Pull Request — master (#441)
by
unknown
03:19
created

InstallmentPlan::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 20
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 9
nc 1
nop 9
dl 0
loc 20
rs 9.9666
c 0
b 0
f 0

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

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 - 2017 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\Service\V1;
28
29
use Payone\Core\Api\InstallmentPlanInterface;
30
use Payone\Core\Helper\Api;
31
use Payone\Core\Service\V1\Data\InstallmentPlanResponse;
32
use Payone\Core\Api\Data\InstallmentPlanResponseInterfaceFactory;
0 ignored issues
show
Bug introduced by
The type Payone\Core\Api\Data\Ins...esponseInterfaceFactory 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...
33
use Magento\Checkout\Model\Session;
0 ignored issues
show
Bug introduced by
The type Magento\Checkout\Model\Session 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
use Payone\Core\Model\Api\Request\Genericpayment\Calculation;
35
use Payone\Core\Model\Api\Request\Genericpayment\PreCheck;
36
use Payone\Core\Model\Methods\Payolution\Installment;
37
use Payone\Core\Block\Payolution\InstallmentPlan as Block;
38
use Payone\Core\Helper\Ratepay;
39
use Payone\Core\Model\Methods\Ratepay\Installment as RatepayInstallment;
40
41
/**
42
 * Web API model for the PAYONE addresscheck
43
 */
44
class InstallmentPlan implements InstallmentPlanInterface
45
{
46
    /**
47
     * Factory for the response object
48
     *
49
     * @var InstallmentPlanResponseInterfaceFactory
50
     */
51
    protected $responseFactory;
52
53
    /**
54
     * Checkout session object
55
     *
56
     * @var Session
57
     */
58
    protected $checkoutSession;
59
60
    /**
61
     * Calculation Genericpayment request object
62
     *
63
     * @var Calculation
64
     */
65
    protected $calculation;
66
67
    /**
68
     * Payone Payolution Installment payment method
69
     *
70
     * @var Installment
71
     */
72
    protected $payolution;
73
74
    /**
75
     * InstallmentRate Block object
76
     *
77
     * @var Block
78
     */
79
    protected $block;
80
81
    /**
82
     * PreCheck Genericpayment request object
83
     *
84
     * @var PreCheck
85
     */
86
    protected $precheck;
87
88
    /**
89
     * @var Ratepay
90
     */
91
    protected $ratepayHelper;
92
93
    /**
94
     * @var RatepayInstallment
95
     */
96
    protected $ratepayInstallment;
97
98
    /**
99
     * @var Api
100
     */
101
    protected $apiHelper;
102
103
    /**
104
     * Constructor.
105
     *
106
     * @param InstallmentPlanResponseInterfaceFactory $responseFactory
107
     * @param Session                                 $checkoutSession
108
     * @param PreCheck                                $precheck
109
     * @param Calculation                             $calculation
110
     * @param Installment                             $payolution
111
     * @param Block                                   $block
112
     * @param Ratepay                                 $ratepayHelper
113
     * @param RatepayInstallment                      $ratepayInstallment
114
     * @param Api                                     $apiHelper
115
     */
116
    public function __construct(
117
        InstallmentPlanResponseInterfaceFactory $responseFactory,
118
        Session $checkoutSession,
119
        PreCheck $precheck,
120
        Calculation $calculation,
121
        Installment $payolution,
122
        Block $block,
123
        Ratepay $ratepayHelper,
124
        RatepayInstallment $ratepayInstallment,
125
        Api $apiHelper
126
    ) {
127
        $this->responseFactory = $responseFactory;
128
        $this->checkoutSession = $checkoutSession;
129
        $this->precheck = $precheck;
130
        $this->calculation = $calculation;
131
        $this->payolution = $payolution;
132
        $this->block = $block;
133
        $this->ratepayInstallment = $ratepayInstallment;
134
        $this->ratepayHelper = $ratepayHelper;
135
        $this->apiHelper = $apiHelper;
136
    }
137
138
    /**
139
     * Write installment draft download link array to session
140
     *
141
     * @param  $aInstallmentData
142
     * @return void
143
     */
144
    protected function setInstallmentDraftDownloadLinks($aInstallmentData)
145
    {
146
        $aDownloadLinks = array();
147
        foreach ($aInstallmentData as $aInstallment) {
148
            $aDownloadLinks[$aInstallment['duration']] = $aInstallment['standardcreditinformationurl'];
149
        }
150
        $this->checkoutSession->setInstallmentDraftLinks($aDownloadLinks);
151
    }
152
153
    /**
154
     * Check responses for errors and add them to the response object if needed
155
     *
156
     * @param  InstallmentPlanResponse $oResponse
157
     * @param  array                   $aResponsePreCheck
158
     * @param  array                   $aResponseCalculation
159
     * @return InstallmentPlanResponse
160
     */
161
    protected function checkForErrors($oResponse, $aResponsePreCheck, $aResponseCalculation)
162
    {
163
        $sErrorMessage = false;
164
        if (isset($aResponsePreCheck['status']) && $aResponsePreCheck['status'] == 'ERROR') {
165
            $sErrorMessage = __($aResponsePreCheck['errorcode'] . ' - ' . $aResponsePreCheck['customermessage']);
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

165
            $sErrorMessage = /** @scrutinizer ignore-call */ __($aResponsePreCheck['errorcode'] . ' - ' . $aResponsePreCheck['customermessage']);
Loading history...
166
        } elseif (isset($aResponseCalculation['status']) && $aResponseCalculation['status'] == 'ERROR') {
167
            $sErrorMessage = __($aResponseCalculation['errorcode'] . ' - ' . $aResponseCalculation['customermessage']);
168
        } elseif (!$aResponsePreCheck || (isset($aResponsePreCheck['status']) && $aResponsePreCheck['status'] == 'OK' && !$aResponseCalculation)) {
169
            $sErrorMessage = __('An unknown error occurred');
170
        }
171
        if ($sErrorMessage !== false) {
172
            $oResponse->setData('errormessage', $sErrorMessage);
173
        }
174
        return $oResponse;
175
    }
176
177
    /**
178
     * PAYONE addresscheck
179
     * The full class-paths must be given here otherwise the Magento 2 WebApi
180
     * cant handle this with its fake type system!
181
     *
182
     * @param  string $cartId
183
     * @param  string $birthday
184
     * @param  string $email
185
     * @return \Payone\Core\Service\V1\Data\InstallmentPlanResponse
186
     */
187
    public function getInstallmentPlan($cartId, $birthday, $email = false)
188
    {
189
        $oResponse = $this->responseFactory->create();
190
        $oResponse->setData('success', false); // set success to false as default, set to true later if true
191
192
        $oQuote = $this->checkoutSession->getQuote();
193
        $aResponsePreCheck = $this->precheck->sendRequest($this->payolution, $oQuote, false, $birthday, $email);
194
        $aResponseCalculation = false;
195
        if (isset($aResponsePreCheck['status']) && $aResponsePreCheck['status'] == 'OK') {
196
            $aResponseCalculation = $this->calculation->sendRequest($this->payolution, $oQuote);
197
            $aInstallmentData = $this->parseResponse($aResponseCalculation);
198
            if (isset($aResponseCalculation['status']) && $aResponseCalculation['status'] == 'OK' && $aInstallmentData !== false) {
199
                $oResponse->setData('success', true); // set success to false as default, set to true later if true
200
                $this->setInstallmentDraftDownloadLinks($aInstallmentData);
201
                $this->checkoutSession->setInstallmentWorkorderId($aResponseCalculation['workorderid']);
202
203
                $this->block->setInstallmentData($aInstallmentData);
204
                $this->block->setCode($this->payolution->getCode());
205
206
                $oResponse->setData('installmentPlanHtml', $this->block->toHtml());
207
            }
208
        }
209
        $oResponse = $this->checkForErrors($oResponse, $aResponsePreCheck, $aResponseCalculation);
210
        return $oResponse;
211
    }
212
213
    /**
214
     * PAYONE addresscheck
215
     * The full class-paths must be given here otherwise the Magento 2 WebApi
216
     * cant handle this with its fake type system!
217
     *
218
     * @param  string $cartId
219
     * @param  string $calcType
220
     * @param  int $calcValue
221
     * @return \Payone\Core\Service\V1\Data\InstallmentPlanResponse
222
     */
223
    public function getInstallmentPlanRatepay($cartId, $calcType, $calcValue)
224
    {
225
        $oResponse = $this->responseFactory->create();
226
        $oResponse->setData('success', false); // set success to false as default, set to true later if true
227
228
        $oQuote = $this->checkoutSession->getQuote();
229
230
        $sRatepayShopId = $this->ratepayHelper->getRatepayShopId($this->ratepayInstallment->getCode(), $oQuote->getBillingAddress()->getCountryId(), $this->apiHelper->getCurrencyFromQuote($oQuote), $this->apiHelper->getQuoteAmount($oQuote));
231
232
        $aResponseCalculation = $this->calculation->sendRequestRatepay($this->ratepayInstallment, $oQuote, $sRatepayShopId, $calcType, $calcValue);
233
        if ($aResponseCalculation['status'] == "OK") {
234
            unset($aResponseCalculation['status']);
235
            unset($aResponseCalculation['workorderid']);
236
            $aInstallmentPlan = [];
237
            foreach ($aResponseCalculation as $sKey => $sValue) {
238
                $sKey = str_replace("add_paydata", "", $sKey);
239
                $sKey = str_replace(["[", "]"], "", $sKey);
240
                $sKey = str_replace("-", "_", $sKey);
241
                $aInstallmentPlan[$sKey] = $sValue;
242
            }
243
            $oResponse->setData('installmentPlan', json_encode($aInstallmentPlan));
244
            $oResponse->setData('success', true);
245
        }
246
        return $oResponse;
247
    }
248
249
    /**
250
     * @param array $aResponse
251
     * @return array
252
     */
253
    public function getPayDataArray($aResponse)
254
    {
255
        $aPayData = array();
256
        foreach($aResponse as $sKey => $sValue) {
257
            $sCorrectedKey = str_ireplace('add_paydata[', '', $sKey);
258
            $sCorrectedKey = rtrim($sCorrectedKey, ']');
0 ignored issues
show
Bug introduced by
It seems like $sCorrectedKey can also be of type array; however, parameter $string of rtrim() does only seem to accept string, 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

258
            $sCorrectedKey = rtrim(/** @scrutinizer ignore-type */ $sCorrectedKey, ']');
Loading history...
259
            $sCorrectedKey = strtolower($sCorrectedKey);
260
            $sCorrectedKey = str_replace('-', '_', $sCorrectedKey);
261
            $aPayData[$sCorrectedKey] = $sValue;
262
        }
263
264
        ksort($aPayData);
265
        return $aPayData;
266
    }
267
268
    /**
269
     * Parse the response array into a readable array
270
     *
271
     * @param $aResponse
272
     * @return array|false
273
     */
274
    protected function parseResponse($aResponse)
275
    {
276
        $aInstallmentData = array();
277
278
        $aPayData = $this->getPayDataArray($aResponse);
279
        foreach ($aPayData as $sKey => $sValue) {
280
            $aSplit = explode('_', $sKey);
281
            for($i = count($aSplit); $i > 0; $i--) {
282
                if($i == count($aSplit)) {
283
                    $aTmp = array($aSplit[$i-1] => $sValue);
284
                } else {
285
                    $aTmp = array($aSplit[$i-1] => $aTmp);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $aTmp does not seem to be defined for all execution paths leading up to this point.
Loading history...
286
                }
287
            }
288
289
            $aInstallmentData = array_replace_recursive($aInstallmentData, $aTmp);
290
        }
291
292
        if(isset($aInstallmentData['paymentdetails']) && count($aInstallmentData['paymentdetails']) > 0) {
293
            return $aInstallmentData['paymentdetails'];
294
        }
295
296
        return false;
297
    }
298
}
299