Passed
Push — main ( 9fd9c1...757bec )
by Breno
01:56
created

CountAtMost::evaluate()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 10
c 1
b 0
f 0
nc 5
nop 2
dl 0
loc 19
rs 9.6111
1
<?php
2
declare(strict_types=1);
3
4
namespace BrenoRoosevelt\Validation\Rules;
5
6
use Attribute;
7
use BrenoRoosevelt\Validation\AbstractRule;
8
use Traversable;
9
10
#[Attribute(Attribute::TARGET_PROPERTY)]
11
class CountAtMost extends AbstractRule
12
{
13
    const MESSAGE = 'Expected count is at most: %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
    public function isValid($input, array $context = []): bool
21
    {
22
        if (is_countable($input)) {
23
            return count($input) <= $this->count;
24
        }
25
26
        if (is_iterable($input)) {
27
            $count = 0;
28
            foreach ($input as $v) {
29
                $count++;
30
                if ($count > $this->count) {
31
                    return false;
32
                }
33
            }
34
35
            return $count <= $this->count;
36
        }
37
38
        return false;
39
    }
40
}
41