3 namespace Drupal\ban\Form;
5 use Drupal\Core\Form\FormBase;
6 use Drupal\ban\BanIpManagerInterface;
7 use Drupal\Core\Form\FormStateInterface;
9 use Symfony\Component\DependencyInjection\ContainerInterface;
12 * Displays banned IP addresses.
16 class BanAdmin extends FormBase {
19 * @var \Drupal\ban\BanIpManagerInterface
24 * Constructs a new BanAdmin object.
26 * @param \Drupal\ban\BanIpManagerInterface $ip_manager
28 public function __construct(BanIpManagerInterface $ip_manager) {
29 $this->ipManager = $ip_manager;
35 public static function create(ContainerInterface $container) {
37 $container->get('ban.ip_manager')
44 public function getFormId() {
51 * @param string $default_ip
52 * (optional) IP address to be passed on to
53 * \Drupal::formBuilder()->getForm() for use as the default value of the IP
56 public function buildForm(array $form, FormStateInterface $form_state, $default_ip = '') {
58 $header = [$this->t('banned IP addresses'), $this->t('Operations')];
59 $result = $this->ipManager->findAll();
60 foreach ($result as $ip) {
65 'title' => $this->t('Delete'),
66 'url' => Url::fromRoute('ban.delete', ['ban_id' => $ip->iid]),
70 '#type' => 'operations',
78 '#title' => $this->t('IP address'),
79 '#type' => 'textfield',
82 '#default_value' => $default_ip,
83 '#description' => $this->t('Enter a valid IP address.'),
85 $form['actions'] = ['#type' => 'actions'];
86 $form['actions']['submit'] = [
88 '#value' => $this->t('Add'),
91 $form['ban_ip_banning_table'] = [
95 '#empty' => $this->t('No blocked IP addresses available.'),
104 public function validateForm(array &$form, FormStateInterface $form_state) {
105 $ip = trim($form_state->getValue('ip'));
106 if ($this->ipManager->isBanned($ip)) {
107 $form_state->setErrorByName('ip', $this->t('This IP address is already banned.'));
109 elseif ($ip == $this->getRequest()->getClientIP()) {
110 $form_state->setErrorByName('ip', $this->t('You may not ban your own IP address.'));
112 elseif (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE) == FALSE) {
113 $form_state->setErrorByName('ip', $this->t('Enter a valid IP address.'));
120 public function submitForm(array &$form, FormStateInterface $form_state) {
121 $ip = trim($form_state->getValue('ip'));
122 $this->ipManager->banIp($ip);
123 $this->messenger()->addStatus($this->t('The IP address %ip has been banned.', ['%ip' => $ip]));
124 $form_state->setRedirect('ban.admin_page');