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

NullableRule   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 9
dl 0
loc 31
ccs 0
cts 8
cp 0
rs 10
c 1
b 0
f 0
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 8 3
A nullable() 0 4 1
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