|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Picqer\Barcode\Types; |
| 4 | + |
| 5 | +use Picqer\Barcode\Barcode; |
| 6 | +use Picqer\Barcode\BarcodeBar; |
| 7 | +use Picqer\Barcode\Exceptions\InvalidCharacterException; |
| 8 | +use Picqer\Barcode\Exceptions\InvalidLengthException; |
| 9 | + |
| 10 | +class TypeITF14 implements TypeInterface |
| 11 | +{ |
| 12 | + /** |
| 13 | + * @throws InvalidLengthException |
| 14 | + * @throws InvalidCharacterException |
| 15 | + */ |
| 16 | + public function getBarcodeData(string $code): Barcode |
| 17 | + { |
| 18 | + $chr = []; |
| 19 | + $chr['0'] = '11221'; |
| 20 | + $chr['1'] = '21112'; |
| 21 | + $chr['2'] = '12112'; |
| 22 | + $chr['3'] = '22111'; |
| 23 | + $chr['4'] = '11212'; |
| 24 | + $chr['5'] = '21211'; |
| 25 | + $chr['6'] = '12211'; |
| 26 | + $chr['7'] = '11122'; |
| 27 | + $chr['8'] = '21121'; |
| 28 | + $chr['9'] = '12121'; |
| 29 | + $chr['A'] = '11'; |
| 30 | + $chr['Z'] = '21'; |
| 31 | + |
| 32 | + if (strlen($code) < 13 || strlen($code) > 14) { |
| 33 | + throw new InvalidLengthException(); |
| 34 | + } |
| 35 | + |
| 36 | + if (strlen($code) === 13) { |
| 37 | + $code .= $this->getChecksum($code); |
| 38 | + } |
| 39 | + |
| 40 | + $barcode = new Barcode($code); |
| 41 | + |
| 42 | + // Add start and stop codes |
| 43 | + $code = 'AA' . strtolower($code) . 'ZA'; |
| 44 | + |
| 45 | + // Loop through 2 chars at once |
| 46 | + for ($charIndex = 0; $charIndex < strlen($code); $charIndex += 2) { |
| 47 | + if (! isset($chr[$code[$charIndex]]) || ! isset($chr[$code[$charIndex + 1]])) { |
| 48 | + throw new InvalidCharacterException(); |
| 49 | + } |
| 50 | + |
| 51 | + $drawBar = true; |
| 52 | + $pbars = $chr[$code[$charIndex]]; |
| 53 | + $pspaces = $chr[$code[$charIndex + 1]]; |
| 54 | + $pmixed = ''; |
| 55 | + |
| 56 | + while (strlen($pbars) > 0) { |
| 57 | + $pmixed .= $pbars[0] . $pspaces[0]; |
| 58 | + $pbars = substr($pbars, 1); |
| 59 | + $pspaces = substr($pspaces, 1); |
| 60 | + } |
| 61 | + |
| 62 | + foreach (str_split($pmixed) as $width) { |
| 63 | + $barcode->addBar(new BarcodeBar($width, 1, $drawBar)); |
| 64 | + $drawBar = ! $drawBar; |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + return $barcode; |
| 69 | + } |
| 70 | + |
| 71 | + private function getChecksum(string $code): string |
| 72 | + { |
| 73 | + $total = 0; |
| 74 | + |
| 75 | + for ($charIndex = 0; $charIndex <= (strlen($code) - 1); $charIndex++) { |
| 76 | + $integerOfChar = intval($code . substr($charIndex, 1)); |
| 77 | + $total += $integerOfChar * (($charIndex === 0 || $charIndex % 2 === 0) ? 3 : 1); |
| 78 | + } |
| 79 | + |
| 80 | + $checksum = 10 - ($total % 10); |
| 81 | + if ($checksum === 10) { |
| 82 | + $checksum = 0; |
| 83 | + } |
| 84 | + |
| 85 | + return (string)$checksum; |
| 86 | + } |
| 87 | +} |
0 commit comments