Completed
Pull Request — master (#647)
by Robbie
64:39 queued 62:36
created

Validator   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 3
dl 0
loc 62
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A setRecord() 0 5 1
A getRecord() 0 4 1
B php() 0 33 6
1
<?php
2
3
namespace SilverStripe\UserForms\Model\EditableFormField;
4
5
use SilverStripe\Forms\RequiredFields;
6
use SilverStripe\UserForms\Model\EditableCustomRule;
7
8
class Validator extends RequiredFields
9
{
10
    /**
11
     *
12
     * @var EditableFormField
13
     */
14
    protected $record = null;
15
16
    /**
17
     *
18
     * @param EditableFormField $record
19
     * @return $this
20
     */
21
    public function setRecord($record)
22
    {
23
        $this->record = $record;
24
        return $this;
25
    }
26
27
    /*
28
     * @return EditableFormField
29
     */
30
    public function getRecord()
31
    {
32
        return $this->record;
33
    }
34
35
36
    public function php($data)
37
    {
38
        if (!parent::php($data)) {
39
            return false;
40
        }
41
42
        // Skip unsaved records
43
        if (!$this->record || !$this->record->exists()) {
44
            return true;
45
        }
46
47
        // Skip validation if not required
48
        if (empty($data['Required'])) {
49
            return;
50
        }
51
52
        // Skip validation if no rules
53
        $count = EditableCustomRule::get()->filter('ParentID', $this->record->ID)->count();
54
        if ($count == 0) {
55
            return true;
56
        }
57
58
        // Both required = true and rules > 0 should error
59
        $this->validationError(
60
            'Required_Error',
61
            _t(
62
                __CLASS__.'.REQUIRED_ERROR',
63
                'Form fields cannot be required and have conditional display rules.'
64
            ),
65
            'error'
66
        );
67
        return false;
68
    }
69
}
70