Completed
Push — master ( 7c1eaa...80d841 )
by Joachim
15:53
created

PaymentController::newAction()   C

Complexity

Conditions 7
Paths 6

Size

Total Lines 98
Code Lines 68

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 98
c 0
b 0
f 0
rs 6.4687
cc 7
eloc 68
nc 6
nop 2

How to fix   Long Method   

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\AltaPay\Payload\CaptureReservation as CaptureReservationPayload;
6
use Loevgaard\AltaPay\Payload\OrderLine as OrderLinePayload;
7
use Loevgaard\AltaPay\Payload\PaymentRequest as PaymentRequestPayload;
8
use Loevgaard\AltaPay\Payload\PaymentRequest\Config as ConfigPayload;
9
use Loevgaard\AltaPay\Payload\PaymentRequest\CustomerInfo as CustomerInfoPayload;
10
use Loevgaard\Dandomain\Pay\Handler;
11
use Loevgaard\DandomainAltapayBundle\Annotation\LogHttpTransaction;
12
use Loevgaard\DandomainAltapayBundle\Entity\Payment;
13
use Loevgaard\DandomainAltapayBundle\Exception\AltapayPaymentRequestException;
14
use Loevgaard\DandomainAltapayBundle\Exception\ChecksumMismatchException;
15
use Loevgaard\DandomainAltapayBundle\Exception\PaymentException;
16
use Loevgaard\DandomainAltapayBundle\Exception\TerminalNotFoundException;
17
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
18
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
19
use Symfony\Bridge\PsrHttpMessage\Factory\DiactorosFactory;
20
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
21
use Symfony\Component\HttpFoundation\RedirectResponse;
22
use Symfony\Component\HttpFoundation\Request;
23
use Symfony\Component\HttpFoundation\Response;
24
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
25
26
/**
27
 * @Route("/payment")
28
 */
