Passed
Pull Request — master (#391)
by Sergei
18:05
created

Required   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 7
eloc 15
c 0
b 0
f 0
dl 0
loc 63
ccs 16
cts 16
cp 1
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A getHandlerClassName() 0 3 1
A getName() 0 3 1
A getOptions() 0 6 1
A getNotPassedMessage() 0 3 1
A getMessage() 0 3 1
A __construct() 0 11 1
A getEmptyHandler() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Attribute;
8
use Closure;
9
use Yiisoft\Validator\Rule\Trait\SkipOnErrorTrait;
10
use Yiisoft\Validator\Rule\Trait\WhenTrait;
11
use Yiisoft\Validator\SerializableRuleInterface;
12
use Yiisoft\Validator\EmptyHandler\SimpleEmpty;
13
use Yiisoft\Validator\SkipOnErrorInterface;
14
use Yiisoft\Validator\ValidationContext;
15
use Yiisoft\Validator\WhenInterface;
16
17
/**
18
 * Validates that the specified value is neither null nor empty.
19
 *
20
 * @psalm-type EmptyHandlerType = callable(mixed,bool):bool
21
 */
22
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
23
final class Required implements SerializableRuleInterface, SkipOnErrorInterface, WhenInterface
24
{
25
    use SkipOnErrorTrait;
26
    use WhenTrait;
27
28
    /**
29
     * @var callable
30
     * @psalm-var EmptyHandlerType
31
     */
32
    private $emptyHandler;
33
34
    /**
35
     * @psalm-param EmptyHandlerType|null $emptyHandler
36
     */
37 40
    public function __construct(
38
        private string $message = 'Value cannot be blank.',
39
        private string $notPassedMessage = 'Value not passed.',
40
        callable|null $emptyHandler = null,
41
        private bool $skipOnError = false,
42
        /**
43
         * @var Closure(mixed, ValidationContext):bool|null
44
         */
45
        private ?Closure $when = null,
46
    ) {
47 40
        $this->emptyHandler = $emptyHandler ?? new SimpleEmpty(trimString: true);
48
    }
49
50 1
    public function getName(): string
51
    {
52 1
        return 'required';
53
    }
54
55 16
    public function getMessage(): string
56
    {
57 16
        return $this->message;
58
    }
59
60 7
    public function getNotPassedMessage(): string
61
    {
62 7
        return $this->notPassedMessage;
63
    }
64
65
    /**
66
     * @psalm-return EmptyHandlerType
67
     */
68 45
    public function getEmptyHandler(): callable
69
    {
70 45
        return $this->emptyHandler;
71
    }
72
73 1
    public function getOptions(): array
74
    {
75
        return [
76 1
            'message' => $this->message,
77 1
            'notPassedMessage' => $this->notPassedMessage,
78 1
            'skipOnError' => $this->skipOnError,
79
        ];
80
    }
81
82 47
    public function getHandlerClassName(): string
83
    {
84 47
        return RequiredHandler::class;
85
    }
86
}
87