Completed
Push — master ( 80d841...fb8f6f )
by Joachim
01:55
created

CallbackController::handleCallback()   F

Complexity

Conditions 22
Paths 552

Size

Total Lines 95
Code Lines 65

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 95
rs 2.5574
c 0
b 0
f 0
cc 22
eloc 65
nc 552
nop 1

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 Loevgaard\DandomainAltapayBundle\Controller;
4
5
use Loevgaard\DandomainAltapayBundle\Annotation\LogHttpTransaction;
6
use Loevgaard\DandomainAltapayBundle\Entity\Payment;
7
use Loevgaard\DandomainAltapayBundle\Exception\CallbackException;
8
use Loevgaard\DandomainAltapayBundle\Exception\NotAllowedIpException;
9
use Loevgaard\DandomainAltapayBundle\Exception\PaymentException;
10
use Loevgaard\DandomainAltapayBundle\Manager\PaymentManager;
11
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
12
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
13
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
14
use Symfony\Component\HttpFoundation\Request;
15
use Symfony\Component\HttpFoundation\Response;
16
17
/**
18
 * @Route("/callback")
19
 */
20
class CallbackController extends Controller
21
{
22
    /**
23
     * @Method("POST")
24
     * @Route("/form", name="loevgaard_dandomain_altapay_callback_form")
25
     *
26
     * @LogHttpTransaction()
27
     *
28
     * @param Request $request
29
     *
30
     * @return Response
31
     */
32
    public function formAction(Request $request)
33
    {
34
        $payment = $this->handleCallback($request);
35
36
        return $this->render('@LoevgaardDandomainAltapay/callback/form.html.twig', [
37
            'payment' => $payment,
38
        ]);
39
    }
40
41
    /**
42
     * @Method("POST")
43
     * @Route("/ok", name="loevgaard_dandomain_altapay_callback_ok")
44
     *
45
     * @LogHttpTransaction()
46
     *
47
     * @param Request $request
48
     *
49
     * @return Response
50
     */
51
    public function okAction(Request $request)
52
    {
53
        $payment = $this->handleCallback($request);
0 ignored issues
show
Unused Code introduced by
$payment 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...
54
55
        return $this->render('@LoevgaardDandomainAltapay/callback/ok.html.twig');
56
    }
57
58
    /**
59
     * @Method("POST")
60
     * @Route("/fail", name="loevgaard_dandomain_altapay_callback_fail")
61
     *
62
     * @LogHttpTransaction()
63
     *
64
     * @param Request $request
65
     *
66
     * @return Response
67
     */
68
    public function failAction(Request $request)
69
    {
70
        $payment = $this->handleCallback($request);
0 ignored issues
show
Unused Code introduced by
$payment 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...
71
72
        return $this->render('@LoevgaardDandomainAltapay/callback/fail.html.twig');
73
    }
74
75
    /**
76
     * @Method("POST")
77
     * @Route("/redirect", name="loevgaard_dandomain_altapay_callback_redirect")
78
     *
79
     * @LogHttpTransaction()
80
     *
81
     * @param Request $request
82
     *
83
     * @return Response
84
     */
85
    public function redirectAction(Request $request)
86
    {
87
        $payment = $this->handleCallback($request);
0 ignored issues
show
Unused Code introduced by
$payment 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...
88
89
        return $this->render('@LoevgaardDandomainAltapay/callback/redirect.html.twig');
90
    }
91
92
    /**
93
     * @Method("POST")
94
     * @Route("/open", name="loevgaard_dandomain_altapay_callback_open")
95
     *
96
     * @LogHttpTransaction()
97
     *
98
     * @param Request $request
99
     *
100
     * @return Response
101
     */
102
    public function openAction(Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
103
    {
104
        return $this->render('@LoevgaardDandomainAltapay/callback/open.html.twig');
105
    }
106
107
    /**
108
     * @Method("POST")
109
     * @Route("/notification", name="loevgaard_dandomain_altapay_callback_notification")
110
     *
111
     * @LogHttpTransaction()
112
     *
113
     * @param Request $request
114
     *
115
     * @return Response
116
     */
117
    public function notificationAction(Request $request)
118
    {
119
        $payment = $this->handleCallback($request);
0 ignored issues
show
Unused Code introduced by
$payment 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...
120
121
        return new Response('OK');
122
    }
123
124
    /**
125
     * @Method("POST")
126
     * @Route("/verify-order", name="loevgaard_dandomain_altapay_callback_verify_order")
127
     *
128
     * @LogHttpTransaction()
129
     *
130
     * @param Request $request
131
     *
132
     * @return Response
133
     */
134
    public function verifyOrderAction(Request $request)
135
    {
136
        $payment = $this->handleCallback($request);
0 ignored issues
show
Unused Code introduced by
$payment 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...
137
138
        return new Response('OK');
139
    }
140
141
    /**
142
     * @param Request $request
143
     *
144
     * @return Payment
145
     *
146
     * @throws PaymentException
147
     */
148
    protected function handleCallback(Request $request)
149
    {
150
        $payment = $this->getPaymentFromRequest($request);
151
152
        // @todo this should be placed somewhere in the altapay php sdk
153
        $transaction = null;
154
155
        if($request->request->has('xml')) {
156
            $xml = new \SimpleXMLElement($request->request->get('xml'));
157
            if(isset($xml->Body->Transactions->Transaction) && !empty($xml->Body->Transactions->Transaction)) {
158
                foreach ($xml->Body->Transactions->Transaction as $transactionXml) {
159
                    $transaction = $transactionXml;
160
                    break;
161
                }
162
            }
163
        }
164
165
        if($transaction) {
166
            $paymentManager = $this->getPaymentManager();
167
168
            $createdDate = \DateTime::createFromFormat('Y-m-d H:i:s', $transaction->CreatedDate);
169
            if($createdDate === false) {
170
                $createdDate = null;
171
            }
172
173
            $updatedDate = \DateTime::createFromFormat('Y-m-d H:i:s', $transaction->UpdatedDate);
174
            if($updatedDate === false) {
175
                $updatedDate = null;
176
            }
177
178
            $supportsRefunds = $supportsRelease = $supportsMultipleCaptures = $supportsMultipleRefunds = null;
179
            if(isset($transaction->PaymentNatureService)) {
180
                if(isset($transaction->PaymentNatureService->SupportsRefunds)) {
181
                    $supportsRefunds = (string)$transaction->PaymentNatureService->SupportsRefunds === 'true';
182
                }
183
184
                if(isset($transaction->PaymentNatureService->SupportsRelease)) {
185
                    $supportsRelease = (string)$transaction->PaymentNatureService->SupportsRelease === 'true';
186
                }
187
188
                if(isset($transaction->PaymentNatureService->SupportsMultipleCaptures)) {
189
                    $supportsMultipleCaptures = (string)$transaction->PaymentNatureService->SupportsMultipleCaptures === 'true';
190
                }
191
192
                if(isset($transaction->PaymentNatureService->SupportsMultipleRefunds)) {
193
                    $supportsMultipleRefunds = (string)$transaction->PaymentNatureService->SupportsMultipleRefunds === 'true';
194
                }
195
            }
196
197
            $payment
198
                ->setAltapayId($transaction->PaymentId ?? null)
199
                ->setCardStatus($transaction->CardStatus ?? null)
200
                ->setCreditCardToken($transaction->CreditCardToken ?? null)
201
                ->setCreditCardMaskedPan($transaction->CreditCardMaskedPan ?? null)
202
                ->setThreeDSecureResult($transaction->ThreeDSecureResult ?? null)
203
                ->setLiableForChargeback($transaction->LiableForChargeback ?? null)
204
                ->setBlacklistToken($transaction->BlacklistToken ?? null)
205
                ->setShop($transaction->Shop ?? null)
206
                ->setTerminal($transaction->Terminal ?? null)
207
                ->setTransactionStatus($transaction->TransactionStatus ?? null)
208
                ->setReasonCode($transaction->ReasonCode ?? null)
209
                ->setMerchantCurrency(isset($transaction->MerchantCurrency) ? (int)$transaction->MerchantCurrency : null)
210
                ->setMerchantCurrencyAlpha($transaction->MerchantCurrencyAlpha ?? null)
211
                ->setCardHolderCurrency(isset($transaction->CardHolderCurrency) ? (int)$transaction->CardHolderCurrency : null)
212
                ->setCardHolderCurrencyAlpha($transaction->CardHolderCurrencyAlpha ?? null)
213
                ->setReservedAmount(isset($transaction->ReservedAmount) ? (float)$transaction->ReservedAmount : null)
214
                ->setCapturedAmount(isset($transaction->CapturedAmount) ? (float)$transaction->CapturedAmount : null)
215
                ->setRefundedAmount(isset($transaction->RefundedAmount) ? (float)$transaction->RefundedAmount : null)
216
                ->setRecurringDefaultAmount(isset($transaction->RecurringDefaultAmount) ? (float)$transaction->RecurringDefaultAmount : null)
217
                ->setCreatedDate($createdDate)
218
                ->setUpdatedDate($updatedDate)
219
                ->setPaymentNature($transaction->PaymentNature ?? null)
220
                ->setSupportsRefunds($supportsRefunds)
221
                ->setSupportsRelease($supportsRelease)
222
                ->setSupportsMultipleCaptures($supportsMultipleCaptures)
223
                ->setSupportsMultipleRefunds($supportsMultipleRefunds)
224
                ->setFraudRiskScore(isset($transaction->FraudRiskScore) ? (float)$transaction->FraudRiskScore : null)
225
                ->setFraudExplanation($transaction->FraudExplanation ?? null)
226
            ;
227
            $paymentManager->update($payment);
228
        }
229
230
        $callbackManager = $this->container->get('loevgaard_dandomain_altapay.callback_manager');
231
        $callback = $callbackManager->createCallbackFromRequest($request);
232
        $callback->setPayment($payment);
233
234
        $callbackManager->update($callback);
235
236
        $allowedIps = $this->container->getParameter('loevgaard_dandomain_altapay.altapay_ips');
237
        if ('prod' === $this->container->get('kernel')->getEnvironment() && !in_array($request->getClientIp(), $allowedIps)) {
238
            throw NotAllowedIpException::create('IP `'.$request->getClientIp().'` is not an allowed IP.', $request, $payment);
239
        }
240
241
        return $payment;
242
    }
243
244
    /**
245
     * @param Request $request
246
     *
247
     * @return Payment
248
     *
249
     * @throws CallbackException
250
     */
251
    protected function getPaymentFromRequest(Request $request)
252
    {
253
        $paymentId = $request->cookies->getInt($this->getParameter('loevgaard_dandomain_altapay.cookie_payment_id'));
254
        $paymentManager = $this->getPaymentManager();
255
256
        /** @var Payment $payment */
257
        $payment = $paymentManager->getRepository()->find($paymentId);
258
259
        if (!$payment) {
260
            throw new CallbackException('Payment '.$paymentId.' does not exist');
261
        }
262
263
        return $payment;
264
    }
265
266
    /**
267
     * Add a callback request to the payment for logging purposes.
268
     *
269
     * @param Payment $payment
270
     * @param Request $request
271
     */
272
    protected function logCallback($payment, Request $request)
273
    {
274
        $callbackManager = $this->container->get('loevgaard_dandomain_altapay.callback_manager');
275
        $callback = $callbackManager->create();
276
        $callback->setPayment($payment)
277
            ->setRequest((string) $request);
278
279
        $callbackManager->update($callback);
280
    }
281
282
    /**
283
     * @return PaymentManager
284
     */
285
    protected function getPaymentManager()
286
    {
287
        return $this->container->get('loevgaard_dandomain_altapay.payment_manager');
288
    }
289
}
290