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

Document   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
c 1
b 0
f 0
dl 0
loc 53
rs 10
wmc 9

6 Methods

Rating   Name   Duplication   Size   Complexity  
A adjustZeroPadding() 0 3 1
A unmaskNumber() 0 3 1
A __construct() 0 3 1
A evaluate() 0 18 4
A validateNumbersWithCorrectLength() 0 4 1
A isValidMask() 0 3 1
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