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

Api::sendApiRequest()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 24
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 24
rs 8.5125
c 0
b 0
f 0
cc 5
eloc 13
nc 4
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 - 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
     * Check which communication possibilities are existing and send the request
90
     *
91
     * @param  string $sRequestUrl
92
     * @return array
93
     */
94
    public function sendApiRequest($sRequestUrl)
95
    {
96
        $aParsedRequestUrl = parse_url($sRequestUrl);
97
98
        if ($aParsedRequestUrl === false) {
99
            throw new \Exception("Malformed URL " . $sRequestUrl);
100
        }
101
102
        $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...
103
        if (function_exists("curl_init")) {
104
            // php native curl exists so we gonna use it for requesting
105
            $aResponse = $this->connCurlPhp->sendCurlPhpRequest($aParsedRequestUrl);
106
        } elseif (file_exists("/usr/local/bin/curl") || file_exists("/usr/bin/curl")) {
107
            // cli version of curl exists on server
108
            $aResponse = $this->connCurlCli->sendCurlCliRequest($aParsedRequestUrl);
109
        } else {
110
            // last resort => via sockets
111
            $aResponse = $this->connFsockopen->sendSocketRequest($aParsedRequestUrl);
112
        }
113
114
        $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...
115
116
        return $aResponse;
117
    }
118
119
    /**
120
     * Format response to a clean output array
121
     *
122
     * @param  array $aResponse
123
     * @return array
124
     */
125
    protected function formatOutputByResponse($aResponse)
126
    {
127
        $aOutput = [];
128
129
        if (is_array($aResponse)) {// correct response existing?
130
            foreach ($aResponse as $iLinenum => $sLine) {// go through line by line
131
                $iPos = strpos($sLine, "=");
132
                if ($iPos > 0) {// is a "=" as delimiter existing?
133
                    $aOutput[substr($sLine, 0, $iPos)] = trim(substr($sLine, $iPos+1));
134
                } elseif (!empty($sLine)) {// is line not empty?
135
                    $aOutput[$iLinenum] = $sLine;// add the line unedited
136
                }
137
            }
138
        }
139
140
        return $aOutput;
141
    }
142
143
    /**
144
     * Generate the request url out of the params and die api url
145
     *
146
     * @return string
147
     */
148
    public function getRequestUrl($aParameters, $sApiUrl)
149
    {
150
        $sRequestUrl = '';
151
        foreach ($aParameters as $sKey => $mValue) {
152 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...
153
                foreach ($mValue as $i => $sSubValue) {
154
                    $sRequestUrl .= "&".$sKey."[".$i."]=".urlencode($sSubValue);
155
                }
156
            } else {
157
                $sRequestUrl .= "&".$sKey."=".urlencode($mValue);
158
            }
159
        }
160
        $sRequestUrl = $sApiUrl."?".substr($sRequestUrl, 1);
161
        return $sRequestUrl;
162
    }
163
164
    /**
165
     * Add PAYONE information to the order object to be saved in the DB
166
     *
167
     * @param  SalesOrder $oOrder
168
     * @param  array      $aRequest
169
     * @param  array      $aResponse
170
     * @return void
171
     */
172
    public function addPayoneOrderData(SalesOrder $oOrder, $aRequest, $aResponse)
173
    {
174
        if (isset($aResponse['txid'])) {// txid existing?
175
            $oOrder->setPayoneTxid($aResponse['txid']);// add txid to order entity
176
        }
177
        $oOrder->setPayoneRefnr($aRequest['reference']);// add refnr to order entity
178
        $oOrder->setPayoneAuthmode($aRequest['request']);// add authmode to order entity
179
        $oOrder->setPayoneMode($aRequest['mode']);// add payone mode to order entity
180
        if (isset($aRequest['mandate_identification'])) {// mandate id existing in request?
181
            $oOrder->setPayoneMandateId($aRequest['mandate_identification']);
182
        } elseif (isset($aResponse['mandate_identification'])) {// mandate id existing in response?
183
            $oOrder->setPayoneMandateId($aResponse['mandate_identification']);
184
        }
185
    }
186
187
    /**
188
     * Check if invoice-data has to be added to the authorization request
189
     *
190
     * @param  PayoneMethod $oPayment
191
     * @return bool
192
     */
193
    public function isInvoiceDataNeeded(PayoneMethod $oPayment)
194
    {
195
        $sType = $this->getConfigParam('request_type');// auth or preauth?
196
        $blInvoiceEnabled = (bool)$this->getConfigParam('transmit_enabled', 'invoicing');// invoicing enabled?
197
        if ($oPayment->needsProductInfo() || ($sType == PayoneConfig::REQUEST_TYPE_AUTHORIZATION && $blInvoiceEnabled)) {
198
            return true;// invoice data needed
199
        }
200
        return false;// invoice data not needed
201
    }
202
}
203