29
class PaymentController extends Controller
30
{
31
    /**
32
     * @Method("GET")
33
     * @Route("", name="loevgaard_dandomain_altapay_payment_index")
34
     *
35
     * @param Request $request
36
     *
37
     * @return Response
38
     */
39
    public function indexAction(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...
40
    {
41
        $paymentManager = $this->container->get('loevgaard_dandomain_altapay.payment_manager');
42
43
        /** @var Payment[] $payments */
44
        $payments = $paymentManager->getRepository()->findAll();
45
46
        return $this->render('@LoevgaardDandomainAltapay/payment/index.html.twig', [
47
            'payments' => $payments,
48
        ]);
49
    }
50
51
    /**
52
     * Payment flow
53
     * 1. The Dandomain payment API POSTs to this page with the terminal slug in the URL
54
     * 2. After validating all input, we create a payment request to the Altapay API
55
     * 3. Finally we redirect the user to the URL given by the Altapay API.
56
     *
57
     * @Method("POST")
58
     * @Route("/{terminal}", name="loevgaard_dandomain_altapay_payment_new")
59
     *
60
     * @LogHttpTransaction()
61
     *
62
     * @param $terminal
63
     * @param Request $request
64
     *
65
     * @return RedirectResponse
66
     *
67
     * @throws PaymentException
68
     */
69
    public function newAction($terminal, Request $request)
70
    {
71
        $terminalManager = $this->container->get('loevgaard_dandomain_altapay.terminal_manager');
72
        $paymentManager = $this->container->get('loevgaard_dandomain_altapay.payment_manager');
73
74
        // convert symfony request to PSR7 request
75
        $psr7Factory = new DiactorosFactory();
76
        $psrRequest = $psr7Factory->createRequest($request);
77
78
        $handler = new Handler(
79
            $psrRequest,
80
            $this->container->getParameter('loevgaard_dandomain_altapay.shared_key_1'),
81
            $this->container->getParameter('loevgaard_dandomain_altapay.shared_key_2')
82
        );
83
84
        $dandomainPaymentRequest = $handler->getPaymentRequest();
85
86
        $paymentEntity = $paymentManager->createPaymentFromDandomainPaymentRequest($dandomainPaymentRequest);
87
        $paymentManager->update($paymentEntity);
88
89
        $terminalEntity = $terminalManager->findTerminalBySlug($terminal, true);
90
        if (!$terminalEntity) {
91
            throw TerminalNotFoundException::create('Terminal `'.$terminal.'` does not exist', $request, $paymentEntity);
92
        }
93
94
        if (!$handler->checksumMatches()) {
95
            throw ChecksumMismatchException::create('Checksum mismatch. Try again', $request, $paymentEntity);
96
        }
97
98
        $paymentRequestPayload = new PaymentRequestPayload(
99
            $terminalEntity->getTitle(),
100
            $dandomainPaymentRequest->getOrderId(),
101
            $dandomainPaymentRequest->getTotalAmount(),
102
            $dandomainPaymentRequest->getCurrencySymbol()
103
        );
104
105
        foreach ($dandomainPaymentRequest->getPaymentLines() as $paymentLine) {
106
            $orderLinePayload = new OrderLinePayload(
107
                $paymentLine->getName(),
108
                $paymentLine->getProductNumber(),
109
                $paymentLine->getQuantity(),
110
                $paymentLine->getPrice()
111
            );
112
            $orderLinePayload->setTaxPercent($paymentLine->getVat());
113
114
            $paymentRequestPayload->addOrderLine($orderLinePayload);
115
        }
116
117
        $customerInfoPayload = new CustomerInfoPayload();
118
        $customerNames = explode(' ', $dandomainPaymentRequest->getCustomerName(), 2);
119
        $shippingNames = explode(' ', $dandomainPaymentRequest->getDeliveryName(), 2);
120
        $customerInfoPayload
121
            ->setBillingFirstName($customerNames[0] ?? '')
122
            ->setBillingLastName($customerNames[1] ?? '')
123
            ->setBillingAddress(
124
                $dandomainPaymentRequest->getCustomerAddress().
125
                ($dandomainPaymentRequest->getCustomerAddress2() ? "\r\n".$dandomainPaymentRequest->getCustomerAddress2() : '')
126
            )
127
            ->setBillingPostal($dandomainPaymentRequest->getCustomerZipCode())
128
            ->setBillingCity($dandomainPaymentRequest->getCustomerCity())
129
            ->setBillingCountry($dandomainPaymentRequest->getCustomerCountry())
130
            ->setShippingFirstName($shippingNames[0] ?? '')
131
            ->setShippingLastName($shippingNames[1] ?? '')
132
            ->setShippingAddress(
133
                $dandomainPaymentRequest->getDeliveryAddress().
134
                ($dandomainPaymentRequest->getDeliveryAddress2() ? "\r\n".$dandomainPaymentRequest->getDeliveryAddress2() : '')
135
            )
136
            ->setShippingPostal($dandomainPaymentRequest->getDeliveryZipCode())
137
            ->setShippingCity($dandomainPaymentRequest->getDeliveryCity())
138
            ->setShippingCountry($dandomainPaymentRequest->getDeliveryCountry())
139
        ;
140
        $paymentRequestPayload->setCustomerInfo($customerInfoPayload);
141
142
        $configPayload = new ConfigPayload();
143
        $configPayload
144
            ->setCallbackForm($this->generateUrl('loevgaard_dandomain_altapay_callback_form', [], UrlGeneratorInterface::ABSOLUTE_URL))
145
            ->setCallbackOk($this->generateUrl('loevgaard_dandomain_altapay_callback_ok', [], UrlGeneratorInterface::ABSOLUTE_URL))
146
            ->setCallbackFail($this->generateUrl('loevgaard_dandomain_altapay_callback_fail', [], UrlGeneratorInterface::ABSOLUTE_URL))
147
            ->setCallbackRedirect($this->generateUrl('loevgaard_dandomain_altapay_callback_redirect', [], UrlGeneratorInterface::ABSOLUTE_URL))
148
            ->setCallbackOpen($this->generateUrl('loevgaard_dandomain_altapay_callback_open', [], UrlGeneratorInterface::ABSOLUTE_URL))
149
            ->setCallbackNotification($this->generateUrl('loevgaard_dandomain_altapay_callback_notification', [], UrlGeneratorInterface::ABSOLUTE_URL))
150
        ;
151
        $paymentRequestPayload->setConfig($configPayload);
152
153
        $paymentRequestPayload
154
            ->setCookiePart($this->getParameter('loevgaard_dandomain_altapay.cookie_payment_id'), $paymentEntity->getId())
155
            ->setCookiePart($this->getParameter('loevgaard_dandomain_altapay.cookie_checksum_complete'), $handler->getChecksum2())
156
        ;
157
158
        $altapay = $this->container->get('loevgaard_dandomain_altapay.altapay_client');
159
        $response = $altapay->createPaymentRequest($paymentRequestPayload);
160
161
        if (!$response->isSuccessful()) {
162
            throw AltapayPaymentRequestException::create('An error occured during payment request. Try again. Message from gateway: '.$response->getErrorMessage(), $request, $paymentEntity);
163
        }
164
165
        return new RedirectResponse($response->getUrl());
166
    }
167
168
    /**
169
     * @Method("POST")
170
     * @Route("/{paymentId}/capture", name="loevgaard_dandomain_altapay_payment_capture")
171
     *
172
     * @param int     $paymentId
173
     * @param Request $request
174
     *
175
     * @return RedirectResponse
176
     */
177
    public function captureAction(int $paymentId, Request $request)
178
    {
179
        $paymentManager = $this->get('loevgaard_dandomain_altapay.payment_manager');
180
181
        /** @var Payment $payment */
182
        $payment = $paymentManager->getRepository()->find($paymentId);
183
184
        if ($payment) {
185
            $altapayClient = $this->get('loevgaard_dandomain_altapay.altapay_client');
186
187
            $payload = new CaptureReservationPayload();
0 ignored issues
show
Bug introduced by
The call to CaptureReservation::__construct() misses a required argument $transactionId.

This check looks for function calls that miss required arguments.

Loading history...
188
            $res = $altapayClient->captureReservation($payload);
189
190
            if ($res->isSuccessful()) {
191
                $this->addFlash('success', 'The payment for order '.$payment->getOrderId().' was captured.'); // @todo fix translation
192
            } else {
193
                $this->addFlash('danger', 'An error occurred during capture of the payment: '.$res->getErrorMessage()); // @todo fix translation
194
            }
195
        }
196
197
        $redirect = $request->headers->get('referer') ? $request->headers->get('referer') : $this->generateUrl('loevgaard_dandomain_altapay_payment_index');
198
199
        return $this->redirect($redirect);
200
    }
201
}
202