* @version $Date: 2020/01/23 10:35:47 $ */ class PartitaIVA { /** * Normalizes a PI by removing white spaces. * Useful to clean-up user's input and to save the result in the DB. * @param string $pi Raw PI, possibly with spaces. * @return string Normalized PI. */ static function normalize($pi) { $pi = (string) str_replace(" ", "", $pi); $pi = (string) str_replace("\t", "", $pi); $pi = (string) str_replace("\r", "", $pi); $pi = (string) str_replace("\n", "", $pi); return $pi; } /** * Returns the formatted PI. Currently does nothing but normalization. * @param string $pi Raw PI, possibly with spaces. * @return string Formatted PI. */ static function format($pi) { return self::normalize($pi); } /** * Verifies the basic syntax, length and control code of the given PI. * @param string $pi Raw PI, possibly with spaces. * @return string NULL if valid, or string describing why this PI must be * rejected. */ static function validate($pi) { $pi = self::normalize($pi); if( strlen($pi) == 0 ) return "Empty."; else if( strlen($pi) != 11 ) return "Invalid length."; if( preg_match("/^[0-9]{11}\$/sD", $pi) !== 1 ) return "Invalid characters."; $s = 0; for( $i = 0; $i < 11; $i++ ){ $n = ord($pi[$i]) - ord('0'); if( ($i & 1) == 1 ){ $n *= 2; if( $n > 9 ) $n -= 9; } $s += $n; } if( $s % 10 != 0 ) return "Invalid checksum."; return NULL; } }