AbstractRule::allowEmptyValue()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 5
rs 10
1
<?php
2
3
namespace Kontrolio\Rules;
4
5
/**
6
 * Validation rule base class.
7
 *
8
 * @package Kontrolio\Rules
9
 */
10
abstract class AbstractRule implements RuleInterface
11
{
12
    /**
13
     * Empty allowed/disallowed state.
14
     *
15
     * @var bool
16
     */
17
    protected $emptyAllowed = false;
18
19
    /**
20
     * Validation violations.
21
     *
22
     * @var array
23
     */
24
    protected $violations = [];
25
26
    /**
27
     * Constructs a rule allowing empty input by default.
28
     *
29
     *
30
     * @return $this
31
     */
32
    public static function allowingEmptyValue()
33
    {
34
        return (new static)->allowEmptyValue();
35
    }
36
37
    /**
38
     * Returns validation rule identifier.
39
     *
40
     * @return string
41
     */
42
    public function getName()
43
    {
44
        $class = get_class($this);
45
        $segments = explode('\\', $class);
46
        $name = end($segments);
47
48
        if (!ctype_lower($name)) {
49
            $name = preg_replace('/\s+/u', '', $name);
50
            $name = mb_strtolower(preg_replace('/(.)(?=[A-Z])/u', '$1_', $name), 'UTF-8');
51
        }
52
53
        $postfix = strrpos($name, '_rule');
54
55
        if ($postfix !== false) {
56
            $name = substr($name, 0, $postfix);
57
        }
58
59
        return $name;
60
    }
61
62
    /**
63
     * When true, validation will be bypassed if validated value is null or an empty string.
64
     *
65
     * @return bool
66
     */
67
    public function emptyValueAllowed()
68
    {
69
        return $this->emptyAllowed;
70
    }
71
72
    /**
73
     * Allows bypassing validation when value is null or an empty string.
74
     *
75
     * @return $this
76
     */
77
    public function allowEmptyValue()
78
    {
79
        $this->emptyAllowed = true;
80
        
81
        return $this;
82
    }
83
84
    /**
85
     * When simply true or some conditions return true, informs validator service that validation can be skipped.
86
     *
87
     * @param mixed $input
88
     *
89
     * @return bool
90
     */
91
    public function canSkipValidation($input = null)
92
    {
93
        return false;
94
    }
95
96
    /**
97
     * Checks whether validation rule has any violations.
98
     *
99
     * @return bool
100
     */
101
    public function hasViolations()
102
    {
103
        return count($this->violations) > 0;
104
    }
105
106
    /**
107
     * Returns validation rule violations.
108
     *
109
     * @return array
110
     */
111
    public function getViolations()
112
    {
113
        return $this->violations;
114
    }
115
}
116