Passed
Push — main ( e79ce9...ff172d )
by Breno
02:17
created

Count::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 3
rs 10
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 Count 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