SummaryForm   A
last analyzed

Complexity

Total Complexity 14

Size/Duplication

Total Lines 122
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 12

Importance

Changes 0
Metric Value
wmc 14
lcom 1
cbo 12
dl 0
loc 122
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 31 3
B makePayment() 0 46 6
A getPaymentErrorMessage() 0 25 5
1
<?php
2
/**
3
 * SummaryForm.php
4
 *
5
 * @author Bram de Leeuw
6
 * Date: 10/03/17
7
 */
8
9
namespace Broarm\EventTickets;
10
11
use FieldList;
12
use FormAction;
13
use GatewayErrorMessage;
14
use Payment;
15
use RequiredFields;
16
use SilverStripe\Omnipay\GatewayInfo;
17
use TextareaField;
18
19
/**
20
 * Class SummaryForm
21
 *
22
 * @package Broarm\EventTickets
23
 */
24
class SummaryForm extends FormStep
25
{
26
    public function __construct($controller, $name, Reservation $reservation)
27
    {
28
        $fields = FieldList::create(
29
            SummaryField::create('Summary', '', $this->reservation = $reservation, true),
30
            TextareaField::create('Comments', _t('SummaryForm.COMMENTS', 'Comments')),
31
            PaymentGatewayField::create(),
32
            TermsAndConditionsField::create('AgreeToTermsAndConditions')
33
        );
34
35
        $paymentLabel = $reservation->Total == 0
36
            ? _t('ReservationForm.RESERVE', 'Reserve tickets')
37
            : _t('ReservationForm.PAYMENT', 'Continue to payment');
38
39
        $actions = FieldList::create(
40
            FormAction::create('makePayment', $paymentLabel)
41
        );
42
43
        $validator = RequiredFields::create(array(
44
            'AgreeToTermsAndConditions'
45
        ));
46
47
        parent::__construct($controller, $name, $fields, $actions, $validator);
48
49
        // check if there is an error message and show it
50
        if ($error = $this->getPaymentErrorMessage()) {
51
            $this->setMessage($error, 'error');
52
        }
53
54
        // Update the summary form with extra fields
55
        $this->extend('updateSummaryForm');
56
    }
57
58
    /**
59
     * Handle the ticket form registration
60
     *
61
     * @param array $data
62
     * @param SummaryForm $form
63
     * @return \SS_HTTPResponse
64
     * @throws \ValidationException
65
     */
66
    public function makePayment(array $data, SummaryForm $form)
67
    {
68
        // If the summary is changed and email receivers are set
69
        if (isset($data['Summary']) && is_array($data['Summary'])) {
70
            foreach ($data['Summary'] as $attendeeID => $fields) {
71
                $attendee = $form->reservation->Attendees()->find('ID', $attendeeID);
72
                foreach ($fields as $field => $value) {
73
                    $attendee->setField($field, $value);
74
                }
75
                $attendee->write();
76
            }
77
        }
78
79
        $form->saveInto($form->reservation);
80
        // If comments are added
81
        //if (isset($data['Comments'])) {
82
        //    $form->reservation->Comments = $data['Comments'];
83
        //}
84
85
        // Hook trough where optional extra field data can be saved on the reservation
86
        $this->extend('updateReservationBeforePayment', $form->reservation, $data, $form);
87
88
        // Check if there is a payment to process otherwise continue with manual processing
89
        $gateway = $form->reservation->Total > 0
90
            ? $data['Gateway']
91
            : 'Manual';
92
93
        $form->reservation->changeState('PENDING');
94
        $form->reservation->Gateway = $gateway;
95
        $form->reservation->write();
96
97
        $paymentProcessor = PaymentProcessor::create($this->reservation);
98
        $paymentProcessor
99
            ->createPayment($gateway)
100
            ->setSuccessUrl($this->getController()->Link($this->nextStep))
101
            ->setFailureUrl($this->getController()->Link())
102
            ->write();
103
104
        $paymentProcessor->setGateWayData(array(
105
            'transactionId' => $this->reservation->ReservationCode
106
        ));
107
108
        $response = $paymentProcessor->createServiceFactory();
109
        $this->extend('beforeNextStep', $data, $form, $response);
110
        return $response->redirectOrRespond();
111
    }
112
113
114
    /**
115
     * Get the last error message from the payment attempts
116
     *
117
     * @return bool|string
118
     */
119
    public function getPaymentErrorMessage()
120
    {
121
        /** @var Payment $lastPayment */
122
        // Get the last payment
123
        if (!$lastPayment = $this->reservation->Payments()->first()) {
124
            return false;
125
        }
126
127
        // Find the gateway error
128
        $lastErrorMessage = null;
129
        $errorMessages = $lastPayment->Messages()->exclude('Message', '')->sort('Created', 'DESC');
130
        foreach ($errorMessages as $errorMessage) {
131
            if ($errorMessage instanceof GatewayErrorMessage) {
132
                $lastErrorMessage = $errorMessage;
133
                break;
134
            }
135
        }
136
137
        // If no error is found return
138
        if (!$lastErrorMessage) {
139
            return false;
140
        }
141
142
        return _t("{$lastErrorMessage->Gateway}.{$lastErrorMessage->Code}", $lastErrorMessage->Message);
143
    }
144
145
}
146