Passed
Push — master ( 9562b0...4734f7 )
by Sergei
04:27 queued 02:02
created

Required::getHandler()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
c 0
b 0
f 0
dl 0
loc 3
rs 10
eloc 1
nc 1
nop 0
ccs 2
cts 2
cp 1
crap 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\RuleWithOptionsInterface;
12
use Yiisoft\Validator\EmptyCriteria\WhenEmpty;
13
use Yiisoft\Validator\SkipOnErrorInterface;
14
use Yiisoft\Validator\WhenInterface;
15
16
/**
17
 * Validates that the specified value is neither null nor empty.
18
 *
19
 * @psalm-type EmptyCriteriaType = callable(mixed,bool):bool
20
 * @psalm-import-type WhenType from WhenInterface
21
 */
22
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
23
final class Required implements RuleWithOptionsInterface, SkipOnErrorInterface, WhenInterface
24
{
25
    use SkipOnErrorTrait;
26
    use WhenTrait;
27
28
    /**
29
     * @var callable
30
     * @psalm-var EmptyCriteriaType
31
     */
32
    private $emptyCriteria;
33
34
    /**
35
     * @psalm-param EmptyCriteriaType|null $emptyCriteria
36
     */
37 37
    public function __construct(
38
        private string $message = 'Value cannot be blank.',
39
        private string $notPassedMessage = 'Value not passed.',
40
        callable|null $emptyCriteria = null,
41
        private bool $skipOnError = false,
42
        /**
43
         * @var WhenType
44
         */
45
        private Closure|null $when = null,
46
    ) {
47 37
        $this->emptyCriteria = $emptyCriteria ?? new WhenEmpty(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 6
    public function getNotPassedMessage(): string
61
    {
62 6
        return $this->notPassedMessage;
63
    }
64
65
    /**
66
     * @psalm-return EmptyCriteriaType
67
     */
68 45
    public function getEmptyCriteria(): callable
69
    {
70 45
        return $this->emptyCriteria;
71
    }
72
73 1
    public function getOptions(): array
74
    {
75
        return [
76
            'message' => [
77 1
                'template' => $this->message,
78
                'parameters' => [],
79
            ],
80
            'notPassedMessage' => [
81 1
                'template' => $this->notPassedMessage,
82
                'parameters' => [],
83
            ],
84 1
            'skipOnError' => $this->skipOnError,
85
        ];
86
    }
87
88 46
    public function getHandler(): string
89
    {
90 46
        return RequiredHandler::class;
91
    }
92
}
93