CallbackController::okAction()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 11
rs 9.4285
cc 1
eloc 6
nc 1
nop 1
1
<?php
2
3
namespace Loevgaard\DandomainAltapayBundle\Controller;
4
5
use Loevgaard\AltaPay\Callback\Xml as XmlCallback;
6
use Loevgaard\AltaPay\Entity\Transaction;
7
use Loevgaard\DandomainAltapayBundle\Annotation\LogHttpTransaction;
8
use Loevgaard\DandomainAltapayBundle\Entity\Payment;
9
use Loevgaard\DandomainAltapayBundle\Entity\PaymentRepository;
10
use Loevgaard\DandomainAltapayBundle\Entity\SiteSetting;
11
use Loevgaard\DandomainAltapayBundle\Exception\CallbackException;
12
use Loevgaard\DandomainAltapayBundle\Exception\NotAllowedIpException;
13
use Loevgaard\DandomainAltapayBundle\Exception\PaymentException;
14
use Loevgaard\DandomainAltapayBundle\PsrHttpMessage\DiactorosTrait;
15
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
16
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
17
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
18
use Symfony\Component\HttpFoundation\RedirectResponse;
19
use Symfony\Component\HttpFoundation\Request;
20
use Symfony\Component\HttpFoundation\Response;
21
22
/**
23
 * @Route("/callback")
24
 */
