-
Notifications
You must be signed in to change notification settings - Fork 406
/
TypeInterleaved25Checksum.php
91 lines (78 loc) · 2.42 KB
/
TypeInterleaved25Checksum.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?php
namespace Picqer\Barcode\Types;
use Picqer\Barcode\Barcode;
use Picqer\Barcode\BarcodeBar;
use Picqer\Barcode\Exceptions\InvalidCharacterException;
/*
* Interleaved 2 of 5 barcodes.
* Compact numeric code, widely used in industry, air cargo
* Contains digits (0 to 9) and encodes the data in the width of both bars and spaces.
*/
class TypeInterleaved25Checksum implements TypeInterface
{
public function getBarcode(string $code): Barcode
{
$chr = [];
$chr['0'] = '11221';
$chr['1'] = '21112';
$chr['2'] = '12112';
$chr['3'] = '22111';
$chr['4'] = '11212';
$chr['5'] = '21211';
$chr['6'] = '12211';
$chr['7'] = '11122';
$chr['8'] = '21121';
$chr['9'] = '12121';
$chr['A'] = '11';
$chr['Z'] = '21';
// add checksum
$code .= $this->getChecksum($code);
if ((strlen($code) % 2) != 0) {
// add leading zero if code-length is odd
$code = '0' . $code;
}
// add start and stop codes
$code = 'AA' . strtolower($code) . 'ZA';
$barcode = new Barcode($code);
for ($i = 0; $i < strlen($code); $i = ($i + 2)) {
$char_bar = $code[$i];
$char_space = $code[$i + 1];
if (! isset($chr[$char_bar]) || ! isset($chr[$char_space])) {
throw new InvalidCharacterException();
}
// create a bar-space sequence
$seq = '';
$chrlen = strlen($chr[$char_bar]);
for ($s = 0; $s < $chrlen; $s++) {
$seq .= $chr[$char_bar][$s] . $chr[$char_space][$s];
}
for ($j = 0; $j < strlen($seq); ++$j) {
if (($j % 2) == 0) {
$t = true; // bar
} else {
$t = false; // space
}
$w = intval($seq[$j]);
$barcode->addBar(new BarcodeBar($w, 1, $t));
}
}
return $barcode;
}
protected function getChecksum(string $code): string
{
$len = strlen($code);
$sum = 0;
for ($i = 0; $i < $len; $i += 2) {
$sum += intval($code[$i]);
}
$sum *= 3;
for ($i = 1; $i < $len; $i += 2) {
$sum += intval($code[$i]);
}
$r = $sum % 10;
if ($r > 0) {
$r = (10 - $r);
}
return (string)$r;
}
}