Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace Foxx\ComputerScience\U1;
- final class SinCheck {
- public function __construct() {
- echo "Welcome to the sin checker!\n";
- $userInput = readline("Enter your 9 digit SIN: ");
- $valid = $this->validateSIN($userInput);
- if ($valid) {
- echo "Your SIN is valid.";
- } else {
- echo "Your SIN is invalid.";
- }
- }
- /**
- * The luhn algorithm is used to check the validity of a number.
- *
- * @param string $str
- * @return bool
- */
- function luhn(string $str): bool {
- $odd = !strlen($str)%2;
- $sum = 0;
- for($i=0;$i<strlen($str);++$i){
- $n=0+$str[$i];
- $odd=!$odd;
- if($odd){
- $sum+=$n;
- }else{
- $x=2*$n;
- $sum+=$x>9?$x-9:$x;
- }
- }
- return(($sum%10)==0);
- }
- /**
- * Checks if the given string is a valid SIN.
- *
- * @param string $str
- * @return bool
- */
- function validateSIN(string $sin): bool {
- $sin = preg_replace('/[^0-9]/','',$sin);
- if(strlen($sin) == 9){
- if($sin[0] == '0' || $sin[0] == '8'){
- return false;
- }else{
- return $this->luhn($sin);
- }
- }else{
- return false;
- }
- }
- /**
- * Generates a random SIN.
- *
- * @param string $separator
- * @return string
- */
- function generateSIN(string $separator = ' '){
- $validPrefix = array(1,2,3,4,5,6,7,9);
- $sin = array_rand($validPrefix,1);
- $length = 9;
- while(strlen($sin) < ($length - 1)){
- $sin .= rand(0,9);
- }
- $sum = 0;
- $pos = 0;
- $reversedSIN = strrev( $sin );
- while($pos < $length - 1){
- $odd = $reversedSIN[ $pos ] * 2;
- if($odd > 9){
- $odd -= 9;
- }
- $sum += $odd;
- if($pos != ($length - 2)){
- $sum += $reversedSIN[ $pos +1 ];
- }
- $pos += 2;
- }
- $checkdigit = (( floor($sum/10) + 1) * 10 - $sum) % 10;
- $sin .= $checkdigit;
- $sin1 = substr($sin,0,3);
- $sin2 = substr($sin,3,3);
- $sin3 = substr($sin,6,3);
- return $sin1.$separator.$sin2.$separator.$sin3;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement