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

Symfony Captcha Bundle Laravel Package

carlos-mg89/symfony-captcha-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require carlos-mg89/symfony-captcha-bundle
    

    Ensure your config/bundles.php includes:

    CarlosMG89\SymfonyCaptchaBundle\CarlosMG89SymfonyCaptchaBundle::class => ['all' => true],
    
  2. Configuration Publish the default config:

    php bin/console config:dump-reference CarlosMG89\SymfonyCaptchaBundle\Configuration
    

    Update config/packages/carlos_mg89_symfony_captcha.yaml with your BotDetect license key and desired settings:

    carlos_mg89_symfony_captcha:
        license_key: "YOUR_LICENSE_KEY"
        captcha_service: "botdetect"
        default_captcha_theme: "CleanArithmetic"  # Optional: Customize theme
    
  3. First Use Case Add CAPTCHA to a form (e.g., src/Form/ContactType.php):

    use CarlosMG89\SymfonyCaptchaBundle\Form\Type\CaptchaType;
    
    $builder->add('captcha', CaptchaType::class, [
        'mapped' => false,  // CAPTCHA is not bound to an entity
        'label' => 'Verify you are human',
    ]);
    
  4. Validate Submission In your controller, verify the CAPTCHA:

    use CarlosMG89\SymfonyCaptchaBundle\Validator\Constraints\ValidCaptcha;
    
    /**
     * @ValidCaptcha(message="Invalid CAPTCHA")
     */
    public function submitForm(Request $request, ContactFormType $form) { ... }
    

Implementation Patterns

Common Workflows

  1. Form Integration

    • Use CaptchaType in any Symfony form (Symfony UX, API Platform, etc.).
    • Example with API Platform:
      use ApiPlatform\Core\Validator\Constraints\ValidEntity;
      use CarlosMG89\SymfonyCaptchaBundle\Validator\Constraints\ValidCaptcha;
      
      #[ValidCaptcha]
      #[ValidEntity]
      public function __construct(...) { ... }
      
  2. Dynamic CAPTCHA Themes Override themes in config:

    carlos_mg89_symfony_captcha:
        themes:
            "CustomTheme": { "background": "#f0f0f0", "font": "Arial" }
    

    Apply in form:

    $builder->add('captcha', CaptchaType::class, [
        'theme' => 'CustomTheme',
    ]);
    
  3. API/JSON Responses For APIs, return CAPTCHA as a JSON field:

    $captcha = $this->get('carlos_mg89_symfony_captcha.captcha_manager')->createCaptcha();
    return $this->json(['captcha' => $captcha->getImageBase64()]);
    

    Validate via:

    $validator = $this->get('validator');
    $errors = $validator->validate($request->request->all(), [
        new ValidCaptcha(),
    ]);
    
  4. Event-Driven CAPTCHA Listen for CAPTCHA generation/validation:

    // config/services.yaml
    services:
        App\EventListener\CaptchaListener:
            tags:
                - { name: kernel.event_listener, event: carlos_mg89_symfony_captcha.on_generate, method: onGenerate }
    
  5. Multi-Step Forms Store CAPTCHA token in session and validate later:

    // Step 1: Generate and store
    $session->set('captcha_token', $captcha->getToken());
    
    // Step 2: Validate
    $validator->validate($request->get('captcha_token'), [new ValidCaptcha()]);
    

Integration Tips

  • Laravel-Symfony Bridge: Use symfony/http-foundation for request/response handling if integrating with Laravel.
    $request = Request::createFromGlobals();
    $validator = $this->get('validator');
    
  • Twig Integration: Embed CAPTCHA in templates:
    {{ form_row(form.captcha) }}
    
  • Testing: Mock CAPTCHA responses in PHPUnit:
    $this->container->set('carlos_mg89_symfony_captcha.captcha_manager', $this->createMock(CaptchaManager::class));
    

Gotchas and Tips

Pitfalls

  1. License Key Validation

    • The bundle fails silently if the license key is invalid. Check logs or test with:
      $this->get('carlos_mg89_symfony_captcha.captcha_manager')->createCaptcha();
      
      Throws InvalidLicenseException if invalid.
  2. Session Dependencies

    • CAPTCHA tokens are session-bound. Ensure session.start() is called before generation/validation.
    • For APIs, use stateless mode (requires manual token storage):
      carlos_mg89_symfony_captcha:
          sessionless: true
      
  3. Caching Issues

    • BotDetect caches CAPTCHA images. Clear cache if themes change:
      php bin/console cache:clear
      
  4. Form Validation Order

    • Validate CAPTCHA after other fields to avoid redundant token generation:
      if ($form->isSubmitted() && $form->isValid()) {
          $validator->validate($form->getData(), [new ValidCaptcha()]);
      }
      
  5. Symfony 6+ Compatibility

    • The bundle targets Symfony 5/4.4. For Symfony 6, alias services in config/services.yaml:
      CarlosMG89\SymfonyCaptchaBundle\:
          resource: '../vendor/carlos-mg89/symfony-captcha-bundle/src/'
          exclude: '../vendor/carlos-mg89/symfony-captcha-bundle/src/{Entity,Migrations,Tests}/*'
      

Debugging

  1. Enable Debug Mode Set debug: true in config to log CAPTCHA generation/validation:

    carlos_mg89_symfony_captcha:
        debug: true
    
  2. Common Errors

    Error Solution
    InvalidCaptchaException Check token case-sensitivity; ensure token matches stored value.
    CaptchaNotFoundException Regenerate CAPTCHA or verify session/token storage.
    Blank CAPTCHA image Check license_key and internet connectivity (BotDetect fetches assets).
  3. Log CAPTCHA Tokens Override CaptchaManager to log tokens for debugging:

    public function createCaptcha(): Captcha
    {
        $captcha = parent::createCaptcha();
        $this->logger->debug('Generated CAPTCHA token:', ['token' => $captcha->getToken()]);
        return $captcha;
    }
    

Extension Points

  1. Custom Validators Extend ValidCaptcha constraint:

    use CarlosMG89\SymfonyCaptchaBundle\Validator\Constraints\ValidCaptcha as BaseValidCaptcha;
    
    #[Attribute]
    class CustomValidCaptcha extends BaseValidCaptcha
    {
        public function validatedBy(): string
        {
            return get_class($this) . 'Validator';
        }
    }
    
  2. Theme Customization Override BotDetect themes by extending the bundle’s Theme class:

    namespace App\Captcha;
    
    use CarlosMG89\SymfonyCaptchaBundle\Theme\Theme;
    
    class DarkTheme extends Theme
    {
        public function getBackgroundColor(): string
        {
            return '#121212';
        }
    }
    

    Register in config:

    carlos_mg89_symfony_captcha:
        themes:
            "DarkTheme": App\Captcha\DarkTheme::class
    
  3. Event Subscribers Listen for CAPTCHA events to modify behavior:

    use CarlosMG89\SymfonyCaptchaBundle\Event\CaptchaEvents;
    
    $dispatcher->addListener(CaptchaEvents::ON_GENERATE, function ($event) {
        $event->getCaptcha()->setTheme('CustomTheme');
    });
    
  4. API Platform Integration Use ApiPlatform\Metadata\Operation to add CAPTCHA to API endpoints:

    #[ApiResource(
        operations: [
            new Post(
                input: ContactInput::class,
                validationContext: [new ValidCaptcha()]
            )
        ]
    )]
    
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.
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
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