You are here

public function AutobanCommands::ban in Automatic IP ban (Autoban) 8

Autoban IP ban.

@command autoban:ban @aliases autoban-ban @usage autoban-ban [rule]

Parameters

string $rule: Autoban rule id.

File

src/Commands/AutobanCommands.php, line 33

Class

AutobanCommands
A Drush commandfile.

Namespace

Drupal\autoban\Commands

Code

public function ban($rule = NULL) {
  $this->autoban = \Drupal::service('autoban');
  $autobanStorage = \Drupal::service('entity_type.manager')
    ->getStorage('autoban');
  $this
    ->output()
    ->writeln('Autoban banning start...');
  if (!empty($rule)) {

    // Checking the rule received from the user input.
    if (!$autobanStorage
      ->load($rule)) {
      $this
        ->logger()
        ->error(sprintf('Wrong rule %s', $rule));
      return;
    }
    $this
      ->output()
      ->writeln(sprintf('Ban for rule %s', $rule));
    $banned = $this
      ->banRule($rule);
    if ($banned > 0) {
      $this
        ->logger()
        ->success(sprintf('Banned count: %s', $banned));
    }
    else {
      $this
        ->logger()
        ->warning('No banned IP.');
    }
  }
  else {
    $rules = $autobanStorage
      ->loadMultiple();
    $this
      ->output()
      ->writeln(sprintf('Ban for all rules: %s', count($rules)));
    if (!empty($rules)) {
      $totalBanned = 0;
      foreach (array_keys($rules) as $rule) {
        $banned = $this
          ->banRule($rule);
        $this
          ->logger()
          ->notice(sprintf('Rule %s Banned count: %s', $rule, $banned));
        $totalBanned += $banned;
      }
      if ($totalBanned > 0) {
        $this
          ->logger()
          ->success(sprintf('Total banned IP count: %s', $totalBanned));
      }
      else {
        $this
          ->logger()
          ->warning('No banned IP.');
      }
    }
  }
  $this
    ->output()
    ->writeln('Finished.');
}