PHP code example of theroadbunch / bouncer

1. Go to this page and download the library: Download theroadbunch/bouncer library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

theroadbunch / bouncer example snippets


use RoadBunch\Bouncer\Bouncer;

$subjectList = ['example', 'one', 'two', 'three'];
$bouncer = Bouncer::allow($subjectList);
$bouncer->isAllowed('example'); // true

$bouncer = Bouncer::deny($subjectList);
$bouncer->isAllowed('example'); // false

// or
$subjectList = 'example;one;two;three';
$bouncer = Bouncer::allow($subjectList);
$bouncer->isAllowed('one'); // true
$bouncer->isAllowed('not in list'); // false

$bouncer = Bouncer::deny($subjectList);
$bouncer->isAllowed('two'); // false
$bouncer->isAllowed('not in list'); // true

// or 
$subject = 'onlydomainiwanttosendemailto.com';
$bouncer = Bouncer::allow($subject);
$bouncer->isAllowed($subject); // true
$bouncer->isAllowed('example.com'); //false

use RoadBunch\Bouncer\Bouncer;

$subject = 'allowedAndThenDenied';

$bouncer = Bouncer::allow($subject);
$bouncer->isAllowed($subject); // true

$bouncer->deny($subject);
$bouncer->isAllowed($subject); // false

use RoadBunch\Bouncer\Rule;
use RoadBunch\Bouncer\BouncerFactory;

$subjectList = ['example', 'one', 'two', 'three'];
$bouncer = BouncerFactory::create(Rule::ALLOW, $subjectList);
$bouncer->isAllowed('example'); // true
$bouncer->isAllowed('not in list'); // false


declare(strict_types=1);

use Psr\Log\LoggerInterface;
use RoadBunch\Bouncer\Bouncer;
use RoadBunch\Bouncer\BouncerInterface;

class Mailer
{
    public function __construct(      
        /** ... config parameters ... */,
        private readonly LoggerInterface $logger,
        private readonly BouncerInterface $bouncer, 
    ) {}
    
    public function send(string $address, string $message): void
    {
        if (!$this->bouncer->isAllowed($address)) {
            $this->logger->warning("Cannot send email to blocked email address: {$address}");
            return;
        }
        // do work
        if (/* work fails */) {
            // deny this address in the next run
            $this->bouncer->deny($address);
            $this->logger->error("Sending failed, {$address} added to block list.")
            return;
        }
        $this->logger->info("Sending email to {$address}.");                               
    }
}

// Create a bouncer that has a DenyList
$bouncer = Bouncer::deny(['[email protected]', '[email protected]']);
$mailer = new Mailer($bouncer);

$mailer->send('[email protected]', 'Welcome!'); // logs warning
$mailer->send('[email protected]', 'Welcome!'); // sends mail