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

Validator::php()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 33
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 33
rs 8.439
c 0
b 0
f 0
cc 6
eloc 17
nc 5
nop 1
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