CheckoutComponentValidator   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 25
dl 0
loc 48
rs 10
c 0
b 0
f 0
wmc 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A fieldHasError() 0 10 4
A php() 0 26 5
1
<?php
2
3
namespace SilverShop\Forms;
4
5
use SilverShop\Checkout\CheckoutComponentConfig;
6
use SilverStripe\Forms\RequiredFields;
7
use SilverStripe\ORM\ValidationException;
8
9
/**
10
 * Order validator makes sure everything is set correctly
11
 * and in place before an order can be placed.
12
 */
13
class CheckoutComponentValidator extends RequiredFields
14
{
15
    protected $config;
16
17
    public function __construct(CheckoutComponentConfig $config)
18
    {
19
        $this->config = $config;
20
        parent::__construct($this->config->getRequiredFields());
21
    }
22
23
    public function php($data)
24
    {
25
        $valid = parent::php($data);
26
        //do component validation
27
        try {
28
            $this->config->validateData($data);
29
        } catch (ValidationException $e) {
30
            $result = $e->getResult();
31
            foreach ($result->getMessages() as $message) {
32
                if (!$this->fieldHasError($message['fieldName'])) {
33
                    $this->validationError($message['fieldName'], $message['message'], 'bad');
34
                }
35
            }
36
            $valid = false;
37
        }
38
        if (!$valid) {
39
            $this->form->sessionMessage(
40
                _t(
41
                    __CLASS__ . ".InvalidDataMessage",
42
                    "There are problems with the data you entered. See below:"
43
                ),
44
                "bad"
45
            );
46
        }
47
48
        return $valid;
49
    }
50
51
    public function fieldHasError($field)
52
    {
53
        if ($this->getErrors()) {
54
            foreach ($this->getErrors() as $error) {
55
                if ($error['fieldName'] === $field) {
56
                    return true;
57
                }
58
            }
59
        }
60
        return false;
61
    }
62
}
63