Passed
Push — main ( 9c0d2b...0a57e9 )
by Breno
01:44
created

CountExactly::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 2
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace BrenoRoosevelt\Validation\Rules;
5
6
use Attribute;
7
use BrenoRoosevelt\Validation\AbstractValidation;
8
use Traversable;
9
10
#[Attribute(Attribute::TARGET_PROPERTY)]
11
class CountExactly extends AbstractValidation
12
{
13
    const MESSAGE = 'Expected count is: %s';
14
15
    public function __construct(private int $count, string $message = null)
16
    {
17
        parent::__construct($message ?? sprintf(self::MESSAGE, $this->count));
18
    }
19
20
    protected function evaluate($input, array $context = []): bool
21
    {
22
        if (is_countable($input)) {
23
            return count($input) === $this->count;
24
        }
25
26
        if ($input instanceof Traversable) {
27
            return iterator_count($input) === $this->count;
28
        }
29
30
        if (is_iterable($input)) {
31
            $count = 0;
32
            foreach ($input as $v) {
33
                $count++;
34
            }
35
36
            return $count === $this->count;
37
        }
38
39
        return false;
40
    }
41
}
42