You are here

public function SimpleReCaptchaFormManager::addReCaptchaInvisible in Simple Google reCAPTCHA 8

Add reCaptcha v3 container and libraries to the form.

Parameters

array $form: Renderable array of form which will be secured by reCaptcha checkbox.

string $form_id: Form ID of form which will be secured.

array $configuration: Configuration for invisible recaptcha.

File

src/SimpleReCaptchaFormManager.php, line 153

Class

SimpleReCaptchaFormManager
Provides helper service used to attach reCaptcha to forms.

Namespace

Drupal\simple_recaptcha

Code

public function addReCaptchaInvisible(array &$form, $form_id, array $configuration) {

  // Allow modules to perform extra access checks and bypass validation.
  $bypass = FALSE;
  $this->moduleHandler
    ->alter('simple_recaptcha_bypass', $form, $bypass);
  if ($bypass) {
    return;
  }

  // Check if site keys are configured, if at least one of keys isn't provided
  // protection won't work, so we can't modify and block this form.
  $config = $this->configFactory
    ->get('simple_recaptcha.config');
  $site_key = $config
    ->get('site_key_v3');
  $secret_key = $config
    ->get('secret_key_v3');
  if (!$site_key || !$secret_key) {
    return;
  }

  // Add HTML data attributes and Wrapper for reCAPTCHA widget.
  $form['#attributes']['data-recaptcha-id'] = $form_id;
  $form['actions']['captcha'] = [
    '#type' => 'container',
    '#weight' => -1,
    '#attributes' => [
      'id' => $form_id . '-captcha',
      'class' => [
        'recaptcha-v3',
        'recaptcha-v3-wrapper',
      ],
    ],
  ];
  $form['#attached']['drupalSettings']['simple_recaptcha_v3']['sitekey'] = $site_key;
  $form['#attached']['drupalSettings']['simple_recaptcha_v3']['forms'][$form_id] = [
    'form_id' => $form_id,
    'score' => $configuration['v3_score'],
    'error_message' => isset($configuration['v3_error_message']) ? $configuration['v3_error_message'] : NULL,
    'action' => $configuration['recaptcha_action'],
  ];
  $form['#attached']['library'][] = 'simple_recaptcha/simple_recaptcha_v3';
  $form['simple_recaptcha_token'] = [
    '#type' => 'hidden',
  ];
  $form['simple_recaptcha_type'] = [
    '#type' => 'hidden',
    '#value' => 'v3',
  ];
  $form['simple_recaptcha_score'] = [
    '#type' => 'hidden',
    '#value' => $configuration['v3_score'],
  ];
  $form['simple_recaptcha_message'] = [
    '#type' => 'hidden',
  ];
  $form['#validate'][] = [
    $this,
    'validateCaptchaToken',
  ];

  // Marge config cache into existing form cache metadata.
  $form_cache = CacheableMetadata::createFromRenderArray($form);
  $config_cache = CacheableMetadata::createFromObject($config);
  $form_cache
    ->merge($config_cache)
    ->applyTo($form);
  $this
    ->addSubmitHandler($form);
}