You are here

public function BrazilianIdsService::validateCnpj in Brazilian IDs 8

Validates CNPJ numbers.

Parameters

string $value: The value of the CNPJ number to be validated.

array $error: If provided, it is filled with the error message at $error['message'] if any.

Return value

bool Returns TRUE if the CNPJ number is valid. Otherwise, returns FALSE.

Overrides BrazilianIdsServiceInterface::validateCnpj

1 call to BrazilianIdsService::validateCnpj()
BrazilianIdsService::validateCpfCnpj in src/BrazilianIdsService.php
Validates CPF or CNPJ numbers depending on the number of digits.

File

src/BrazilianIdsService.php, line 73

Class

BrazilianIdsService
Provides validation functionalities for Brazilian IDs numbers.

Namespace

Drupal\brazilian_ids

Code

public function validateCnpj($value, array &$error = []) {
  $is_valid = FALSE;
  if (isset($value) && $value !== '') {
    $forbidden = array(
      '00000000000000',
      '11111111111111',
      '22222222222222',
      '33333333333333',
      '44444444444444',
      '55555555555555',
      '66666666666666',
      '77777777777777',
      '88888888888888',
      '99999999999999',
    );

    // Checks if the value has the correct number of digits and is none of
    // the forbidden values.
    if (!preg_match('/^[0-9]{14}$/', $value)) {
      $error['message'] = $this
        ->t('CNPJ must be a 14-digit number.');
    }
    elseif (in_array($value, $forbidden)) {
      $error['message'] = $this
        ->t('CNPJ cannot be a sequence of the same digit only.');
    }
    else {

      // Checks the verification digits.
      $k = 6;
      $sum1 = 0;
      $sum2 = 0;
      for ($i = 0; $i < 13; $i++) {
        $k = $k == 1 ? 9 : $k;
        $sum2 += $value[$i] * $k--;
        if ($i < 12) {
          $sum1 += $k == 1 ? $value[$i] * 9 : $value[$i] * $k;
        }
      }
      $digit1 = $sum1 % 11 < 2 ? 0 : 11 - $sum1 % 11;
      $digit2 = $sum2 % 11 < 2 ? 0 : 11 - $sum2 % 11;
      if (!($is_valid = $value[12] == $digit1 && $value[13] == $digit2)) {
        $error['message'] = $this
          ->t('The number %value is not a valid CNPJ number.', [
          '%value' => $value,
        ]);
      }
    }
  }
  return $is_valid;
}