Passed
Push — master ( e3afe2...5369ce )
by Smoren
02:31
created

NullableRule::validate()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 4
nc 3
nop 1
dl 0
loc 8
ccs 0
cts 5
cp 0
crap 12
rs 10
c 1
b 0
f 0
1
<?php
2
3
namespace Smoren\Validator\Rules;
4
5
use Smoren\Validator\Exceptions\ValidationError;
6
use Smoren\Validator\Interfaces\BaseRuleInterface;
7
8
abstract class NullableRule implements BaseRuleInterface
9
{
10
    public const ERROR_NULL = 'null';
11
12
    /**
13
     * @var bool
14
     */
15
    protected bool $isNullable = false;
16
17
    /**
18
     * {@inheritDoc}
19
     *
20
     * @return static
21
     */
22
    public function nullable(): self
23
    {
24
        $this->isNullable = true;
25
        return $this;
26
    }
27
28
    /**
29
     * {@inheritDoc}
30
     */
31
    public function validate($value): void
32
    {
33
        if ($value === null) {
34
            if ($this->isNullable) {
35
                return;
36
            }
37
38
            throw new ValidationError($value, [[self::ERROR_NULL, []]]);
39
        }
40
    }
41
}
42