You are here

function simple_recaptcha_form_alter in Simple Google reCAPTCHA 8

Implements hook_form_alter().

File

./simple_recaptcha.module, line 16
Provides common hooks and functions for simple_google_recaptcha module.

Code

function simple_recaptcha_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  // Check user permissions.
  if (\Drupal::currentUser()
    ->hasPermission('bypass simple_recaptcha')) {
    return;
  }

  // Find matching form id in module configuration.
  $config = \Drupal::configFactory()
    ->get('simple_recaptcha.config');
  $form_ids = explode(',', $config
    ->get('form_ids'));

  // Check if this form_id is on our list.
  if (!SimpleReCaptchaFormManager::formIdInList($form_id, $form_ids)) {
    return;
  }

  // Attach reCaptcha markup and libraries to the form form.
  $info = $form_state
    ->getBuildInfo();
  switch ($config
    ->get('recaptcha_type')) {
    case 'v3':
      $settings = [
        'v3_score' => $config
          ->get('v3_score'),
        'recaptcha_action' => $info['form_id'],
      ];
      \Drupal::service('simple_recaptcha.form_manager')
        ->addReCaptchaInvisible($form, $info['form_id'], $settings);
      break;
    case 'v2':
    default:
      \Drupal::service('simple_recaptcha.form_manager')
        ->addReCaptchaCheckbox($form, $info['form_id']);
      break;
  }
  return $form;
}