GridFieldDeleteRelationsValidator::php()   B
last analyzed

Complexity

Conditions 10
Paths 24

Size

Total Lines 43
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 10
eloc 24
c 3
b 0
f 0
nc 24
nop 1
dl 0
loc 43
rs 7.6666

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Signify\Forms\Validators;
4
5
use Signify\Forms\GridField\GridFieldDeleteRelationsButton;
6
use SilverStripe\Forms\Validator;
7
8
class GridFieldDeleteRelationsValidator extends Validator
9
{
10
    public function php($data)
11
    {
12
        $valid = true;
13
        $filters = array();
14
        // Check for checked filter checkboxes.
15
        foreach ($data as $key => $value) {
16
            if (preg_match('/' . GridFieldDeleteRelationsButton::FILTER_BY_SUFFIX . '$/', $key) && $value) {
17
                $filters[] = $key;
18
            }
19
        }
20
21
        // If the delete all checkbox is checked, no other filters can be checked.
22
        if (!empty($filters) && !empty($data[GridFieldDeleteRelationsButton::DELETE_ALL])) {
23
            $message = _t(
24
                GridFieldDeleteRelationsButton::class . '.VALIDATION_TooManyFilters',
25
                'A filter checkbox and "Delete all" cannot be checked simultaneously.'
26
            );
27
            $filters[] = GridFieldDeleteRelationsButton::DELETE_ALL;
28
            foreach ($filters as $fieldName) {
29
                $this->validationError($fieldName, $message);
30
            }
31
            $valid = false;
32
        }
33
34
        // At least one checkbox must be checked.
35
        if (empty($filters) && empty($data[GridFieldDeleteRelationsButton::DELETE_ALL])) {
36
            $message = _t(
37
                GridFieldDeleteRelationsButton::class . '.VALIDATION_RequireFilters',
38
                'At least one filter checkbox or "Delete all" must be checked.'
39
            );
40
            $this->validationError(GridFieldDeleteRelationsButton::DELETE_ALL, $message);
41
            $valid = false;
42
        }
43
44
        // Add a message to the form itself.
45
        if (!$valid) {
46
            $this->validationError('', _t(
47
                GridFieldDeleteRelationsButton::class . '.VALIDATION_FormMessage',
48
                'Please correct the validation errors.'
49
            ));
50
        }
51
52
        return $valid;
53
    }
54
}
55