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

Count   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 30
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 30
rs 10
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A evaluate() 0 20 5
A __construct() 0 3 1
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