Completed
Push — master ( 1154fb...96c712 )
by Bram
01:51
created

SummaryForm::makePayment()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 46
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 46
rs 8.4751
c 0
b 0
f 0
cc 6
eloc 26
nc 4
nop 2
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
    /**
27
     * @var Reservation
28
     */
29
    protected $reservation;
30
31
    public function __construct($controller, $name, Reservation $reservation)
32
    {
33
        $fields = FieldList::create(
34
            SummaryField::create('Summary', '', $this->reservation = $reservation, true),
35
            TextareaField::create('Comments', _t('SummaryForm.COMMENTS', 'Comments')),
36
            PaymentGatewayField::create(),
37
            TermsAndConditionsField::create('AgreeToTermsAndConditions')
38
        );
39
40
        $actions = FieldList::create(
41
            FormAction::create('makePayment', _t('ReservationForm.PAYMENT', 'Continue to payment'))
42
        );
43
44
        $validator = RequiredFields::create(array(
45
            'AgreeToTermsAndConditions'
46
        ));
47
48
        parent::__construct($controller, $name, $fields, $actions, $validator);
49
50
        // check if there is an error message and show it
51
        if ($error = $this->getPaymentErrorMessage()) {
52
            $this->setMessage($error, 'error');
53
        }
54
55
        // Update the summary form with extra fields
56
        $this->extend('updateSummaryForm');
57
    }
58
59
    /**
60
     * Handle the ticket form registration
61
     *
62
     * @param array       $data
63
     * @param SummaryForm $form
64
     *
65
     * @return string
66
     */
67
    public function makePayment(array $data, SummaryForm $form)
68
    {
69
        // If the summary is changed and email receivers are set
70
        if (isset($data['Summary']) && is_array($data['Summary'])) {
71
            foreach ($data['Summary'] as $attendeeID => $fields) {
72
                $attendee = $form->reservation->Attendees()->find('ID', $attendeeID);
73
                foreach ($fields as $field => $value) {
74
                    $attendee->setField($field, $value);
75
                }
76
                $attendee->write();
77
            }
78
        }
79
80
        $form->saveInto($form->reservation);
81
        // If comments are added
82
        //if (isset($data['Comments'])) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
85% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
83
        //    $form->reservation->Comments = $data['Comments'];
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
84
        //}
85
86
        // Hook trough where optional extra field data can be saved on the reservation
87
        $this->extend('updateReservationBeforePayment', $form->reservation, $data, $form);
88
89
        // Check if there is a payment to process otherwise continue with manual processing
90
        $gateway = $form->reservation->Total > 0
91
            ? $data['Gateway']
92
            : 'Manual';
93
94
        $form->reservation->changeState('PENDING');
95
        $form->reservation->Gateway = $gateway;
96
        $form->reservation->write();
97
98
        $paymentProcessor = PaymentProcessor::create($this->reservation);
99
        $paymentProcessor
100
            ->createPayment($gateway)
101
            ->setSuccessUrl($this->getController()->Link($this->nextStep))
0 ignored issues
show
Unused Code introduced by
The call to Controller::Link() has too many arguments starting with $this->nextStep.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
102
            ->setFailureUrl($this->getController()->Link())
103
            ->write();
104
105
        $paymentProcessor->setGateWayData(array(
106
            'transactionId' => $this->reservation->ReservationCode
107
        ));
108
109
        $response = $paymentProcessor->createServiceFactory();
110
        $this->extend('beforeNextStep', $data, $form, $response);
111
        return $response->redirectOrRespond();
112
    }
113
114
115
    /**
116
     * Get the last error message from the payment attempts
117
     *
118
     * @return bool|string
119
     */
120
    public function getPaymentErrorMessage()
121
    {
122
        /** @var Payment $lastPayment */
123
        // Get the last payment
124
        if (!$lastPayment = $this->reservation->Payments()->first()) {
125
            return false;
126
        }
127
128
        // Find the gateway error
129
        $lastErrorMessage = null;
130
        $errorMessages = $lastPayment->Messages()->exclude('Message', '')->sort('Created', 'DESC');
131
        foreach ($errorMessages as $errorMessage) {
132
            if ($errorMessage instanceof GatewayErrorMessage) {
133
                $lastErrorMessage = $errorMessage;
134
                break;
135
            }
136
        }
137
138
        // If no error is found return
139
        if (!$lastErrorMessage) {
140
            return false;
141
        }
142
143
        return _t("{$lastErrorMessage->Gateway}.{$lastErrorMessage->Code}", $lastErrorMessage->Message);
144
    }
145
146
}