Completed
Push — master ( 341936...178071 )
by Florian
03:31
created

InstallmentPlan::getPayDataArray()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
c 0
b 0
f 0
rs 9.4285
cc 2
eloc 10
nc 2
nop 1
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\Service\V1\Data\InstallmentPlanResponse;
31
use Payone\Core\Api\Data\InstallmentPlanResponseInterfaceFactory;
32
use Magento\Checkout\Model\Session;
33
use Payone\Core\Model\Api\Request\Genericpayment\Calculation;
34
use Payone\Core\Model\Api\Request\Genericpayment\PreCheck;
35
use Payone\Core\Model\Methods\Payolution\Installment;
36
use Payone\Core\Block\Payolution\InstallmentPlan as Block;
37
38
/**
39
 * Web API model for the PAYONE addresscheck
40
 */
41
class InstallmentPlan implements InstallmentPlanInterface
42
{
43
    /**
44
     * Factory for the response object
45
     *
46
     * @var InstallmentPlanResponseInterfaceFactory
47
     */
48
    protected $responseFactory;
49
50
    /**
51
     * Checkout session object
52
     *
53
     * @var Session
54
     */
55
    protected $checkoutSession;
56
57
    /**
58
     * Calculation Genericpayment request object
59
     *
60
     * @var Calculation
61
     */
62
    protected $calculation;
63
64
    /**
65
     * Payone Payolution Installment payment method
66
     *
67
     * @var Installment
68
     */
69
    protected $payment;
70
71
    /**
72
     * InstallmentRate Block object
73
     *
74
     * @var Block
75
     */
76
    protected $block;
77
78
    /**
79
     * PreCheck Genericpayment request object
80
     *
81
     * @var PreCheck
82
     */
83
    protected $precheck;
84
85
    /**
86
     * Constructor.
87
     *
88
     * @param InstallmentPlanResponseInterfaceFactory $responseFactory
89
     * @param Session                                 $checkoutSession
90
     * @param PreCheck                                $precheck
91
     * @param Calculation                             $calculation
92
     * @param Installment                             $payment
93
     * @param Block                                   $block
94
     */
95
    public function __construct(
96
        InstallmentPlanResponseInterfaceFactory $responseFactory,
97
        Session $checkoutSession,
98
        PreCheck $precheck,
99
        Calculation $calculation,
100
        Installment $payment,
101
        Block $block
102
    ) {
103
        $this->responseFactory = $responseFactory;
104
        $this->checkoutSession = $checkoutSession;
105
        $this->precheck = $precheck;
106
        $this->calculation = $calculation;
107
        $this->payment = $payment;
108
        $this->block = $block;
109
    }
110
111
    /**
112
     * Write installment draft download link array to session
113
     *
114
     * @param  $aInstallmentData
115
     * @return void
116
     */
117
    protected function setInstallmentDraftDownloadLinks($aInstallmentData)
118
    {
119
        $aDownloadLinks = array();
120
        foreach ($aInstallmentData as $aInstallment) {
121
            $aDownloadLinks[$aInstallment['duration']] = $aInstallment['standardcreditinformationurl'];
122
        }
123
        $this->checkoutSession->setInstallmentDraftLinks($aDownloadLinks);
124
    }
125
126
    /**
127
     * Check responses for errors and add them to the response object if needed
128
     *
129
     * @param  InstallmentPlanResponse $oResponse
130
     * @param  array                   $aResponsePreCheck
131
     * @param  array                   $aResponseCalculation
132
     * @return InstallmentPlanResponse
133
     */
134
    protected function checkForErrors($oResponse, $aResponsePreCheck, $aResponseCalculation)
135
    {
136
        $sErrorMessage = false;
137
        if (isset($aResponsePreCheck['status']) && $aResponsePreCheck['status'] == 'ERROR') {
138
            $sErrorMessage = __($aResponsePreCheck['errorcode'] . ' - ' . $aResponsePreCheck['customermessage']);
139
        } elseif (isset($aResponseCalculation['status']) && $aResponseCalculation['status'] == 'ERROR') {
140
            $sErrorMessage = __($aResponseCalculation['errorcode'] . ' - ' . $aResponseCalculation['customermessage']);
141
        } elseif (!$aResponsePreCheck || (isset($aResponsePreCheck['status']) && $aResponsePreCheck['status'] == 'OK' && !$aResponseCalculation)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $aResponsePreCheck 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...
Bug Best Practice introduced by
The expression $aResponseCalculation 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...
142
            $sErrorMessage = __('An unknown error occurred');
143
        }
144
        if ($sErrorMessage !== false) {
145
            $oResponse->setData('errormessage', $sErrorMessage);
146
        }
147
        return $oResponse;
148
    }
149
150
    /**
151
     * PAYONE addresscheck
152
     * The full class-paths must be given here otherwise the Magento 2 WebApi
153
     * cant handle this with its fake type system!
154
     *
155
     * @param  string $birthday
156
     * @param  string $email
157
     * @return \Payone\Core\Service\V1\Data\InstallmentPlanResponse
158
     */
159
    public function getInstallmentPlan($birthday, $email = false)
160
    {
161
        $oResponse = $this->responseFactory->create();
162
        $oResponse->setData('success', false); // set success to false as default, set to true later if true
163
164
        $oQuote = $this->checkoutSession->getQuote();
165
166
        $aResponsePreCheck = $this->precheck->sendRequest($this->payment, $oQuote, $oQuote->getBaseGrandTotal(), $birthday, $email);
167
        $aResponseCalculation = false;
168
        if (isset($aResponsePreCheck['status']) && $aResponsePreCheck['status'] == 'OK') {
169
            $aResponseCalculation = $this->calculation->sendRequest($this->payment, $oQuote, $oQuote->getBaseGrandTotal());
170
            $aInstallmentData = $this->parseResponse($aResponseCalculation);
171
            if (isset($aResponseCalculation['status']) && $aResponseCalculation['status'] == 'OK' && $aInstallmentData !== false) {
172
                $oResponse->setData('success', true); // set success to false as default, set to true later if true
173
                $this->setInstallmentDraftDownloadLinks($aInstallmentData);
174
                $this->checkoutSession->setInstallmentWorkorderId($aResponseCalculation['workorderid']);
175
176
                $this->block->setInstallmentData($aInstallmentData);
0 ignored issues
show
Documentation Bug introduced by
The method setInstallmentData does not exist on object<Payone\Core\Block...lution\InstallmentPlan>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
177
                $this->block->setCode($this->payment->getCode());
0 ignored issues
show
Documentation Bug introduced by
The method setCode does not exist on object<Payone\Core\Block...lution\InstallmentPlan>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
178
179
                $oResponse->setData('installmentPlanHtml', $this->block->toHtml());
180
            }
181
        }
182
        $oResponse = $this->checkForErrors($oResponse, $aResponsePreCheck, $aResponseCalculation);
0 ignored issues
show
Security Bug introduced by
It seems like $aResponseCalculation defined by false on line 167 can also be of type false; however, Payone\Core\Service\V1\I...tPlan::checkForErrors() does only seem to accept array, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
183
        return $oResponse;
184
    }
185
186
    /**
187
     * @param array $aResponse
188
     * @return array
189
     */
190
    public function getPayDataArray($aResponse)
191
    {
192
        $aPayData = array();
193
        foreach($aResponse as $sKey => $sValue) {
194
            $sCorrectedKey = str_ireplace('add_paydata[', '', $sKey);
195
            $sCorrectedKey = rtrim($sCorrectedKey, ']');
196
            $sCorrectedKey = strtolower($sCorrectedKey);
197
            $sCorrectedKey = str_replace('-', '_', $sCorrectedKey);
198
            $aPayData[$sCorrectedKey] = $sValue;
199
        }
200
201
        ksort($aPayData);
202
        return $aPayData;
203
    }
204
205
    /**
206
     * Parse the response array into a readable array
207
     *
208
     * @param $aResponse
209
     * @return array|false
210
     */
211
    protected function parseResponse($aResponse)
212
    {
213
        $aInstallmentData = array();
214
215
        $aPayData = $this->getPayDataArray($aResponse);
216
        foreach ($aPayData as $sKey => $sValue) {
217
            $aSplit = explode('_', $sKey);
218
            for($i = count($aSplit); $i > 0; $i--) {
219
                if($i == count($aSplit)) {
220
                    $aTmp = array($aSplit[$i-1] => $sValue);
221
                } else {
222
                    $aTmp = array($aSplit[$i-1] => $aTmp);
0 ignored issues
show
Bug introduced by
The variable $aTmp does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
223
                }
224
            }
225
226
            $aInstallmentData = array_replace_recursive($aInstallmentData, $aTmp);
227
        }
228
229
        if(isset($aInstallmentData['paymentdetails']) && count($aInstallmentData['paymentdetails']) > 0) {
230
            return $aInstallmentData['paymentdetails'];
231
        }
232
233
        return false;
234
    }
235
}
236