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
|
|
|
|