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

alexsabur/antispam-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:

    composer require alexsabur/antispam-bundle
    

    (Note: The original package is nucleos/antispam-bundle, but the composer.json specifies alexsabur/antispam-bundle. Verify the correct package name before installation.)

  2. Enable the bundle in config/bundles.php:

    return [
        // ...
        Nucleos\AntiSpamBundle\NucleosAntiSpamBundle::class => ['all' => true],
    ];
    
  3. Configure basic settings in config/packages/nucleos_antispam.yaml:

    nucleos_antispam:
        time:
            min: 5  # Minimum seconds between form display and submission
            max: 3600
        honeypot:
            field: 'email_address'
            class: 'hidden'
    
  4. First use case: Protect a form Add time protection to a form type in the controller:

    $this->createForm(CustomFormType::class, null, [
        'antispam_time' => true,
        'antispam_time_min' => 10,
    ]);
    

First Twig Usage

Apply email obfuscation in Twig:

{{ 'contact@example.com'|antispam }}

(Output: contact[AT]example.com)


Implementation Patterns

Form Protection Workflows

  1. Global vs. Per-Form Configuration

    • Use global: true in nucleos_antispam.yaml to apply time/honeypot protection to all forms without manual configuration.
    • Override globally applied settings in the form type or controller for specific forms.
  2. Form Type Integration Configure options in configureOptions():

    public function configureOptions(OptionsResolver $resolver): void {
        $resolver->setDefaults([
            'antispam_honeypot' => true,
            'antispam_honeypot_field' => 'spam_field',
            'antispam_time_min' => 15,
        ]);
    }
    
  3. Dynamic Field Naming Use a unique antispam_honeypot_field name (e.g., spam_field_{$formId}) to avoid conflicts in multi-form pages.


Twig Email Obfuscation

  1. Rich Text Handling Use the second parameter (true) for HTML content to preserve formatting:

    {{ htmlContent|antispam(true) }}
    
  2. JavaScript Decoding Include AntiSpam.js via Webpack Encore:

    // assets/js/antispam.js
    import AntiSpam from 'nucleos-antispam-bundle/AntiSpam';
    document.addEventListener('DOMContentLoaded', () => {
        new AntiSpam('.email-class');
    });
    

    (Ensure the JS file is copied to public/ via Webpack.)

  3. Custom CSS Classes Configure css_class in nucleos_antispam.yaml to target specific elements:

    nucleos_antispam:
        twig:
            mail:
                css_class: 'obfuscated-email'
    

Event-Driven Extensions

Leverage Symfony’s event system to extend functionality:

  1. Listen for Form Submission Subscribe to FormEvent::SUBMIT to log or analyze spam attempts:

    // src/EventListener/AntiSpamListener.php
    public function onFormSubmit(FormEvent $event) {
        $form = $event->getForm();
        if ($form->has('spam_field')) {
            $this->logger->warning('Potential spam detected');
        }
    }
    
  2. Custom Validation Add a validator to reject forms with invalid time/honeypot data:

    use Nucleos\AntiSpamBundle\Validator\Constraints\AntiSpam;
    
    $builder->add('your_field', null, [
        new AntiSpam(['time_min' => 10]),
    ]);
    

Gotchas and Tips

Pitfalls

  1. Session Dependency

    • Time protection relies on the session. Ensure session.start() is called before form rendering.
    • Fix: Add session_start() in your AppKernel or use Symfony’s built-in session handling.
  2. JavaScript Conflicts

    • AntiSpam.js may interfere with other JS libraries if not scoped properly.
    • Fix: Use a unique CSS class and namespace the JS:
      new AntiSpam('.my-app-emails');
      
  3. Form Type Overrides

    • Globally applied settings (e.g., global: true) may conflict with explicit form configurations.
    • Fix: Use null to disable global settings for a specific form:
      'antispam_time' => null, // Disables global time protection
      
  4. Deprecated Session Methods

    • The bundle uses Symfony’s session component. If you upgrade Symfony, check for deprecation warnings (e.g., Session::get()Session::getBag('default')).
    • Fix: Update the bundle or patch locally (see PR #399).

Debugging Tips

  1. Log Spam Attempts Enable debug mode and check logs for AntiSpamBundle entries:

    monolog:
        handlers:
            main:
                level: debug
                channels: ['!event']
    
  2. Inspect Form HTML Verify honeypot fields are rendered with the correct CSS class:

    <input type="text" name="spam_field" class="hidden" />
    

    (Use browser dev tools to check if .hidden is applied.)

  3. Time Protection Validation

    • If time checks fail, verify:
      • The session is active.
      • antispam_time_min/max values are reasonable (e.g., min: 5).
      • No JavaScript is disabling the form submission timer.

Extension Points

  1. Custom Honeypot Fields Override the default field provider:

    nucleos_antispam:
        honeypot:
            provider: 'app.custom_honeypot_provider'
    

    (Implement Nucleos\AntiSpamBundle\Provider\HoneypotProviderInterface.)

  2. Email Obfuscation Patterns Extend the Twig filter by subclassing the default provider:

    // src/Twig/AntiSpamExtension.php
    class CustomAntiSpamExtension extends \Nucleos\AntiSpamBundle\Twig\AntiSpamExtension {
        public function getAtReplacements() {
            return ['[AT]', '(AT)', 'AT']; // Add custom patterns
        }
    }
    

    Register the service in services.yaml:

    services:
        Nucleos\AntiSpamBundle\Twig\AntiSpamExtension:
            alias: 'app.custom_antispam_extension'
            public: true
    
  3. Custom Validation Messages Override default error messages in config/packages/validation.yaml:

    Nucleos\AntiSpamBundle\Validator\Constraints\AntiSpam:
        message: 'This form was submitted too quickly. Please try again.'
    

Configuration Quirks

  1. YAML vs. PHP Config

    • The bundle supports both YAML (nucleos_antispam.yaml) and PHP (config/packages/nucleos_antispam.php).
    • Tip: Use PHP config for dynamic values (e.g., fetching min/max from a database).
  2. Global Settings Precedence

    • Controller options > Form type options > Global config.
    • Example: A form type can disable global honeypot protection:
      $resolver->setDefaults(['antispam_honeypot' => false]);
      
  3. Asset Paths

    • The JS file (AntiSpam.js) is in the assets folder. Ensure Webpack Encore copies it to public/build/:
      // webpack.config.js
      Encore
          .addEntry('antispam', './assets/js/antispam.js')
          .copyFiles({
              from: './assets/js/AntiSpam.js',
              to: 'build/[name].js',
          });
      
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor