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

Cpf::evaluate()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 11
nc 6
nop 2
dl 0
loc 21
rs 9.2222
c 1
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace BrenoRoosevelt\Validation\Rules\Brazilian;
5
6
use Attribute;
7
use BrenoRoosevelt\Validation\AbstractRule;
8
use Throwable;
9
10
#[Attribute(Attribute::TARGET_PROPERTY)]
11
class Cpf extends AbstractRule
12
{
13
    const MASK = '/^[0-9]{3}\.[0-9]{3}\.[0-9]{3}\-[0-9]{2}$/';
14
    const LENGTH = 11;
15
16
    public function __construct(private bool $mask = true, ?string $message = 'CPF inválido')
17
    {
18
        parent::__construct($message);
19
    }
20
21
    public function isValid(mixed $input, array $context = []): bool
22
    {
23
        if (!is_string($input) || !is_numeric($input)) {
24
            return false;
25
        }
26
27
        $cpf = (string) $input;
28
        if ($this->mask) {
29
            if (preg_match(Cpf::MASK, $cpf) !== 1) {
30
                return false;
31
            }
32
33
            $cpf = preg_replace('/\D/', '', $cpf);
34
        }
35
36
        $cpf = str_pad($cpf, Cpf::LENGTH, '0', STR_PAD_LEFT);
37
        if (strlen($cpf) !== Cpf::LENGTH) {
38
            return false;
39
        }
40
41
        return DigitoVerificador::checkCpfCnpjDigits($cpf);
42
    }
43
}
44