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

Blacklist Bundle Laravel Package

antoinelemaire/blacklist-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install via Composer:

    composer require antoinelemaire/blacklist-bundle:dev-master
    

    (Note: Use dev-master as the latest release is outdated.)

  2. Enable the Bundle: Add to config/bundles.php (Symfony 4+) or app/AppKernel.php (Symfony 3):

    AntoineLemaire\BlacklistBundle\AntoineLemaireBlacklistBundle::class => ['all' => true],
    
  3. Run Migrations: The bundle creates a blacklist table. Run:

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
  4. First Use Case: Add the @IsNotBlacklisted annotation to a property in an entity (e.g., User):

    use AntoineLemaire\BlacklistBundle\Validator\Constraints\IsNotBlacklisted;
    
    class User
    {
        /**
         * @IsNotBlacklisted(type="email")
         */
        private $email;
    }
    

    Validate via Symfony’s validator:

    $validator = $this->get('validator');
    $errors = $validator->validate($user);
    

Implementation Patterns

Core Workflow

  1. Define Blacklist Entries: Use Sonata Admin to manage blacklisted values (e.g., emails, IPs, domains) via /admin/blacklist. (Configure Sonata Admin as per the README.)

  2. Annotate Entities: Apply @IsNotBlacklisted to properties with supported types (email, email_domain, ip).

    /**
     * @IsNotBlacklisted(
     *     type="ip",
     *     message="This IP is blocked: {{ value }}",
     *     groups={"registration"}
     * )
     */
    private $ipAddress;
    
  3. Validation Integration:

    • Form Validation: Automatically triggered in Symfony forms.
    • Manual Validation: Use the validator service:
      $validator->validateProperty($user, 'email');
      
    • Event Subscribers: Extend validation logic via EventSubscriber (e.g., for API requests).
  4. Dynamic Blacklists: Fetch blacklists dynamically in controllers/services:

    $blacklistManager = $this->get('antoinelemaire_blacklist.manager');
    $isBlacklisted = $blacklistManager->isBlacklisted($email, 'email');
    

Advanced Patterns

  • Custom Types: Extend the bundle by creating a custom validator constraint and service. Override the BlacklistManager to support new types (e.g., phone_number).

    # config/services.yaml
    AntoineLemaire\BlacklistBundle\:
        manager: App\Service\CustomBlacklistManager
    
  • Bulk Validation: Validate multiple entities in a loop (e.g., CSV imports):

    foreach ($users as $user) {
        $errors = $validator->validate($user);
        if (count($errors) > 0) {
            $this->addFlash('error', 'Invalid user: ' . $user->getEmail());
        }
    }
    
  • Caching: Cache blacklist queries for performance (e.g., using Symfony’s cache component):

    $cache = $this->get('cache.app');
    $blacklist = $cache->get('blacklist_emails', function() {
        return $blacklistManager->findByType('email');
    });
    

Gotchas and Tips

Pitfalls

  1. Outdated Dependencies:

    • The bundle is unmaintained (last release: 2018). Test thoroughly with Symfony 4/5.
    • Fix: Use dev-master and patch dependencies if needed (e.g., sonata-project/admin-bundle compatibility).
  2. Annotation Parsing Issues:

    • Symfony’s validator may fail to load constraints if annotations are misconfigured.
    • Debug: Clear cache (php bin/console cache:clear) and check for errors in var/log/dev.log.
  3. Case Sensitivity:

    • Email/IP comparisons are case-sensitive by default. Normalize values before validation:
      $email = strtolower($email);
      
  4. Performance:

    • Large blacklists (e.g., millions of IPs) will slow down validation.
    • Workaround: Use a dedicated service (e.g., Redis) for blacklist storage and query optimization.
  5. Sonata Admin Conflicts:

    • If Sonata Admin routes conflict, adjust the sonata_admin configuration:
      sonata_admin:
          dashboard:
              groups:
                  antoinelemaire_blacklist:
                      label: 'Blacklist Management'
                      icon: '<i class="fa fa-ban"></i>'
                      items:
                          - AntoineLemaire\BlacklistBundle\Admin\BlacklistAdmin
      

Debugging Tips

  • Validate Manually: Test constraints independently:

    $constraint = new IsNotBlacklisted(['type' => 'email']);
    $validator = $this->get('validator');
    $violations = $validator->validateValue($email, 'email', $constraint);
    
  • Log Blacklist Queries: Enable Doctrine logging to inspect SQL queries:

    # config/packages/dev/doctrine.yaml
    doctrine:
        dbal:
            logging: true
            profiling: true
    
  • Override Validation Messages: Customize error messages in annotations:

    /**
     * @IsNotBlacklisted(
     *     type="email",
     *     message="The email {{ value }} is not allowed."
     * )
     */
    

Extension Points

  1. Custom Constraint Validator: Create a new validator for unsupported types (e.g., credit_card):

    namespace App\Validator\Constraints;
    
    use Symfony\Component\Validator\Constraint;
    use Symfony\Component\Validator\ConstraintValidator;
    
    class IsNotBlacklistedCreditCard extends ConstraintValidator
    {
        public function validate($value, Constraint $constraint)
        {
            // Custom logic to check against a blacklist
        }
    }
    
  2. Event Listeners: Trigger actions when blacklist entries are added/removed:

    namespace App\EventListener;
    
    use AntoineLemaire\BlacklistBundle\Event\BlacklistEvent;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class BlacklistListener implements EventSubscriberInterface
    {
        public static function getSubscribedEvents()
        {
            return [
                BlacklistEvent::BLACKLIST_ADDED => 'onBlacklistAdded',
            ];
        }
    
        public function onBlacklistAdded(BlacklistEvent $event)
        {
            // Send notification, log, etc.
        }
    }
    
  3. API Integration: Expose blacklist checks via an API endpoint:

    #[Route('/api/blacklist/check', name: 'api_blacklist_check', methods: ['POST'])]
    public function checkBlacklist(Request $request): JsonResponse
    {
        $data = json_decode($request->getContent(), true);
        $isBlacklisted = $this->get('antoinelemaire_blacklist.manager')->isBlacklisted($data['value'], $data['type']);
        return new JsonResponse(['blacklisted' => $isBlacklisted]);
    }
    

Configuration Quirks

  • Doctrine Behavior: The bundle uses knplabs/doctrine-behaviors for soft-deletes. Ensure your EntityManager is configured to handle behaviors:

    # config/packages/doctrine.yaml
    doctrine:
        orm:
            entity_managers:
                default:
                    mappings:
                        AntoineLemaireBlacklistBundle: false # Disable if conflicts arise
    
  • Validator Groups: Exclude blacklist validation from certain groups (e.g., default) to optimize performance:

    /**
     * @IsNotBlacklisted(type="email", groups={"registration"})
     */
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware