Drupal - Un petit filtre pour les commentaires en fonction d'une liste de mots bannis

C'est loin d'être la solution la plus moderne au monde, mais voila un petit filtre qui, en fonction d'une liste de mots publiera ou non un commentaire posté sur votre site. 

Évidement l'idée peut s'adapter à toute sorte de formulaire de votre site.

J'ai utilisé le hook comment_presave : 

Fichier : web/modules/mon_module/src/Hook/EntityHooks.php 

<?php

namespace Drupal\mon_module\Hook;

use Drupal\comment\CommentInterface;
use Drupal\Core\DependencyInjection\AutowireTrait;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Hook\Attribute\Hook;

/**
 * Provides hook implementations for Entity alterations.
 */
final class EntityHooks implements ContainerInjectionInterface {

  use AutowireTrait;

  /**
   * Comments blacklisted words.
   */
  protected static array $commentBlackListWords = [
    "useful",
    "nexus",
    "д",
    "Psilocybin",
    "?link",
    "url?",
    "dark market?",
    "dark web",
    "darkweb",
    "darknet",
    "Gambling",
    "darkmarket",
    "drug",
    "Russia",
    "อ",
    "ส์",
    "Why SQL Matters in Business Analytic",
  ];

  /**
   * Hook method triggered before a comment is saved.
   *
   * Checks the comment body for blacklisted words and updates the comment
   * status to "not published" if any blacklisted word is detected.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The comment entity being processed.
   */
  #[Hook('comment_presave')]
  public function commentPresave(EntityInterface $entity): void {
    if ($entity instanceof CommentInterface) {
      $body = $entity->get('comment_body')->value;
      $body = strtolower($body);
      foreach (self::$commentBlackListWords as $word) {
        if (str_contains($body, strtolower($word))) {
          $entity->set('status', CommentInterface::NOT_PUBLISHED);
        }
      }
    }
  }

}

Ajouter un commentaire

Ne sera pas publié
CAPTCHA
Désolé, pour ça, mais c'est le seul moyen pour éviter le spam...