Completed
Push — master ( e0d2a4...2983b4 )
by Joachim
15:21
created

LabelController   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 164
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 4
dl 0
loc 164
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A indexAction() 0 12 1
A showAction() 0 11 2
C newAction() 0 101 7
1
<?php
2
3
namespace Loevgaard\DandomainAltapayBundle\Controller;
4
5
use Loevgaard\PakkelabelsBundle\Entity\Label;
6
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
7
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
8
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
9
use Symfony\Component\HttpFoundation\RedirectResponse;
10
use Symfony\Component\HttpFoundation\Request;
11
use Symfony\Component\HttpFoundation\Response;
12
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
13
14
/**
15
 * @Route("/label")
16
 */
17
class LabelController extends Controller
18
{
19
    /**
20
     * @Method("GET")
21
     * @Route("", name="loevgaard_pakkelabels_label_index")
22
     *
23
     * @param Request $request
24
     *
25
     * @return Response
26
     */
27
    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...
28
    {
29
        /** @var Label[] $labels */
30
        $labels = $this->get('doctrine')
31
            ->getManager()
32
            ->getRepository('LoevgaardPakkelabelsBundle:Label')
33
            ->findAll();
34
35
        return $this->render('@LoevgaardPakkelabels/payment/index.html.twig', [
36
            'labels' => $labels,
37
        ]);
38
    }
39
40
    /**
41
     * @Method("GET")
42
     * @Route("/{paymentId}/show", name="loevgaard_pakkelabels_payment_show")
43
     *
44
     * @param int     $paymentId
45
     * @param Request $request
46
     *
47
     * @return Response
48
     */
49
    public function showAction(int $paymentId, 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...
50
    {
51
        $payment = $this->getPaymentFromId($paymentId);
0 ignored issues
show
Bug introduced by
The method getPaymentFromId() does not seem to exist on object<Loevgaard\Dandoma...roller\LabelController>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
52
        if(!$payment) {
53
            throw $this->createNotFoundException('Payment with id `'.$paymentId.'` not found');
54
        }
55
56
        return $this->render('@LoevgaardDandomainAltapay/payment/show.html.twig', [
57
            'payment' => $payment,
58
        ]);
59
    }
60
61
    /**
62
     * Payment flow
63
     * 1. The Dandomain payment API POSTs to this page with the terminal slug in the URL
64
     * 2. After validating all input, we create a payment request to the Altapay API
65
     * 3. Finally we redirect the user to the URL given by the Altapay API.
66
     *
67
     * @Method("POST")
68
     * @Route("/{terminal}", name="loevgaard_pakkelabels_payment_new")
69
     *
70
     * @LogHttpTransaction()
71
     *
72
     * @param $terminal
73
     * @param Request $request
74
     *
75
     * @return RedirectResponse
76
     *
77
     * @throws PaymentException
78
     */
79
    public function newAction($terminal, Request $request)
80
    {
81
        $terminalManager = $this->container->get('loevgaard_pakkelabels.terminal_manager');
82
        $paymentManager = $this->container->get('loevgaard_pakkelabels.payment_manager');
83
84
        // convert symfony request to PSR7 request
85
        $psr7Factory = new DiactorosFactory();
86
        $psrRequest = $psr7Factory->createRequest($request);
87
88
        $handler = new Handler(
89
            $psrRequest,
90
            $this->container->getParameter('loevgaard_pakkelabels.shared_key_1'),
91
            $this->container->getParameter('loevgaard_pakkelabels.shared_key_2')
92
        );
93
94
        $dandomainPaymentRequest = $handler->getPaymentRequest();
95
96
        $paymentEntity = $paymentManager->createPaymentFromDandomainPaymentRequest($dandomainPaymentRequest);
97
        $paymentManager->update($paymentEntity);
98
99
        $terminalEntity = $terminalManager->findTerminalBySlug($terminal, true);
100
        if (!$terminalEntity) {
101
            // @todo fix translation
102
            throw TerminalNotFoundException::create('Terminal `'.$terminal.'` does not exist', $request, $paymentEntity);
103
        }
104
105
        if (!$handler->checksumMatches()) {
106
            // @todo fix translation
107
            throw ChecksumMismatchException::create('Checksum mismatch. Try again', $request, $paymentEntity);
108
        }
109
110
        $paymentRequestPayload = new PaymentRequestPayload(
111
            $terminalEntity->getTitle(),
112
            $dandomainPaymentRequest->getOrderId(),
113
            $dandomainPaymentRequest->getTotalAmount(),
114
            $dandomainPaymentRequest->getCurrencySymbol()
115
        );
116
117
        foreach ($dandomainPaymentRequest->getPaymentLines() as $paymentLine) {
118
            $orderLinePayload = new OrderLinePayload(
119
                $paymentLine->getName(),
120
                $paymentLine->getProductNumber(),
121
                $paymentLine->getQuantity(),
122
                $paymentLine->getPrice()
123
            );
124
            $orderLinePayload->setTaxPercent($paymentLine->getVat());
125
126
            $paymentRequestPayload->addOrderLine($orderLinePayload);
127
        }
128
129
        $customerInfoPayload = new CustomerInfoPayload();
130
        $customerNames = explode(' ', $dandomainPaymentRequest->getCustomerName(), 2);
131
        $shippingNames = explode(' ', $dandomainPaymentRequest->getDeliveryName(), 2);
132
        $customerInfoPayload
133
            ->setBillingFirstName($customerNames[0] ?? '')
134
            ->setBillingLastName($customerNames[1] ?? '')
135
            ->setBillingAddress(
136
                $dandomainPaymentRequest->getCustomerAddress().
137
                ($dandomainPaymentRequest->getCustomerAddress2() ? "\r\n".$dandomainPaymentRequest->getCustomerAddress2() : '')
138
            )
139
            ->setBillingPostal($dandomainPaymentRequest->getCustomerZipCode())
140
            ->setBillingCity($dandomainPaymentRequest->getCustomerCity())
141
            ->setBillingCountry($dandomainPaymentRequest->getCustomerCountry())
142
            ->setShippingFirstName($shippingNames[0] ?? '')
143
            ->setShippingLastName($shippingNames[1] ?? '')
144
            ->setShippingAddress(
145
                $dandomainPaymentRequest->getDeliveryAddress().
146
                ($dandomainPaymentRequest->getDeliveryAddress2() ? "\r\n".$dandomainPaymentRequest->getDeliveryAddress2() : '')
147
            )
148
            ->setShippingPostal($dandomainPaymentRequest->getDeliveryZipCode())
149
            ->setShippingCity($dandomainPaymentRequest->getDeliveryCity())
150
            ->setShippingCountry($dandomainPaymentRequest->getDeliveryCountry())
151
        ;
152
        $paymentRequestPayload->setCustomerInfo($customerInfoPayload);
153
154
        $configPayload = new ConfigPayload();
155
        $configPayload
156
            ->setCallbackForm($this->generateUrl('loevgaard_pakkelabels_callback_form', [], UrlGeneratorInterface::ABSOLUTE_URL))
157
            ->setCallbackOk($this->generateUrl('loevgaard_pakkelabels_callback_ok', [], UrlGeneratorInterface::ABSOLUTE_URL))
158
            ->setCallbackFail($this->generateUrl('loevgaard_pakkelabels_callback_fail', [], UrlGeneratorInterface::ABSOLUTE_URL))
159
            ->setCallbackRedirect($this->generateUrl('loevgaard_pakkelabels_callback_redirect', [], UrlGeneratorInterface::ABSOLUTE_URL))
160
            ->setCallbackOpen($this->generateUrl('loevgaard_pakkelabels_callback_open', [], UrlGeneratorInterface::ABSOLUTE_URL))
161
            ->setCallbackNotification($this->generateUrl('loevgaard_pakkelabels_callback_notification', [], UrlGeneratorInterface::ABSOLUTE_URL))
162
        ;
163
        $paymentRequestPayload->setConfig($configPayload);
164
165
        $paymentRequestPayload
166
            ->setCookiePart($this->getParameter('loevgaard_pakkelabels.cookie_payment_id'), $paymentEntity->getId())
167
            ->setCookiePart($this->getParameter('loevgaard_pakkelabels.cookie_checksum_complete'), $handler->getChecksum2())
168
        ;
169
170
        $altapay = $this->container->get('loevgaard_pakkelabels.altapay_client');
171
        $response = $altapay->createPaymentRequest($paymentRequestPayload);
172
173
        if (!$response->isSuccessful()) {
174
            // @todo fix translation
175
            throw AltapayPaymentRequestException::create('An error occured during payment request. Try again. Message from gateway: '.$response->getErrorMessage(), $request, $paymentEntity);
176
        }
177
178
        return new RedirectResponse($response->getUrl());
179
    }
180
}
181