PersonTest.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. namespace Faker\Test\Provider\pt_PT;
  3. use Faker\Generator;
  4. use Faker\Provider\pt_PT\Person;
  5. use PHPUnit\Framework\TestCase;
  6. class PersonTest extends TestCase
  7. {
  8. public function setUp()
  9. {
  10. $faker = new Generator();
  11. $faker->addProvider(new Person($faker));
  12. $this->faker = $faker;
  13. }
  14. public function testTaxpayerIdentificationNumberIsValid()
  15. {
  16. $tin = $this->faker->taxpayerIdentificationNumber();
  17. $this->assertTrue($this->isValidTin($tin), $tin);
  18. }
  19. /**
  20. *
  21. * @link http://pt.wikipedia.org/wiki/N%C3%BAmero_de_identifica%C3%A7%C3%A3o_fiscal
  22. *
  23. * @param type $tin
  24. *
  25. * @return boolean
  26. */
  27. public static function isValidTin($tin)
  28. {
  29. $regex = '(([1,2,3,5,6,8]{1}[0-9]{8})|((45)|(70)|(71)|(72)|(77)|(79)|(90|(98|(99))))[0-9]{7})';
  30. if (is_null($tin) || !is_numeric($tin) || !strlen($tin) == 9 || preg_match("/$regex/", $tin) !== 1) {
  31. return false;
  32. }
  33. $n = str_split($tin);
  34. // cd - Control Digit
  35. $cd = ($n[0] * 9 + $n[1] * 8 + $n[2] * 7 + $n[3] * 6 + $n[4] * 5 + $n[5] * 4 + $n[6] * 3 + $n[7] * 2) % 11;
  36. if ($cd === 0 || $cd === 1) {
  37. $cd = 0;
  38. } else {
  39. $cd = 11 - $cd;
  40. }
  41. if ($cd === intval($n[8])) {
  42. return true;
  43. }
  44. return false;
  45. }
  46. }