PHP code example of ipapikas / gatekeeper

1. Go to this page and download the library: Download ipapikas/gatekeeper 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/ */

    

ipapikas / gatekeeper example snippets


// [GateKeeperBootstrap].php

use Gatekeeper\Gate;
use Gatekeeper\GateKeeper;
use Gatekeeper\GateRegistry;
use Gatekeeper\Keeper\DateTimeKeeper;
use Gatekeeper\Keeper\IpAddressKeeper;

// Get / Mock (Symfony) Request object
$request = new \Symfony\Component\HttpFoundation\Request();

// Initialize a gate registry
$registry = new GateRegistry();

// Create a gate that will be activated only for January 2017
$keeper = new DateTimeKeeper(new \DateTime('2017-01-01'), new \DateTime('2017-02-01'));
$gate = new Gate('January-Feature', $keeper);
$registry->register($gate);

// Create a gate that will allow access only from a specific sub-network
$keeper = new IpAddressKeeper($request, ['10.1.1.0/24'], ['20.0.1.0/24']);
$gate = new Gate('Ip-Specific-Feature', $keeper);
$registry->register($gate);

// Setup GateKeeper and set to a container (or create a singleton)
$gateKeeper = new GateKeeper($registry);
$container->set(GateKeeper::class, $gateKeeper);

// example.php

// At any point in our code, we can simply get the GateKeeper and check any gate
// Using a container (like PHP-DI) or a singleton that we have already created
$gateKeeper = $container->get(GateKeeper::class);

// Check gate
if ($gateKeeper->checkGate('January-Feature')) {
    // Gate is open
    echo 'gate is open';
} else {
    // Gate is closed
    echo 'gate is closed';
}

// MyKeeper.php

namespace MyProject\Gatekeeper\Keeper;

use Gatekeeper\Keeper\AbstractKeeper;

class MyKeeper extends AbstractKeeper
{
    /**
     * Implementation of keeper allow() function logic. 
     */
    public function allow()
    {
        // Implement your allow logic anyway you believe that suits your product
        // Remember, it has to return true for the gate to open (along with the rest of the keepers)
    }
}

// [GateKeeperBootstrap].php

use Gatekeeper\Gate;
use Gatekeeper\GateKeeper;
use Gatekeeper\GateRegistry;
use MyProject\Gatekeeper\Keeper\MyKeeper;

// Initialize a gate registry
$registry = new GateRegistry();

// Create a gate with MyKeeper
$keeper = new MyKeeper();
$gate = new Gate('My-Feature', $keeper);
$registry->register($gate);

// Create GateKeeper
$gateKeeper = new GateKeeper($registry);