Passed
Push — main ( 48c7ef...34571b )
by Breno
01:46
created

Document::evaluate()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 10
c 0
b 0
f 0
nc 3
nop 2
dl 0
loc 18
rs 9.9332
1
<?php
2
declare(strict_types=1);
3
4
namespace BrenoRoosevelt\Validation\Rules;
5
6
use BrenoRoosevelt\Validation\AbstractValidation;
7
use Throwable;
8
9
abstract class Document extends AbstractValidation
10
{
11
    public function __construct(private bool $mask = true, ?string $message = 'Invalid document')
12
    {
13
        parent::__construct($message);
14
    }
15
16
    public function evaluate($input, array $context = []): bool
17
    {
18
        try {
19
            $document = (string) $input;
20
        } catch (Throwable) {
0 ignored issues
show
Unused Code introduced by
catch (\Throwable) is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
21
            return false;
22
        }
23
24
        if ($this->mask) {
25
            if (!$this->isValidMask($document)) {
26
                return false;
27
            }
28
29
            $document = $this->unmaskNumber($document);
30
        }
31
32
        $document = $this->adjustZeroPadding($document);
33
        return $this->isValidDocument($document);
34
    }
35
36
    public function isValidMask(string $input): bool
37
    {
38
        return preg_match($this->maskPattern(), $input) === 1;
39
    }
40
41
    public function unmaskNumber(string $input): string
42
    {
43
        return preg_replace('/\D/', '', $input);
44
    }
45
46
    public function adjustZeroPadding(string $input): string
47
    {
48
        return $input;
49
    }
50
51
    public function validateNumbersWithCorrectLength(string $unmaskedInput): bool
52
    {
53
        $numericWithSize = '/^\d{' . $this->unmaskedLength() . '}$/';
54
        return preg_match($numericWithSize, $unmaskedInput) === 1;
55
    }
56
57
    abstract public function isValidDocument(string $input): bool;
58
59
    abstract public function maskPattern(): string;
60
61
    abstract public function unmaskedLength(): int;
62
}
63