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

Cpf   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 32
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
dl 0
loc 32
rs 10
c 1
b 0
f 0
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A isValid() 0 21 6
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