Passed
Pull Request — master (#4)
by
unknown
02:09
created

BoletoValidator   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 82
Duplicated Lines 0 %

Test Coverage

Coverage 97.06%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 11
eloc 32
c 2
b 0
f 0
dl 0
loc 82
ccs 33
cts 34
cp 0.9706
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getLastCharacter() 0 3 1
A calculateBarcodeDigit() 0 8 2
A verifyWritableLine() 0 32 5
A verifyBarcode() 0 19 3
1
<?php
2
3
namespace Claudsonm\BoletoWinner\Validators;
4
5
class BoletoValidator implements Validator
6
{
7
    /**
8
     * {@inheritdoc}
9
     */
10 45
    public function verifyWritableLine(string $writableLine): bool
11
    {
12 45
        $writableLine = preg_replace('/[^0-9]/', '', $writableLine);
13
14 45
        if (strlen($writableLine) != 47) {
15 15
            return false;
16
        }
17
18 31
        if ($writableLine[0] == '8') {
19
            return false;
20
        }
21
22
        $blocks = [
23 31
            substr($writableLine, 0, 10),
24 31
            substr($writableLine, 10, 11),
25 31
            substr($writableLine, 21, 11),
26
        ];
27
28 31
        $blocksValidated = 0;
29 31
        foreach ($blocks as $block) {
30 31
            $blockLength = strlen($block) - 1;
31
32 31
            $blockInputNumbers = substr($block, 0, $blockLength);
33
34 31
            $blockVerificationDigit = $this->getLastCharacter($block);
35
36 31
            if (module10($blockInputNumbers) === $blockVerificationDigit) {
37 31
                $blocksValidated++;
38
            }
39
        }
40
41 31
        return 3 === $blocksValidated;
42
    }
43
44
    /**
45
     * {@inheritdoc}
46
     */
47 48
    public function verifyBarcode(string $barcode): bool
48
    {
49 48
        $barcode = preg_replace('/[^0-9]/', '', $barcode);
50
51 48
        if (strlen($barcode) != 44) {
52 12
            return false;
53
        }
54
55 36
        if ($barcode[0] == '8') {
56 5
            return false;
57
        }
58
59 32
        $barcodeVerificationDigit = substr($barcode, 4, 1);
60
61 32
        $blockInputNumbers = substr($barcode, 0, 4);
62
63 32
        $blockInputNumbers .= substr($barcode, 5);
64
65 32
        return $this->calculateBarcodeDigit($blockInputNumbers) === $barcodeVerificationDigit;
66
    }
67
68
    /**
69
     * Returns the last character of the input string.
70
     */
71 31
    private function getLastCharacter(string $input): string
72
    {
73 31
        return substr($input, -1);
74
    }
75
76
    /**
77
     * Computes the barcode verification digit.
78
     */
79 32
    private function calculateBarcodeDigit(string $inputNumbers): string
80
    {
81 32
        $digit = module11($inputNumbers);
82 32
        if ('0' === $digit) {
83 7
            return '1';
84
        }
85
86 25
        return $digit;
87
    }
88
}
89