Created
September 20, 2025 18:07
-
-
Save rlnorthcutt/81e98c99054d45316ea0a7cad19b335a to your computer and use it in GitHub Desktop.
Drupal 10+ hook - delete (or unpublish) comment with Cyrillic characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| declare(strict_types=1); | |
| use Drupal\Core\Entity\EntityInterface; | |
| use Drupal\comment\CommentInterface; | |
| /** | |
| * Implements hook_ENTITY_TYPE_insert(). | |
| * | |
| * Hard-deletes comments that contain Cyrillic characters. | |
| * Logs the user ID instead of the comment ID. | |
| */ | |
| function my_module_comment_insert(EntityInterface $entity): void { | |
| if ( | |
| !$entity instanceof CommentInterface || | |
| !$entity->hasField('comment_body') || | |
| $entity->get('comment_body')->isEmpty() | |
| ) { | |
| return; | |
| } | |
| $id = $entity->id(); | |
| $body = (string) $entity->get('comment_body')->value; | |
| // Match any Cyrillic character. | |
| if (preg_match('/\p{Cyrillic}/u', $body) === 1) { | |
| // Capture the author ID before deletion (0 for anonymous). | |
| $uid = (int) $entity->getOwnerId(); | |
| // Hard-delete the comment (policy choice). | |
| $entity->delete(); | |
| // If you prefer to *unpublish* instead of deleting | |
| // $entity->setUnpublished(); | |
| // $entity->save(); | |
| \Drupal::logger('my_module')->warning( | |
| 'Deleted a comment containing Cyrillic characters. User ID: @uid, Comment ID: @id', | |
| ['@uid' => $uid, '@id' => $id] | |
| ); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment