You are here

function antibot_form_alter in Antibot 8

Same name and namespace in other branches
  1. 7 antibot.module \antibot_form_alter()

Implements hook_form_alter().

File

./antibot.module, line 47
Implements the antibot module.

Code

function antibot_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $protection = FALSE;

  // Load module config.
  $config = \Drupal::config('antibot.settings');

  // Get the configured active form IDs for antibot.
  if ($form_ids = $config
    ->get('form_ids')) {

    // Check if this form is a match.
    if (\Drupal::service('path.matcher')
      ->matchPath($form_id, implode("\n", $form_ids))) {

      // Enable protection for this form.
      antibot_protect_form($form);

      // Track that protection was added.
      $protection = TRUE;
    }
  }

  // Determine if we should display the form ID.
  if ($config
    ->get('show_form_ids')) {

    // Check if the user has permission to view these messages.
    if (\Drupal::currentUser()
      ->hasPermission('administer antibot configuration')) {

      // Set a message with the form ID and status.
      \Drupal::messenger()
        ->addMessage(t('Antibot (:id): :status', [
        ':id' => $form_id,
        ':status' => $protection ? t('enabled') : t('disabled'),
      ]));
    }
  }

  // Tag this form with Antibot settings config so that if the list of forms is
  // changing the form cache is invalidated. Note that also the unprotected
  // forms are tagged as they might be protected with the new Antibot settings.
  $cache_metadata = CacheableMetadata::createFromRenderArray($form);
  $cache_metadata
    ->addCacheableDependency($config);
  $cache_metadata
    ->applyTo($form);
}