Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Antispam Bundle Laravel Package

bxnxg/antispam-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:
    composer require bxnxg/antispam-bundle
    
  2. Enable the Bundle: Add to config/bundles.php:
    return [
        // ...
        Bxnxg\AntiSpamBundle\BxnxgAntiSpamBundle::class => ['all' => true],
    ];
    
  3. Configure: Publish the default config:
    php bin/console config:dump-reference BxnxgAntiSpamBundle
    
    Override in config/packages/bxnxg_antispam.yaml:
    bxnxg_antispam:
        enabled: true
        honeypot:
            enabled: true
            field_name: 'honeypot_field'
        captcha:
            enabled: false
            # (Configure if enabling)
    

First Use Case

Add Honeypot to a Form:

// src/Form/ContactType.php
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\TextType;

class ContactType extends AbstractType {
    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder
            ->add('name', TextType::class)
            ->add('email', TextType::class)
            ->add('message', TextType::class)
            ->add('honeypot_field', HiddenType::class, [
                'mapped' => false,
                'required' => false,
            ]);
    }
}

Validate Submission: The bundle automatically checks for honeypot submissions. No extra validation code needed.


Implementation Patterns

Common Workflows

  1. Honeypot Integration:

    • Add hidden fields to forms (e.g., honeypot_field).
    • The bundle validates that these fields are empty (bots fill them).
    • Works seamlessly with Symfony’s form validation system.
  2. CAPTCHA Integration (Optional):

    • Enable in config:
      bxnxg_antispam:
          captcha:
              enabled: true
              provider: 'recaptcha' # or 'hcaptcha'
              recaptcha:
                  site_key: '%env(RECAPTCHA_SITE_KEY)%'
                  secret_key: '%env(RECAPTCHA_SECRET_KEY)%'
      
    • Add CAPTCHA field to forms:
      $builder->add('captcha', CaptchaType::class);
      
  3. Custom Validation:

    • Extend the bundle’s validator:
      // src/Validator/Constraints/CustomAntiSpam.php
      use Symfony\Component\Validator\Constraint;
      
      class CustomAntiSpam extends Constraint {
          public $message = 'This submission looks like spam.';
      }
      
    • Create a validator:
      // src/Validator/CustomAntiSpamValidator.php
      use Symfony\Component\Validator\ConstraintValidator;
      
      class CustomAntiSpamValidator extends ConstraintValidator {
          public function validate($value, Constraint $constraint) {
              // Custom logic (e.g., IP rate limiting, keyword checks)
          }
      }
      
    • Use in forms:
      $builder->add('message', TextType::class, [
          'constraints' => [new CustomAntiSpam()],
      ]);
      
  4. Event-Based Extensions:

    • Listen for spam detection events:
      // src/EventListener/AntiSpamListener.php
      use Bxnxg\AntiSpamBundle\Event\SpamDetectedEvent;
      use Symfony\Component\EventDispatcher\EventSubscriberInterface;
      
      class AntiSpamListener implements EventSubscriberInterface {
          public static function getSubscribedEvents() {
              return [
                  SpamDetectedEvent::NAME => 'onSpamDetected',
              ];
          }
      
          public function onSpamDetected(SpamDetectedEvent $event) {
              // Log, block IP, or notify admin
              $event->setHandled(true); // Prevent default response
          }
      }
      

Integration Tips

  • Symfony Forms: Works out-of-the-box with Symfony’s form system. No manual validation needed for honeypots.
  • Twig Templates: Hide honeypot fields with CSS:
    {{ form_row(form.honeypot_field, { 'attr': { 'style': 'display:none;' } }) }}
    
  • APIs: For API endpoints, use the SpamChecker service directly:
    $spamChecker = $container->get('bxnxg_antispam.spam_checker');
    if ($spamChecker->isSpam($request)) {
        throw new \Symfony\Component\HttpKernel\Exception\HttpException(403, 'Spam detected');
    }
    
  • Testing: Mock the SpamChecker service in PHPUnit:
    $this->container->set('bxnxg_antispam.spam_checker', $this->createMock(SpamCheckerInterface::class));
    

Gotchas and Tips

Pitfalls

  1. Honeypot Field Naming:

    • Default field name is honeypot_field. If you rename it, update the config:
      bxnxg_antispam:
          honeypot:
              field_name: 'custom_honeypot'
      
    • Gotcha: Forgetting to update the config after renaming the field will cause validation to fail silently.
  2. CAPTCHA Configuration:

    • If captcha.enabled is true but no provider is configured, the bundle will throw an exception.
    • Fix: Always set provider and required keys (e.g., recaptcha.site_key).
  3. Double Validation:

    • If using both honeypot and CAPTCHA, ensure the CAPTCHA field is not hidden (bots may ignore it).
    • Tip: Use a visible CAPTCHA for high-risk forms (e.g., admin panels).
  4. Event Handling:

    • The SpamDetectedEvent is dispatched after validation fails. If you set $event->setHandled(true), the default response (e.g., 403) will be suppressed.
    • Gotcha: Forgetting to handle the event may leave spam submissions unchecked.
  5. Performance:

    • CAPTCHA providers (e.g., reCAPTCHA) add network overhead. Cache responses if possible:
      bxnxg_antispam:
          captcha:
              recaptcha:
                  cache_response: true
      

Debugging

  1. Enable Debug Mode:

    • Set debug: true in config to log spam attempts:
      bxnxg_antispam:
          debug: true
      
    • Check logs in var/log/dev.log.
  2. Validate Manually:

    • Use the SpamChecker service to debug submissions:
      $spamChecker = $container->get('bxnxg_antispam.spam_checker');
      $isSpam = $spamChecker->isSpam($request);
      dump($spamChecker->getSpamReasons());
      
  3. Common Issues:

    • Issue: Honeypot validation fails even for legitimate submissions. Cause: The hidden field is not truly hidden (e.g., display: none is overridden by JS). Fix: Use type="hidden" and ensure no JS modifies it.
    • Issue: CAPTCHA fails with "Invalid domain" errors. Cause: Incorrect site_key or secret_key in config. Fix: Verify keys match your CAPTCHA provider’s settings.

Extension Points

  1. Custom Spam Checks:

    • Extend the SpamChecker service:
      // src/Service/CustomSpamChecker.php
      use Bxnxg\AntiSpamBundle\SpamChecker\SpamCheckerInterface;
      
      class CustomSpamChecker implements SpamCheckerInterface {
          private $decorated;
      
          public function __construct(SpamCheckerInterface $decorated) {
              $this->decorated = $decorated;
          }
      
          public function isSpam(Request $request): bool {
              $isSpam = $this->decorated->isSpam($request);
              // Add custom logic (e.g., check for suspicious keywords)
              if (str_contains($request->request->get('message'), 'free offer')) {
                  $isSpam = true;
              }
              return $isSpam;
          }
      }
      
    • Register as a decorator in config/services.yaml:
      services:
          Bxnxg\AntiSpamBundle\SpamChecker\SpamChecker:
              decorates: 'bxnxg_antispam.spam_checker'
              arguments: ['@bxnxg_antispam.spam_checker.inner']
      
  2. Override Templates:

    • The bundle uses Twig templates for CAPTCHA rendering. Override them in templates/bxnxg_antispam/:
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle