Calculate check digit for machine/component ID, warn public users of typos
parent
1866b59040
commit
b52f0b0eb3
@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright 2020 Netsyms Technologies.
|
||||
* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
class CheckDigit {
|
||||
|
||||
/**
|
||||
* https://en.wikipedia.org/wiki/S10_(UPU_standard)#Check-digit_calculation
|
||||
* @param $number 8-digit number (int or string). Digits to the right of the eighth are ignored
|
||||
* when calculating the checksum.
|
||||
* @return int
|
||||
*/
|
||||
public static function S10($number): int {
|
||||
$weights = [8, 6, 4, 2, 3, 5, 9, 7];
|
||||
$sum = 0;
|
||||
$digits = str_split(str_pad("$number", 8, "0", STR_PAD_LEFT));
|
||||
for ($i = 0; $i < 8; $i++) {
|
||||
$sum += $digits[$i] * $weights[$i];
|
||||
}
|
||||
$sum = 11 - ($sum % 11);
|
||||
if ($sum == 10) {
|
||||
$sum = 0;
|
||||
} else if ($sum == 11) {
|
||||
$sum = 5;
|
||||
}
|
||||
return $sum;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the given number has a valid S10 check digit at index 8 (ninth counting from 1).
|
||||
* @param type $number
|
||||
* @return bool
|
||||
*/
|
||||
public static function validateS10($number): bool {
|
||||
$numberpad = str_pad("$number", 9, "0", STR_PAD_LEFT);
|
||||
$digits = str_split($numberpad);
|
||||
|
||||
$realcheckdigit = CheckDigit::S10($number);
|
||||
|
||||
return ($digits[8] == $realcheckdigit);
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue