Cake\Localized\Validation\ItValidation::cf PHP Method

cf() public static method

Checks Codice Fiscale for Italy.
public static cf ( string $check ) : boolean
$check string The value to check.
return boolean Success.
    public static function cf($check)
    {
        if (strlen($check) === 11 && preg_match('/[0-9]{11}/', $check)) {
            return true;
        }
        $check = strtoupper($check);
        if (strlen($check) != 16 || !preg_match('/[A-Z]{6}[0-9]{2}[A-Z][0-9]{2}[A-Z][0-9]{3}[A-Z]/', $check)) {
            return false;
        }
        $checkOdd = ['0' => 1, '1' => 0, '2' => 5, '3' => 7, '4' => 9, '5' => 13, '6' => 15, '7' => 17, '8' => 19, '9' => 21, 'A' => 1, 'B' => 0, 'C' => 5, 'D' => 7, 'E' => 9, 'F' => 13, 'G' => 15, 'H' => 17, 'I' => 19, 'J' => 21, 'K' => 2, 'L' => 4, 'M' => 18, 'N' => 20, 'O' => 11, 'P' => 3, 'Q' => 6, 'R' => 8, 'S' => 12, 'T' => 14, 'U' => 16, 'V' => 10, 'W' => 22, 'X' => 25, 'Y' => 24, 'Z' => 23];
        $sum = 0;
        for ($i = 1; $i <= 13; $i += 2) {
            $sum += is_numeric($check[$i]) ? (int) $check[$i] : ord($check[$i]) - ord('A');
        }
        for ($i = 0; $i <= 14; $i += 2) {
            $sum += $checkOdd[$check[$i]];
        }
        return chr($sum % 26 + ord('A')) == $check[15];
    }

Usage Example

Example #1
0
 /**
  * test the Codice Fiscale for Italy
  *
  * @return void
  */
 public function testCf()
 {
     $this->assertTrue(ItValidation::cf('JLTRSS68A41Z114A'));
     $this->assertTrue(ItValidation::cf('RSSMRA50A01F205R'));
     $this->assertTrue(ItValidation::cf('TRVMRA30T31L736B'));
     $this->assertTrue(ItValidation::cf('spsNTN55a01F839q'));
     $this->assertTrue(ItValidation::cf('02345678901'));
     $this->assertFalse(ItValidation::cf('MSSRNL30T31L736B'));
     $this->assertFalse(ItValidation::cf('spsNTN55a01F839r'));
     $this->assertFalse(ItValidation::cf('JLTRSSG8A41Z114A'));
     $this->assertFalse(ItValidation::cf('023456789O1'));
     $this->assertFalse(ItValidation::cf('0234567890'));
     $this->assertFalse(ItValidation::cf('Fail'));
 }