CheckoutSubmitBefore   A
last analyzed

Complexity

Total Complexity 31

Size/Duplication

Total Lines 193
Duplicated Lines 4.15 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 31
c 1
b 0
f 0
lcom 1
cbo 2
dl 8
loc 193
rs 9.8

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A getConfigParam() 8 8 2
A isCreditratingNeeded() 0 20 4
B isPaymentApplicableForScore() 0 19 7
B checkoutNeedsToBeStopped() 0 8 5
B getScoreByCreditrating() 0 22 5
A getInsufficientScoreMessage() 0 8 2
B execute() 0 27 5

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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\Observer;
28
29
use Magento\Framework\Event\ObserverInterface;
30
use Magento\Framework\Event\Observer;
31
use Magento\Framework\Exception\LocalizedException;
32
use Magento\Quote\Model\Quote;
33
use Magento\Quote\Api\Data\AddressInterface;
34
use Payone\Core\Model\Source\CreditratingIntegrationEvent as Event;
35
36
/**
37
 * Event class to set the orderstatus to new and pending
38
 */
39
class CheckoutSubmitBefore implements ObserverInterface
40
{
41
    /**
42
     * PAYONE consumerscore request model
43
     *
44
     * @var \Payone\Core\Model\Api\Request\Consumerscore
45
     */
46
    protected $consumerscore;
47
48
    /**
49
     * Consumerscore helper
50
     *
51
     * @var \Payone\Core\Helper\Consumerscore
52
     */
53
    protected $consumerscoreHelper;
54
55
    /**
56
     * Constructor
57
     *
58
     * @param \Payone\Core\Model\Api\Request\Consumerscore $consumerscore
59
     * @param \Payone\Core\Helper\Consumerscore            $consumerscoreHelper
60
     */
61
    public function __construct(
62
        \Payone\Core\Model\Api\Request\Consumerscore $consumerscore,
63
        \Payone\Core\Helper\Consumerscore $consumerscoreHelper
64
    ) {
65
        $this->consumerscore = $consumerscore;
66
        $this->consumerscoreHelper = $consumerscoreHelper;
67
    }
68
69
    /**
70
     * Get parameter from config
71
     *
72
     * @param  string $sParam
73
     * @param  bool   $blIsAddresscheck
74
     * @return string
75
     */
76 View Code Duplication
    public function getConfigParam($sParam, $blIsAddresscheck = false)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
77
    {
78
        $sGroup = 'creditrating';
79
        if ($blIsAddresscheck === true) {
80
            $sGroup = 'address_check';
81
        }
82
        return $this->consumerscoreHelper->getConfigParam($sParam, $sGroup, 'payone_protect');
83
    }
84
85
    /**
86
     * Determine if creditrating is needed
87
     *
88
     * @param  Quote $oQuote
89
     * @return bool
90
     */
91
    public function isCreditratingNeeded(Quote $oQuote)
92
    {
93
        if (!$this->consumerscoreHelper->isCreditratingNeeded(Event::AFTER_PAYMENT, $oQuote->getGrandTotal())) {
94
            return false;
95
        }
96
97
        $oMethodInstance = $oQuote->getPayment()->getMethodInstance();
98
        $sPaymentCode = $oMethodInstance->getCode();
99
        $sPaymentTypesToCheck = $this->getConfigParam('enabled_for_payment_methods');
100
        $aPaymentTypesToCheck = explode(',', $sPaymentTypesToCheck);
101
        if (array_search($sPaymentCode, $aPaymentTypesToCheck) === false) {
102
            return false;
103
        }
104
105
        if ($oMethodInstance->getInfoInstance()->getAdditionalInformation('payone_boni_agreement') === false) {
106
            return false; // agreement checkbox was not checked by the customer
107
        }
108
109
        return true;
110
    }
111
112
    /**
113
     * Determine if the payment type can be used with this score
114
     *
115
     * @param  Quote $oQuote
116
     * @param  string $sScore
117
     * @return bool
118
     */
119
    public function isPaymentApplicableForScore(Quote $oQuote, $sScore)
120
    {
121
        if ($sScore == 'G') {
122
            return true;
123
        }
124
125
        $sPaymentCode = $oQuote->getPayment()->getMethodInstance()->getCode();
126
127
        $aYellowMethods = $this->consumerscoreHelper->getAllowedMethodsForScore('Y');
128
        $aRedMethods = $this->consumerscoreHelper->getAllowedMethodsForScore('R');
129
130
        if ($sScore == 'Y' && (array_search($sPaymentCode, $aYellowMethods) !== false ||
131
                array_search($sPaymentCode, $aRedMethods) !== false)) {
132
            return true;
133
        } elseif ($sScore == 'R' && array_search($sPaymentCode, $aRedMethods) !== false) {
134
            return true;
135
        }
136
        return false;
137
    }
138
139
    /**
140
     *
141
     * @param  array $aResponse
142
     * @return bool
143
     */
144
    public function checkoutNeedsToBeStopped($aResponse)
145
    {
146
        if (!$aResponse || (isset($aResponse['status']) && $aResponse['status'] == 'ERROR'
0 ignored issues
show
Bug Best Practice introduced by
The expression $aResponse of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
147
                && $this->getConfigParam('handle_response_error') == 'stop_checkout')) {
148
            return true;
149
        }
150
        return false;
151
    }
152
153
    /**
154
     * Filter payment methods by the creditrating result if applicable
155
     *
156
     * @param  AddressInterface $oBilling
157
     * @return string
158
     * @throws LocalizedException
159
     */
160
    public function getScoreByCreditrating(AddressInterface $oBilling)
161
    {
162
        $aResponse = $this->consumerscore->sendRequest($oBilling);
163
        if ($aResponse === true) { // creditrating not executed because of a previous check
164
            $this->consumerscoreHelper->copyOldStatusToNewAddress($oBilling);
165
        }
166
167
        if ($this->checkoutNeedsToBeStopped($aResponse)) {
0 ignored issues
show
Bug introduced by
It seems like $aResponse defined by $this->consumerscore->sendRequest($oBilling) on line 162 can also be of type boolean; however, Payone\Core\Observer\Che...ckoutNeedsToBeStopped() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
168
            $sErrorMsg = $this->getConfigParam('stop_checkout_message');
169
            if (empty($sErrorMsg)) {
170
                $sErrorMsg = 'An error occured during the credit check.';
171
            }
172
            throw new LocalizedException(__($sErrorMsg));
173
        }
174
175
        if (isset($aResponse['score'])) {
176
            $oBilling->setPayoneProtectScore($aResponse['score'])->save();
177
        }
178
179
        $sScore = $oBilling->getPayoneProtectScore();
180
        return $sScore;
181
    }
182
183
    /**
184
     * Get error message for when the creditrating failed because the score is insufficient
185
     *
186
     * @return string
187
     */
188
    public function getInsufficientScoreMessage()
189
    {
190
        $sErrorMsg = $this->getConfigParam('insufficient_score_message');
191
        if (empty($sErrorMsg)) {
192
            $sErrorMsg = 'An error occured during the credit check.';
193
        }
194
        return $sErrorMsg;
195
    }
196
197
    /**
198
     * Execute certain tasks after the payment is placed and thus the order is placed
199
     *
200
     * @param  Observer $observer
201
     * @return void
202
     * @throws LocalizedException
203
     */
204
    public function execute(Observer $observer)
205
    {
206
        /** @var Quote $oQuote */
207
        $oQuote = $observer->getQuote();
208
        if (!$oQuote) {
209
            return;
210
        }
211
212
        $oBilling = $oQuote->getBillingAddress();
213
        $oShipping = $oQuote->getShippingAddress();
214
215
        $aScores = [];
216
        if ($this->getConfigParam('enabled', true)) { // is addresscheck active
217
            $aScores[] = $oBilling->getPayoneAddresscheckScore();
218
            $aScores[] = $oShipping->getPayoneAddresscheckScore();
219
        }
220
221
        if ($this->isCreditratingNeeded($oQuote) === true) {
222
            $aScores[] = $this->getScoreByCreditrating($oBilling);
223
        }
224
225
        $sScore = $this->consumerscoreHelper->getWorstScore($aScores);
226
        $blSuccess = $this->isPaymentApplicableForScore($oQuote, $sScore);
227
        if ($blSuccess === false) {
228
            throw new LocalizedException(__($this->getInsufficientScoreMessage()));
229
        }
230
    }
231
}
232