25
class CallbackController extends Controller
26
{
27
    use DiactorosTrait;
28
29
    /**
30
     * @Method("POST")
31
     * @Route("/form", name="loevgaard_dandomain_altapay_callback_form")
32
     *
33
     * @LogHttpTransaction()
34
     *
35
     * @param Request $request
36
     * @throws CallbackException
37
     * @throws PaymentException
38
     *
39
     * @return Response
40
     */
41 View Code Duplication
    public function formAction(Request $request)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
42
    {
43
        $payment = $this->handleCallback($request);
44
        $siteSettings = $this->getSiteSettings($payment);
45
46
        return $this->render('@LoevgaardDandomainAltapay/callback/form.html.twig', [
47
            'payment' => $payment,
48
            'siteSettings' => $siteSettings,
49
        ]);
50
    }
51
52
    /**
53
     * @Method("POST")
54
     * @Route("/ok", name="loevgaard_dandomain_altapay_callback_ok")
55
     *
56
     * @LogHttpTransaction()
57
     *
58
     * @param Request $request
59
     * @throws CallbackException
60
     * @throws PaymentException
61
     * @return RedirectResponse
62
     */
63
    public function okAction(Request $request)
64
    {
65
        $payment = $this->handleCallback($request);
66
67
        $url = $payment->getFullCallBackOkUrl()
68
            .'&PayApiCompleteOrderChecksum='.$request->cookies->getAlnum(
69
                $this->getParameter('loevgaard_dandomain_altapay.cookie_checksum_complete')
70
            );
71
72
        return $this->redirect($url);
73
    }
74
75
    /**
76
     * @Method("POST")
77
     * @Route("/fail", name="loevgaard_dandomain_altapay_callback_fail")
78
     *
79
     * @LogHttpTransaction()
80
     *
81
     * @param Request $request
82
     * @throws CallbackException
83
     * @throws PaymentException
84
     * @return Response
85
     */
86
    public function failAction(Request $request)
87
    {
88
        $payment = $this->handleCallback($request);
89
        $siteSettings = $this->getSiteSettings($payment);
90
91
        $redirect = $payment->getReferrer();
92
        if (!$redirect) {
93
            $redirect = 'http://'.$payment->getCallBackServerUrl();
94
        }
95
96
        return $this->render('@LoevgaardDandomainAltapay/callback/fail.html.twig', [
97
            'payment' => $payment,
98
            'siteSettings' => $siteSettings,
99
            'redirect' => $redirect
100
        ]);
101
    }
102
103
    /**
104
     * @Method("POST")
105
     * @Route("/redirect", name="loevgaard_dandomain_altapay_callback_redirect")
106
     *
107
     * @LogHttpTransaction()
108
     *
109
     * @param Request $request
110
     * @throws CallbackException
111
     * @throws PaymentException
112
     * @return Response
113
     */
114 View Code Duplication
    public function redirectAction(Request $request)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
115
    {
116
        $payment = $this->handleCallback($request);
117
        $siteSettings = $this->getSiteSettings($payment);
118
119
        return $this->render('@LoevgaardDandomainAltapay/callback/redirect.html.twig', [
120
            'payment' => $payment,
121
            'siteSettings' => $siteSettings,
122
        ]);
123
    }
124
125
    /**
126
     * @Method("POST")
127
     * @Route("/open", name="loevgaard_dandomain_altapay_callback_open")
128
     *
129
     * @LogHttpTransaction()
130
     *
131
     * @param Request $request
132
     * @throws CallbackException
133
     * @throws PaymentException
134
     * @return Response
135
     */
136 View Code Duplication
    public function openAction(Request $request)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
137
    {
138
        $payment = $this->handleCallback($request);
139
        $siteSettings = $this->getSiteSettings($payment);
140
141
        return $this->render('@LoevgaardDandomainAltapay/callback/open.html.twig', [
142
            'payment' => $payment,
143
            'siteSettings' => $siteSettings,
144
        ]);
145
    }
146
147
    /**
148
     * @Method("POST")
149
     * @Route("/notification", name="loevgaard_dandomain_altapay_callback_notification")
150
     *
151
     * @LogHttpTransaction()
152
     *
153
     * @param Request $request
154
     * @throws CallbackException
155
     * @throws PaymentException
156
     * @return Response
157
     */
158
    public function notificationAction(Request $request)
159
    {
160
        $this->handleCallback($request);
161
162
        return new Response('OK');
163
    }
164
165
    /**
166
     * @Method("POST")
167
     * @Route("/verify-order", name="loevgaard_dandomain_altapay_callback_verify_order")
168
     *
169
     * @LogHttpTransaction()
170
     *
171
     * @param Request $request
172
     * @throws CallbackException
173
     * @throws PaymentException
174
     * @return Response
175
     */
176
    public function verifyOrderAction(Request $request)
177
    {
178
        $this->handleCallback($request);
179
180
        return new Response('OK');
181
    }
182
183
    /**
184
     * @param Request $request
185
     *
186
     * @return Payment
187
     *
188
     * @throws CallbackException
189
     * @throws PaymentException
190
     */
191
    protected function handleCallback(Request $request)
192
    {
193
        $payment = $this->getPaymentFromRequest($request);
194
        $callbackFactory = $this->get('loevgaard_dandomain_altapay.altapay_callback_factory');
195
196
        $psrRequest = $this->createPsrRequest($request);
197
        $callback = $callbackFactory->create($psrRequest);
198
199
        if ($callback instanceof XmlCallback) {
200
            $transactions = $callback->getTransactions();
201
            if (isset($transactions[0])) {
202
                /** @var Transaction $transaction */
203
                $transaction = $transactions[0];
204
205
                $paymentRepository = $this->getPaymentRepository();
206
207
                $payment
208
                    ->setAltapayId($transaction->getPaymentId())
209
                    ->setCardStatus($transaction->getCardStatus())
210
                    ->setCreditCardToken($transaction->getCreditCardToken())
211
                    ->setCreditCardMaskedPan($transaction->getCreditCardMaskedPan())
212
                    ->setThreeDSecureResult($transaction->getThreeDSecureResult())
213
                    ->setLiableForChargeback($transaction->getLiableForChargeback())
214
                    ->setBlacklistToken($transaction->getBlacklistToken())
215
                    ->setShop($transaction->getShop())
216
                    ->setTerminal($transaction->getTerminal())
217
                    ->setTransactionStatus($transaction->getTransactionStatus())
218
                    ->setReasonCode($transaction->getReasonCode())
219
                    ->setMerchantCurrency($transaction->getMerchantCurrency())
220
                    ->setMerchantCurrencyAlpha($transaction->getMerchantCurrencyAlpha())
221
                    ->setCardHolderCurrency($transaction->getCardHolderCurrency())
222
                    ->setCardHolderCurrencyAlpha($transaction->getCardHolderCurrencyAlpha())
223
                    ->setReservedAmount($transaction->getReservedAmount())
0 ignored issues
show
Bug introduced by
It seems like $transaction->getReservedAmount() can be null; however, setReservedAmount() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
224
                    ->setCapturedAmount($transaction->getCapturedAmount())
0 ignored issues
show
Bug introduced by
It seems like $transaction->getCapturedAmount() can be null; however, setCapturedAmount() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
225
                    ->setRefundedAmount($transaction->getRefundedAmount())
0 ignored issues
show
Bug introduced by
It seems like $transaction->getRefundedAmount() can be null; however, setRefundedAmount() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
226
                    ->setRecurringDefaultAmount($transaction->getRecurringDefaultAmount())
0 ignored issues
show
Bug introduced by
It seems like $transaction->getRecurringDefaultAmount() can be null; however, setRecurringDefaultAmount() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
227
                    ->setCreatedDate($transaction->getCreatedDate())
228
                    ->setUpdatedDate($transaction->getUpdatedDate())
229
                    ->setPaymentNature($transaction->getPaymentNature())
230
                    ->setSupportsRefunds($transaction->getPaymentNatureService()->isSupportsRefunds())
231
                    ->setSupportsRelease($transaction->getPaymentNatureService()->isSupportsRelease())
232
                    ->setSupportsMultipleCaptures($transaction->getPaymentNatureService()->isSupportsMultipleCaptures())
233
                    ->setSupportsMultipleRefunds($transaction->getPaymentNatureService()->isSupportsMultipleRefunds())
234
                    ->setFraudRiskScore($transaction->getFraudRiskScore())
235
                    ->setFraudExplanation($transaction->getFraudExplanation())
236
                ;
237
238
                $paymentRepository->persist($payment);
239
                $paymentRepository->flush();
240
            }
241
        }
242
243
        $allowedIps = $this->container->getParameter('loevgaard_dandomain_altapay.altapay_ips');
244
        if ('prod' === $this->container->get('kernel')->getEnvironment() && !in_array($request->getClientIp(), $allowedIps)) {
245
            throw NotAllowedIpException::create('IP `'.$request->getClientIp().'` is not an allowed IP.', $request, $payment);
246
        }
247
248
        return $payment;
249
    }
250
251
    /**
252
     * @param Request $request
253
     *
254
     * @return Payment
255
     *
256
     * @throws CallbackException
257
     */
258
    protected function getPaymentFromRequest(Request $request)
259
    {
260
        $paymentId = $request->cookies->getInt($this->getParameter('loevgaard_dandomain_altapay.cookie_payment_id'));
261
        $paymentRepository = $this->getPaymentRepository();
262
263
        /** @var Payment $payment */
264
        $payment = $paymentRepository->find($paymentId);
265
266
        if (!$payment) {
267
            throw new CallbackException('Payment '.$paymentId.' does not exist');
268
        }
269
270
        return $payment;
271
    }
272
273
    /**
274
     * @return PaymentRepository
275
     */
276
    protected function getPaymentRepository()
277
    {
278
        return $this->container->get('loevgaard_dandomain_altapay.payment_repository');
279
    }
280
281
    /**
282
     * @param Payment $payment
283
     * @return SiteSetting[]
284
     */
285
    protected function getSiteSettings(Payment $payment) : array
286
    {
287
        return $this
288
            ->get('loevgaard_dandomain_altapay.site_settings_provider')
289
            ->findBySiteIdIndexedBySetting($payment->getLanguageId());
290
    }
291
}
292