Passed
Push — main ( bcfe1e...2c9533 )
by Breno
01:52
created

Cnpj::isValidDocument()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 7
rs 10
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
    protected function evaluate(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