This repository has been archived by the owner on Mar 19, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBarcodeChecksum.php
104 lines (90 loc) · 2.39 KB
/
BarcodeChecksum.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
92
93
94
95
96
97
98
99
100
101
102
103
104
<?php
/**
* @link http://astwell.com/
* @copyright Copyright (c) 2014 Astwell Soft
* @license http://astwell.com/license/
*/
namespace lembadm\barcode;
use Yii;
use yii\validators\Validator;
/**
* Class BarcodeChecksum
*
* @package lembadm\barcode
*/
class BarcodeChecksum extends Validator
{
/**
* @var string Checksum generator name
*/
public $method;
/**
* @inheritdoc
*/
public function init()
{
$this->message = $this->message
?: Yii::t( 'yii', '{attribute} checksum not valid' );
}
/**
* @inheritdoc
*/
public function validateValue( $value )
{
if( ! $this->method ) return null;
return ( $this->{'compute' . $this->method}( $value ) )
? [$this->message, []]
: null;
}
/**
* @inheritdoc
*/
public function clientValidateAttribute($model, $attribute, $view)
{
BarcodeAsset::register($view);
return null;
}
/**
* EAN13 checksum generator
*
* @param string $value
*
* @return bool
*/
protected function computeEAN( $value )
{
$sum = 0;
$odd = true;
for ($i = (strlen($value) - 2); $i > -1; $i--) {
$sum += ( $odd ? 3 : 1 ) * $value[$i];
$odd = ! $odd;
}
return substr( $value, -1 ) != (( 10 - $sum % 10 ) % 10);
}
/**
* Code39 checksum generator
*
* @param string $value
*
* @return bool
*/
protected function computeCode39($value)
{
$check = [
'0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5, '6' => 6,
'7' => 7, '8' => 8, '9' => 9, 'A' => 10, 'B' => 11, 'C' => 12, 'D' => 13,
'E' => 14, 'F' => 15, 'G' => 16, 'H' => 17, 'I' => 18, 'J' => 19, 'K' => 20,
'L' => 21, 'M' => 22, 'N' => 23, 'O' => 24, 'P' => 25, 'Q' => 26, 'R' => 27,
'S' => 28, 'T' => 29, 'U' => 30, 'V' => 31, 'W' => 32, 'X' => 33, 'Y' => 34,
'Z' => 35, '-' => 36, '.' => 37, ' ' => 38, '$' => 39, '/' => 40, '+' => 41,
'%' => 42,
];
$checksum = substr( $value, - 1, 1 );
$value = str_split( substr( $value, 0, - 1 ) );
$count = 0;
foreach ($value as $char) {
$count += $check[$char];
}
return ( ( $count % 43 ) == $check[$checksum] );
}
}