-
Notifications
You must be signed in to change notification settings - Fork 0
/
SaIdNumberVerification.php
57 lines (47 loc) · 1.79 KB
/
SaIdNumberVerification.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
<?php
namespace App\Validations;
trait SaIdNumberVerification
{
public function validateSouthAfricanId(string $idNumber): bool
{
// Check for valid length (13 digits) and numeric characters
if (strlen($idNumber) !== 13 || !is_numeric($idNumber)) {
return false;
}
// Extract components 930208 1372 0 8 9 // YYMMDD G SSSS C 8 Z
$year = substr($idNumber, 0, 2);
$prefix = $this->determineCentury($year);
$birthYear = (int)$prefix . $year;
$BirthMonth = (int)substr($idNumber, 2, 2);
$BirthDay = (int)substr($idNumber, 4, 2);
$gender = substr($idNumber, 6, 4);
$citizenship = (int)substr($idNumber, 10, 1);
$checksum = (int)substr($idNumber, 12, 1);
// Validate birthdate (basic check)
if (!checkdate($BirthMonth, $BirthDay, $birthYear)) {
return false;
}
// Validate gender (0-4 female, 5-9 male)
// unnecessary check
if ($gender < '0000' || $gender > '9999') {
return false;
}
// Validate citizenship (0 - South African Citizen, 1 - Permanent Resident)
if ($citizenship !== 0 && $citizenship !== 1) {
return false;
}
// Calculate checksum digit using Luhn Algorithm
$digits = str_split(substr($idNumber, 0, 12));
$sum = array_reduce($digits, function ($carry, $digit) use (&$index) {
$digit = (($index++ % 2 === 0) ? $digit : $digit * 2);
return $carry + ($digit > 9 ? $digit - 9 : $digit);
}, 0);
$checkDigit = (10 - ($sum % 10)) % 10;
// Validate checksum
return $checksum === $checkDigit;
}
private function determineCentury($YY): string
{
return ($YY < date('y')) ? '20' : '19';
}
}