Install via Composer:
composer require antoinelemaire/blacklist-bundle:dev-master
(Note: Use dev-master as the latest release is outdated.)
Enable the Bundle:
Add to config/bundles.php (Symfony 4+) or app/AppKernel.php (Symfony 3):
AntoineLemaire\BlacklistBundle\AntoineLemaireBlacklistBundle::class => ['all' => true],
Run Migrations:
The bundle creates a blacklist table. Run:
php bin/console doctrine:migrations:diff
php bin/console doctrine:migrations:migrate
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);
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.)
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;
Validation Integration:
$validator->validateProperty($user, 'email');
EventSubscriber (e.g., for API requests).Dynamic Blacklists: Fetch blacklists dynamically in controllers/services:
$blacklistManager = $this->get('antoinelemaire_blacklist.manager');
$isBlacklisted = $blacklistManager->isBlacklisted($email, 'email');
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');
});
Outdated Dependencies:
dev-master and patch dependencies if needed (e.g., sonata-project/admin-bundle compatibility).Annotation Parsing Issues:
php bin/console cache:clear) and check for errors in var/log/dev.log.Case Sensitivity:
$email = strtolower($email);
Performance:
Sonata Admin Conflicts:
sonata_admin configuration:
sonata_admin:
dashboard:
groups:
antoinelemaire_blacklist:
label: 'Blacklist Management'
icon: '<i class="fa fa-ban"></i>'
items:
- AntoineLemaire\BlacklistBundle\Admin\BlacklistAdmin
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."
* )
*/
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
}
}
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.
}
}
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]);
}
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"})
*/
How can I help you explore Laravel packages today?