Passed
Pull Request — master (#320)
by Dmitriy
02:36
created

CountHandler::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 0
c 1
b 0
f 0
dl 0
loc 2
ccs 1
cts 1
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
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\LimitHandlerTrait;
11
use Yiisoft\Validator\RuleHandlerInterface;
12
use Yiisoft\Validator\ValidationContext;
13
14
use function count;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Yiisoft\Validator\Rule\count. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are 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.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/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:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
15
16
/**
17
 * Validates that the value contains certain number of items. Can be applied to arrays or classes implementing
18
 * {@see Countable} interface.
19
 */
20
final class CountHandler implements RuleHandlerInterface
21
{
22
    use LimitHandlerTrait;
23
24 25
    public function validate(mixed $value, object $rule, ValidationContext $context): Result
25
    {
26 25
        if (!$rule instanceof Count) {
27 1
            throw new UnexpectedRuleException(Count::class, $rule);
28
        }
29
30 24
        $result = new Result();
31
32 24
        if (!is_countable($value)) {
33 1
            $result->addError(
34 1
                message: $rule->getMessage(),
35 1
                parameters: ['value' => $value]
36
            );
37
38 1
            return $result;
39
        }
40
41 23
        $count = count($value);
42 23
        $this->validateLimits($value, $rule, $context, $count, $result);
43
44 23
        return $result;
45
    }
46
}
47