1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Validator\Rule; |
6
|
|
|
|
7
|
|
|
use Yiisoft\Validator\Exception\UnexpectedRuleException; |
8
|
|
|
use Yiisoft\Validator\Formatter; |
9
|
|
|
use Yiisoft\Validator\FormatterInterface; |
10
|
|
|
use Yiisoft\Validator\Result; |
11
|
|
|
use Yiisoft\Validator\Rule\Trait\LimitHandlerTrait; |
12
|
|
|
use Yiisoft\Validator\RuleHandlerInterface; |
13
|
|
|
use Yiisoft\Validator\ValidationContext; |
14
|
|
|
|
15
|
|
|
use function is_string; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Validates that the value is of certain length. |
19
|
|
|
* |
20
|
|
|
* Note, this rule should only be used with strings. |
21
|
|
|
*/ |
22
|
|
|
final class HasLengthHandler implements RuleHandlerInterface |
23
|
|
|
{ |
24
|
|
|
use LimitHandlerTrait; |
25
|
|
|
|
26
|
|
|
private FormatterInterface $formatter; |
27
|
|
|
|
28
|
30 |
|
public function __construct(?FormatterInterface $formatter = null) |
29
|
|
|
{ |
30
|
30 |
|
$this->formatter = $formatter ?? new Formatter(); |
31
|
|
|
} |
32
|
|
|
|
33
|
30 |
|
public function validate($value, object $rule, ?ValidationContext $context = null): Result |
34
|
|
|
{ |
35
|
30 |
|
if (!$rule instanceof HasLength) { |
36
|
1 |
|
throw new UnexpectedRuleException(HasLength::class, $rule); |
37
|
|
|
} |
38
|
|
|
|
39
|
29 |
|
$result = new Result(); |
40
|
|
|
|
41
|
29 |
|
if (!is_string($value)) { |
42
|
5 |
|
$formattedMessage = $this->formatter->format( |
43
|
5 |
|
$rule->getMessage(), |
44
|
5 |
|
['attribute' => $context->getAttribute(), 'value' => $value] |
|
|
|
|
45
|
|
|
); |
46
|
5 |
|
$result->addError($formattedMessage); |
47
|
5 |
|
return $result; |
48
|
|
|
} |
49
|
|
|
|
50
|
24 |
|
$length = mb_strlen($value, $rule->getEncoding()); |
51
|
24 |
|
$this->validateLimits($value, $rule, $context, $length, $result); |
|
|
|
|
52
|
|
|
|
53
|
24 |
|
return $result; |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|
This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.
This is most likely a typographical error or the method has been renamed.