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

Cnpj::maskPattern()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 3
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