Passed
Pull Request — master (#41)
by Alexander
01:57 queued 36s
created

Required::getMessage()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 7
ccs 3
cts 4
cp 0.75
crap 2.0625
rs 10
c 0
b 0
f 0
1
<?php
2
namespace Yiisoft\Validator\Rule;
3
4
use Yiisoft\Validator\DataSetInterface;
5
use Yiisoft\Validator\Result;
6
use Yiisoft\Validator\Rule;
7
8
/**
9
 * RequiredValidator validates that the specified attribute does not have null or empty value.
10
 */
11
class Required extends Rule
12
{
13
    /**
14
     * @var bool whether the comparison between the attribute value and [[requiredValue]] is strict.
15
     * When this is true, both the values and types must match.
16
     * Defaults to false, meaning only the values need to match.
17
     * Note that when [[requiredValue]] is null, if this property is true, the validator will check
18
     * if the attribute value is null; If this property is false, the validator will call [[isEmpty]]
19
     * to check if the attribute value is empty.
20
     */
21
    private $strict = false;
22
    /**
23
     * @var string the user-defined error message. It may contain the following placeholders which
24
     * will be replaced accordingly by the validator:
25
     *
26
     * - `{attribute}`: the label of the attribute being validated
27
     * - `{value}`: the value of the attribute being validated
28
     * - `{requiredValue}`: the value of [[requiredValue]]
29
     */
30
    private $message;
31
32 3
    protected function validateValue($value, DataSetInterface $dataSet = null): Result
33
    {
34 3
        $result = new Result();
35
36 3
        if ($this->strict && $value !== null || !$this->strict && !$this->isEmpty(is_string($value) ? trim($value) : $value)) {
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: ($this->strict && $value... trim($value) : $value), Probably Intended Meaning: $this->strict && ($value...trim($value) : $value))
Loading history...
37 3
            return $result;
38
        }
39
40 1
        return $result->addError($this->getMessage());
41
    }
42
43 1
    private function getMessage(): string
44
    {
45 1
        if ($this->message === null) {
46 1
            return $this->formatMessage('Value cannot be blank.');
47
        }
48
49
        return $this->formatMessage($this->message);
50
    }
51
52
    public function message(string $message): self
53
    {
54
        $this->message = $message;
55
        return $this;
56
    }
57
58
    public function strict(): self
59
    {
60
        $this->strict = true;
61
        return $this;
62
    }
63
}
64