You are here

public function SimpleReCaptchaFormManager::addReCaptchaCheckbox in Simple Google reCAPTCHA 8

Add reCaptcha v2 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.

File

src/SimpleReCaptchaFormManager.php, line 89

Class

SimpleReCaptchaFormManager
Provides helper service used to attach reCaptcha to forms.

Namespace

Drupal\simple_recaptcha

Code

public function addReCaptchaCheckbox(array &$form, $form_id) {

  // 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');
  $secret_key = $config
    ->get('secret_key');
  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',
        'recaptcha-wrapper',
      ],
    ],
  ];

  // Attach helper libraries.
  $form['#attached']['drupalSettings']['simple_recaptcha']['sitekey'] = $site_key;
  $form['#attached']['drupalSettings']['simple_recaptcha']['form_ids'][$form_id] = $form_id;
  $form['#attached']['library'][] = 'simple_recaptcha/simple_recaptcha';
  $form['simple_recaptcha_token'] = [
    '#type' => 'hidden',
  ];
  $form['simple_recaptcha_type'] = [
    '#type' => 'hidden',
    '#value' => 'v2',
  ];
  $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);
}