RefundResponse::__construct()   C
last analyzed

Complexity

Conditions 14
Paths 96

Size

Total Lines 72
Code Lines 47

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 47
CRAP Score 14.0423

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 14
eloc 47
c 1
b 0
f 0
nc 96
nop 2
dl 0
loc 72
ccs 47
cts 50
cp 0.94
crap 14.0423
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
namespace Omnipay\Redsys\Message;
4
5
use AvaiBookSports\Component\RedsysMessages\Exception\CatalogNotFoundException;
6
use AvaiBookSports\Component\RedsysMessages\Factory;
7
use AvaiBookSports\Component\RedsysMessages\Loader\CatalogLoader;
8
use Http\Discovery\MessageFactoryDiscovery;
9
use Omnipay\Common\Exception\InvalidResponseException;
10
use Omnipay\Common\Http\Exception\RequestException;
11
use Omnipay\Common\Message\RequestInterface;
12
13
/**
14
 * Redsys Purchase Response.
15
 */
16
class RefundResponse extends AbstractResponse
17
{
18
    /** @var string */
19
    protected $returnSignature;
20
21
    /** @var bool */
22
    protected $usingUpcaseResponse = false;
23
24
    /** @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...
25
    protected $redsysMessages;
26
27
    /**
28
     * Constructor.
29
     *
30
     * @param RequestInterface $request the initiating request
31
     * @param mixed            $data
32
     *
33
     * @throws InvalidResponseException If resopnse format is incorrect, data is missing, or signature does not match
34
     */
35
    public function __construct(RequestInterface $request, $data)
36 9
    {
37
        parent::__construct($request, $data);
38 9
39
        $security = new Security();
40 9
41
        try {
42
            $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...
43 9
        } catch (CatalogNotFoundException $e) {
44 9
            $this->redsysMessages = (new Factory(new CatalogLoader()))->createCatalogByLanguage('en');
45 1
        }
46
47
        if (!isset($data['CODIGO'])) {
48 9
            throw new InvalidResponseException('Invalid response from payment gateway (no data)');
49
        }
50
51
        if (!isset($data['OPERACION'])) {
52 9
            if ('0' == $data['CODIGO']) {
53 3
                throw new InvalidResponseException('Invalid response from payment gateway (no data)');
54
            }
55
        }
56 3
57
        // Exceeder API rate limit
58
        if ('SIS0295' == $data['CODIGO'] || '9295' == $data['CODIGO']) {
59 9
            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

59
            throw new RequestException('Too many requests. "'.$data['CODIGO'].'"', MessageFactoryDiscovery::find()->createRequest('POST', $this->getRequest()->/** @scrutinizer ignore-call */ getEndpoint(), ['SOAPAction' => 'trataPeticion']));
Loading history...
60 1
        }
61
62
        if (isset($data['OPERACION']['DS_ORDER'])) {
63 8
            $this->usingUpcaseResponse = true;
64 1
        }
65 1
66
        if (!empty($data['OPERACION'])) {
67 8
            if (!empty($data['OPERACION']['Ds_CardNumber'])) {
68 6
                $signature_keys = [
69
                    'Ds_Amount',
70 1
                    'Ds_Order',
71 1
                    'Ds_MerchantCode',
72 1
                    'Ds_Currency',
73 1
                    'Ds_Response',
74 1
                    'Ds_CardNumber',
75 1
                    'Ds_TransactionType',
76 1
                    'Ds_SecurePayment',
77 1
                ];
78 1
            } else {
79 1
                $signature_keys = [
80
                    'Ds_Amount',
81 5
                    'Ds_Order',
82 5
                    'Ds_MerchantCode',
83 5
                    'Ds_Currency',
84 5
                    'Ds_Response',
85 5
                    'Ds_TransactionType',
86 5
                    'Ds_SecurePayment',
87 5
                ];
88 5
            }
89
90
            $signature_data = '';
91 6
            foreach ($signature_keys as $key) {
92 6
                $value = $this->getKey($key);
93 6
                if (null === $value) {
94 6
                    throw new InvalidResponseException('Invalid response from payment gateway (missing data)');
95
                }
96
                $signature_data .= $value;
97 6
            }
98 6
99
            $this->returnSignature = $security->createSignature(
100 6
                $signature_data,
101 6
                $this->getKey('Ds_Order'),
102 6
                $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

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