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

Cnpj::isValid()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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