Completed
Pull Request — master (#1)
by Florian
02:27
created

Api   A

Complexity

Total Complexity 24

Size/Duplication

Total Lines 171
Duplicated Lines 4.09 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 24
c 1
b 0
f 0
lcom 1
cbo 5
dl 7
loc 171
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 12 1
A parseUrl() 0 9 2
A sendApiRequest() 0 20 4
B formatOutputByResponse() 0 17 5
A getRequestUrl() 7 15 4
A addPayoneOrderData() 0 14 4
A isInvoiceDataNeeded() 0 9 4

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\Helper;
28
29
use Payone\Core\Model\PayoneConfig;
30
use Payone\Core\Model\Methods\PayoneMethod;
31
use Magento\Sales\Model\Order as SalesOrder;
32
33
/**
34
 * Helper class for everything that has to do with APIs
35
 *
36
 * @category  Payone
37
 * @package   Payone_Magento2_Plugin
38
 * @author    FATCHIP GmbH <[email protected]>
39
 * @copyright 2003 - 2016 Payone GmbH
40
 * @license   <http://www.gnu.org/licenses/> GNU Lesser General Public License
41
 * @link      http://www.payone.de
42
 */
43
class Api extends \Payone\Core\Helper\Base
44
{
45
    /**
46
     * PAYONE connection curl php
47
     *
48
     * @var \Payone\Core\Helper\Connection\CurlPhp
49
     */
50
    protected $connCurlPhp;
51
52
    /**
53
     * PAYONE connection curl cli
54
     *
55
     * @var \Payone\Core\Helper\Connection\CurlCli
56
     */
57
    protected $connCurlCli;
58
59
    /**
60
     * PAYONE connection fsockopen
61
     *
62
     * @var \Payone\Core\Helper\Connection\Fsockopen
63
     */
64
    protected $connFsockopen;
65
66
    /**
67
     * Constructor
68
     *
69
     * @param \Magento\Framework\App\Helper\Context      $context
70
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
71
     * @param \Payone\Core\Helper\Connection\CurlPhp     $connCurlPhp
72
     * @param \Payone\Core\Helper\Connection\CurlCli     $connCurlCli
73
     * @param \Payone\Core\Helper\Connection\Fsockopen   $connFsockopen
74
     */
75
    public function __construct(
76
        \Magento\Framework\App\Helper\Context $context,
77
        \Magento\Store\Model\StoreManagerInterface $storeManager,
78
        \Payone\Core\Helper\Connection\CurlPhp $connCurlPhp,
79
        \Payone\Core\Helper\Connection\CurlCli $connCurlCli,
80
        \Payone\Core\Helper\Connection\Fsockopen $connFsockopen
81
    ) {
82
        parent::__construct($context, $storeManager);
83
        $this->connCurlPhp = $connCurlPhp;
84
        $this->connCurlCli = $connCurlCli;
85
        $this->connFsockopen = $connFsockopen;
86
    }
87
88
    /**
89
     * @param string $sRequestUrl
90
     * @return array
91
     * @throws \Exception
92
     */
93
    protected function parseUrl($sRequestUrl)
94
    {
95
        $aParsedRequestUrl = parse_url($sRequestUrl);
96
97
        if ($aParsedRequestUrl === false) {
98
            throw new \Exception("Malformed URL " . $sRequestUrl);
99
        }
100
        return $aParsedRequestUrl;
101
    }
102
103
    /**
104
     * Check which communication possibilities are existing and send the request
105
     *
106
     * @param  string $sRequestUrl
107
     * @return array
108
     */
109
    public function sendApiRequest($sRequestUrl)
110
    {
111
        $aParsedRequestUrl = $this->parseUrl($sRequestUrl);
112
113
        $aResponse = [];
0 ignored issues
show
Unused Code introduced by
$aResponse is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
114
        if (function_exists("curl_init")) {
115
            // php native curl exists so we gonna use it for requesting
116
            $aResponse = $this->connCurlPhp->sendCurlPhpRequest($aParsedRequestUrl);
117
        } elseif (file_exists("/usr/local/bin/curl") || file_exists("/usr/bin/curl")) {
118
            // cli version of curl exists on server
119
            $aResponse = $this->connCurlCli->sendCurlCliRequest($aParsedRequestUrl);
120
        } else {
121
            // last resort => via sockets
122
            $aResponse = $this->connFsockopen->sendSocketRequest($aParsedRequestUrl);
123
        }
124
125
        $aResponse = $this->formatOutputByResponse($aResponse);
0 ignored issues
show
Bug introduced by
It seems like $aResponse can also be of type null; however, Payone\Core\Helper\Api::formatOutputByResponse() 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...
126
127
        return $aResponse;
128
    }
129
130
    /**
131
     * Format response to a clean output array
132
     *
133
     * @param  array $aResponse
134
     * @return array
135
     */
136
    protected function formatOutputByResponse($aResponse)
137
    {
138
        $aOutput = [];
139
140
        if (is_array($aResponse)) {// correct response existing?
141
            foreach ($aResponse as $iLinenum => $sLine) {// go through line by line
142
                $iPos = strpos($sLine, "=");
143
                if ($iPos > 0) {// is a "=" as delimiter existing?
144
                    $aOutput[substr($sLine, 0, $iPos)] = trim(substr($sLine, $iPos+1));
145
                } elseif (!empty($sLine)) {// is line not empty?
146
                    $aOutput[$iLinenum] = $sLine;// add the line unedited
147
                }
148
            }
149
        }
150
151
        return $aOutput;
152
    }
153
154
    /**
155
     * Generate the request url out of the params and die api url
156
     *
157
     * @return string
158
     */
159
    public function getRequestUrl($aParameters, $sApiUrl)
160
    {
161
        $sRequestUrl = '';
162
        foreach ($aParameters as $sKey => $mValue) {
163 View Code Duplication
            if (is_array($mValue)) {// might be array
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
164
                foreach ($mValue as $i => $sSubValue) {
165
                    $sRequestUrl .= "&".$sKey."[".$i."]=".urlencode($sSubValue);
166
                }
167
            } else {
168
                $sRequestUrl .= "&".$sKey."=".urlencode($mValue);
169
            }
170
        }
171
        $sRequestUrl = $sApiUrl."?".substr($sRequestUrl, 1);
172
        return $sRequestUrl;
173
    }
174
175
    /**
176
     * Add PAYONE information to the order object to be saved in the DB
177
     *
178
     * @param  SalesOrder $oOrder
179
     * @param  array      $aRequest
180
     * @param  array      $aResponse
181
     * @return void
182
     */
183
    public function addPayoneOrderData(SalesOrder $oOrder, $aRequest, $aResponse)
184
    {
185
        if (isset($aResponse['txid'])) {// txid existing?
186
            $oOrder->setPayoneTxid($aResponse['txid']);// add txid to order entity
187
        }
188
        $oOrder->setPayoneRefnr($aRequest['reference']);// add refnr to order entity
189
        $oOrder->setPayoneAuthmode($aRequest['request']);// add authmode to order entity
190
        $oOrder->setPayoneMode($aRequest['mode']);// add payone mode to order entity
191
        if (isset($aRequest['mandate_identification'])) {// mandate id existing in request?
192
            $oOrder->setPayoneMandateId($aRequest['mandate_identification']);
193
        } elseif (isset($aResponse['mandate_identification'])) {// mandate id existing in response?
194
            $oOrder->setPayoneMandateId($aResponse['mandate_identification']);
195
        }
196
    }
197
198
    /**
199
     * Check if invoice-data has to be added to the authorization request
200
     *
201
     * @param  PayoneMethod $oPayment
202
     * @return bool
203
     */
204
    public function isInvoiceDataNeeded(PayoneMethod $oPayment)
205
    {
206
        $sType = $this->getConfigParam('request_type');// auth or preauth?
207
        $blInvoiceEnabled = (bool)$this->getConfigParam('transmit_enabled', 'invoicing');// invoicing enabled?
208
        if ($oPayment->needsProductInfo() || ($sType == PayoneConfig::REQUEST_TYPE_AUTHORIZATION && $blInvoiceEnabled)) {
209
            return true;// invoice data needed
210
        }
211
        return false;// invoice data not needed
212
    }
213
}
214