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

Cnpj   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 evaluate() 0 21 6
A __construct() 0 3 1
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