Payment::getFormFields()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 21
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 13
nc 4
nop 1
dl 0
loc 21
rs 9.8333
c 0
b 0
f 0
1
<?php
2
3
namespace SilverShop\Checkout\Component;
4
5
use SilverShop\Checkout\Checkout;
6
use SilverShop\Model\Order;
7
use SilverStripe\Forms\FieldList;
8
use SilverStripe\Forms\HiddenField;
9
use SilverStripe\Forms\OptionsetField;
10
use SilverStripe\Omnipay\GatewayInfo;
11
use SilverStripe\ORM\ValidationException;
12
use SilverStripe\ORM\ValidationResult;
13
14
class Payment extends CheckoutComponent
15
{
16
    public function getFormFields(Order $order)
17
    {
18
        $fields = FieldList::create();
19
        $gateways = GatewayInfo::getSupportedGateways();
20
        if (count($gateways) > 1) {
21
            $fields->push(
22
                OptionsetField::create(
23
                    'PaymentMethod',
24
                    _t("SilverShop\Checkout\CheckoutField.PaymentType", "Payment Type"),
25
                    $gateways,
26
                    array_keys($gateways)
27
                )
28
            );
29
        }
30
        if (count($gateways) == 1) {
31
            $fields->push(
32
                HiddenField::create('PaymentMethod')->setValue(key($gateways))
33
            );
34
        }
35
36
        return $fields;
37
    }
38
39
    public function getRequiredFields(Order $order)
40
    {
41
        if (count(GatewayInfo::getSupportedGateways()) > 1) {
42
            return [];
43
        }
44
45
        return ['PaymentMethod'];
46
    }
47
48
    public function validateData(Order $order, array $data)
49
    {
50
        $result = ValidationResult::create();
51
        if (!isset($data['PaymentMethod'])) {
52
            $result->addError(
53
                _t(__CLASS__ . '.NoPaymentMethod', "Payment method not provided"),
54
                "PaymentMethod"
55
            );
56
            throw new ValidationException($result);
57
        }
58
        $methods = GatewayInfo::getSupportedGateways();
59
        if (!isset($methods[$data['PaymentMethod']])) {
60
            $result->addError(_t(__CLASS__ . '.UnsupportedGateway', "Gateway not supported"), "PaymentMethod");
61
            throw new ValidationException($result);
62
        }
63
    }
64
65
    public function getData(Order $order)
66
    {
67
        return [
68
            'PaymentMethod' => Checkout::get($order)->getSelectedPaymentMethod(),
69
        ];
70
    }
71
72
    public function setData(Order $order, array $data)
73
    {
74
        if (isset($data['PaymentMethod'])) {
75
            Checkout::get($order)->setPaymentMethod($data['PaymentMethod']);
76
        }
77
    }
78
}
79