VoidAuthorizeResponse::__construct()   C
last analyzed

Complexity

Conditions 14
Paths 96

Size

Total Lines 72
Code Lines 47

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 14
eloc 47
c 1
b 0
f 1
nc 96
nop 2
dl 0
loc 72
rs 6.2666

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Omnipay\Redsys\Message;
6
7
use AvaiBookSports\Component\RedsysMessages\Exception\CatalogNotFoundException;
8
use AvaiBookSports\Component\RedsysMessages\Factory;
9
use AvaiBookSports\Component\RedsysMessages\Loader\CatalogLoader;
10
use Http\Discovery\MessageFactoryDiscovery;
11
use Omnipay\Common\Exception\InvalidResponseException;
12
use Omnipay\Common\Http\Exception\RequestException;
13
use Omnipay\Common\Message\RequestInterface;
14
15
class VoidAuthorizeResponse extends AbstractResponse
16
{
17
    protected $returnSignature;
18
19
    /** @var bool */
20
    protected $usingUpcaseResponse = false;
21
22
    /** @var CatalogInterface */
0 ignored issues
show
Bug introduced by
The type Omnipay\Redsys\Message\CatalogInterface 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...
23
    protected $redsysMessages;
24
25
    public function __construct(RequestInterface $request, $data)
26
    {
27
        parent::__construct($request, $data);
28
29
        $security = new Security();
30
31
        try {
32
            $this->redsysMessages = (new Factory(new CatalogLoader()))->createCatalogByLanguage(array_key_exists('language', $this->request->getParameters()) ? $this->request->getParameters()['language'] : 'en');
0 ignored issues
show
Documentation Bug introduced by
It seems like new AvaiBookSports\Compo...s()['language'] : 'en') of type AvaiBookSports\Component...ssages\CatalogInterface is incompatible with the declared type Omnipay\Redsys\Message\CatalogInterface of property $redsysMessages.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
33
        } catch (CatalogNotFoundException $e) {
34
            $this->redsysMessages = (new Factory(new CatalogLoader()))->createCatalogByLanguage('en');
35
        }
36
37
        if (!isset($data['CODIGO'])) {
38
            throw new InvalidResponseException('Invalid response from payment gateway (no data)');
39
        }
40
41
        if (!isset($data['OPERACION'])) {
42
            if ('0' == $data['CODIGO']) {
43
                throw new InvalidResponseException('Invalid response from payment gateway (no data)');
44
            }
45
        }
46
47
        // Exceeder API rate limit
48
        if ('SIS0295' == $data['CODIGO'] || '9295' == $data['CODIGO']) {
49
            throw new RequestException('Too many requests. "'.$data['CODIGO'].'"', MessageFactoryDiscovery::find()->createRequest('POST', $this->getRequest()->getEndpoint(), ['SOAPAction' => 'trataPeticion']));
0 ignored issues
show
Bug introduced by
The method getEndpoint() does not exist on Omnipay\Common\Message\RequestInterface. It seems like you code against a sub-type of Omnipay\Common\Message\RequestInterface such as Omnipay\Redsys\Message\AbstractRequest. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

49
            throw new RequestException('Too many requests. "'.$data['CODIGO'].'"', MessageFactoryDiscovery::find()->createRequest('POST', $this->getRequest()->/** @scrutinizer ignore-call */ getEndpoint(), ['SOAPAction' => 'trataPeticion']));
Loading history...
50
        }
51
52
        if (isset($data['OPERACION']['DS_ORDER'])) {
53
            $this->usingUpcaseResponse = true;
54
        }
55
56
        if (!empty($data['OPERACION'])) {
57
            if (!empty($data['OPERACION']['Ds_CardNumber'])) {
58
                $signature_keys = [
59
                    'Ds_Amount',
60
                    'Ds_Order',
61
                    'Ds_MerchantCode',
62
                    'Ds_Currency',
63
                    'Ds_Response',
64
                    'Ds_CardNumber',
65
                    'Ds_TransactionType',
66
                    'Ds_SecurePayment',
67
                ];
68
            } else {
69
                $signature_keys = [
70
                    'Ds_Amount',
71
                    'Ds_Order',
72
                    'Ds_MerchantCode',
73
                    'Ds_Currency',
74
                    'Ds_Response',
75
                    'Ds_TransactionType',
76
                    'Ds_SecurePayment',
77
                ];
78
            }
79
80
            $signature_data = '';
81
            foreach ($signature_keys as $key) {
82
                $value = $this->getKey($key);
83
                if (null === $value) {
84
                    throw new InvalidResponseException('Invalid response from payment gateway (missing data)');
85
                }
86
                $signature_data .= $value;
87
            }
88
89
            $this->returnSignature = $security->createSignature(
90
                $signature_data,
91
                $this->getKey('Ds_Order'),
92
                $this->request->getHmacKey()
0 ignored issues
show
Bug introduced by
The method getHmacKey() does not exist on Omnipay\Common\Message\RequestInterface. It seems like you code against a sub-type of Omnipay\Common\Message\RequestInterface such as Omnipay\Redsys\Message\AbstractRequest. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

92
                $this->request->/** @scrutinizer ignore-call */ 
93
                                getHmacKey()
Loading history...
93
            );
94
95
            if ($this->returnSignature != $this->getKey('Ds_Signature')) {
96
                throw new InvalidResponseException('Invalid response from payment gateway (signature mismatch)');
97
            }
98
        }
99
    }
