yiisoft /
validator
| 1 | <?php |
||
| 2 | |||
| 3 | declare(strict_types=1); |
||
| 4 | |||
| 5 | namespace Yiisoft\Validator\Rule; |
||
| 6 | |||
| 7 | use Countable; |
||
| 8 | use Yiisoft\Validator\Exception\UnexpectedRuleException; |
||
| 9 | use Yiisoft\Validator\Result; |
||
| 10 | use Yiisoft\Validator\Rule\Trait\CountableLimitHandlerTrait; |
||
| 11 | use Yiisoft\Validator\RuleHandlerInterface; |
||
| 12 | use Yiisoft\Validator\ValidationContext; |
||
| 13 | |||
| 14 | use function count; |
||
|
0 ignored issues
–
show
|
|||
| 15 | |||
| 16 | /** |
||
| 17 | * Validates that the value contains certain number of items. |
||
| 18 | * Can be applied to arrays or classes implementing {@see Countable} interface. |
||
| 19 | * |
||
| 20 | * @see Count |
||
| 21 | */ |
||
| 22 | final class CountHandler implements RuleHandlerInterface |
||
| 23 | { |
||
| 24 | 35 | use CountableLimitHandlerTrait; |
|
| 25 | |||
| 26 | 35 | public function validate(mixed $value, object $rule, ValidationContext $context): Result |
|
| 27 | 1 | { |
|
| 28 | if (!$rule instanceof Count) { |
||
| 29 | throw new UnexpectedRuleException(Count::class, $rule); |
||
| 30 | 34 | } |
|
| 31 | |||
| 32 | 34 | $result = new Result(); |
|
| 33 | 4 | ||
| 34 | 4 | /** @var mixed $value */ |
|
| 35 | 4 | if (!is_countable($value)) { |
|
| 36 | $result->addError($rule->getIncorrectInputMessage(), [ |
||
| 37 | 'attribute' => $context->getTranslatedAttribute(), |
||
| 38 | 4 | 'type' => get_debug_type($value), |
|
| 39 | ]); |
||
| 40 | |||
| 41 | 30 | return $result; |
|
| 42 | 30 | } |
|
| 43 | |||
| 44 | 30 | $count = count($value); |
|
| 45 | $this->validateCountableLimits($rule, $context, $count, $result); |
||
| 46 | |||
| 47 | return $result; |
||
| 48 | } |
||
| 49 | } |
||
| 50 |
Let?s assume that you have a directory layout like this:
. |-- OtherDir | |-- Bar.php | `-- Foo.php `-- SomeDir `-- Foo.phpand let?s assume the following content of
Bar.php:If both files
OtherDir/Foo.phpandSomeDir/Foo.phpare loaded in the same runtime, you will see a PHP error such as the following:PHP Fatal error: Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.phpHowever, as
OtherDir/Foo.phpdoes not necessarily have to be loaded and the error is only triggered if it is loaded beforeOtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias: