Home / Indice sezione
 www.icosaedro.it 

 Controllo del codice fiscale e della partita IVA

pi-php.txt

<?php

// This source code is now part of the PHPLint project, see:
// http://cvs.icosaedro.it:8080/viewvc/public/phplint/stdlib/it/icosaedro/web
// Test code also available under the test/ directory of that project.

namespace it\icosaedro\web;

/*. require_module 'core'; require_module 'pcre'; .*/

/**
 * Italian Partita IVA normalization, formatting and validation routines.
 * A Partita IVA (PI) is composed of 11 digits; the last digit is the control
 * code. Example: 12345678903.
 * @author Umberto Salsi <salsi@icosaedro.it>
 * @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;
	}
	
}

Vedi il codice come puro testo.

Umberto Salsi
Contatto
Mappa
Home / Indice sezione