100
101
    /**
102
     * @return bool
103
     */
104
    public function isSuccessful()
105
    {
106
        $response_code = $this->getKey('Ds_Response');
107
108
        // check for field existence as well as value
109
        return isset($this->data['CODIGO'])
110
            && '0' == $this->data['CODIGO']
111
            && null !== $response_code
112
            && is_numeric($response_code)
113
            && 400 == $response_code;
114
    }
115
116
    /**
117
     * Helper method to get a specific response parameter if available.
118
     *
119
     * @param string $key The key to look up
120
     *
121
     * @return mixed|null
122
     */
123
    protected function getKey($key)
124
    {
125
        if ($this->usingUpcaseResponse) {
126
            $key = strtoupper($key);
127
        }
128
129
        return isset($this->data['OPERACION'][$key]) ? $this->data['OPERACION'][$key] : null;
130
    }
131
132
    /**
133
     * Get the authorisation code if available.
134
     *
135
     * @return string|null
136
     */
137
    public function getTransactionReference()
138
    {
139
        return $this->getAuthorisationCode() ?? $this->request->getParameters()['transactionId'];
140
    }
141
142
    /**
143
     * Get the merchant message if available.
144
     *
145
     * @return string|null A response message from the payment gateway
146
     */
147
    public function getMessage()
148
    {
149
        $message = $this->redsysMessages->getDsResponseMessage($this->getCode());
150
151
        if (null === $message) {
152
            $message = $this->redsysMessages->getErrorMessage($this->getCode());
153
        }
154
155
        return $message;
156
    }
157
158
    /**
159
     * Get the merchant response code if available.
160
     *
161
     * @return string|null
162
     */
163
    public function getCode()
164
    {
165
        $code = $this->getKey('Ds_Response');
166
167
        if (null === $code) {
168
            $code = $this->data['CODIGO'];
169
        }
170
171
        return $code;
172
    }
173
174
    /**
175
     * Get the merchant data if available.
176
     *
177
     * @return string|null
178
     */
179
    public function getMerchantData()
180
    {
181
        return $this->getKey('Ds_MerchantData');
182
    }
183
184
    /**
185
     * Get the card country if available.
186
     *
187
     * @return string|null ISO 3166-1 (3-digit numeric) format, if supplied
188
     */
189
    public function getCardCountry()
190
    {
191
        return $this->getKey('Ds_Card_Country');
192
    }
193
}
194