PHP code example of sunspikes / php-ratelimiter

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

    

sunspikes / php-ratelimiter example snippets


use Sunspikes\Ratelimit\Cache\Adapter\DesarrollaCacheAdapter;
use Sunspikes\Ratelimit\Cache\Factory\DesarrollaCacheFactory;
use Sunspikes\Ratelimit\RateLimiter;
use Sunspikes\Ratelimit\Throttle\Factory\ThrottlerFactory;
use Sunspikes\Ratelimit\Throttle\Hydrator\HydratorFactory;
use Sunspikes\Ratelimit\Throttle\Settings\ElasticWindowSettings;

// 1. Make a rate limiter with limit 3 attempts in 10 minutes
$cacheAdapter = new DesarrollaCacheAdapter((new DesarrollaCacheFactory())->make());
$settings = new ElasticWindowSettings(3, 600);
$ratelimiter = new RateLimiter(new ThrottlerFactory($cacheAdapter), new HydratorFactory(), $settings);

// 2. Get a throttler for path /login
$loginThrottler = $ratelimiter->get('/login');

// 3. Register a hit
$loginThrottler->hit();

// 4. Check if it reached the limit
if ($loginThrottler->check()) {
    // access permitted
} else {
    // access denied
}

// Or combine steps 3 & 4
if ($loginThrottler->access()) {
    // access permitted
} else {
    // access denied
}

// To get the number of hits
print $loginThrottler->count();

return [
    'default_ttl' => 3600,
    'driver'      => 'memcache',
    'memcache' => [
        'servers' => ['localhost'],
    ],
];

use Sunspikes\Ratelimit\Cache\Adapter\CacheAdapterInterface;
use Sunspikes\Ratelimit\Cache\Exception\ItemNotFoundException;

class SymfonyCacheAdapter implements CacheAdapterInterface
{
    public function __construct(
        private CacheItemPoolInterface $pool
    ) {}

    public function get(string $key): mixed { /* ... */ }
    public function set(string $key, mixed $value, ?int $ttl = null): void { /* ... */ }
    public function delete(string $key): void { /* ... */ }
    public function has(string $key): bool { /* ... */ }
    public function clear(): void { /* ... */ }
}

use Sunspikes\Ratelimit\Throttle\Entity\Data;
use Sunspikes\Ratelimit\Throttle\Hydrator\DataHydratorInterface;

class RequestHydrator implements DataHydratorInterface
{
    public function hydrate(mixed $data): Data
    {
        $key = $data->getClientIp() . $data->getPathInfo();

        return new Data($key);
    }
}

use Sunspikes\Ratelimit\Throttle\Hydrator\FactoryInterface;
use Sunspikes\Ratelimit\Throttle\Hydrator\DataHydratorInterface;
use Symfony\Component\HttpFoundation\Request;

class MyHydratorFactory implements FactoryInterface
{
    public function __construct(
        private FactoryInterface $defaultFactory
    ) {}

    public function make(mixed $data): DataHydratorInterface
    {
        if ($data instanceof Request) {
            return new RequestHydrator();
        }

        return $this->defaultFactory->make($data);
    }
}

use Sunspikes\Ratelimit\Throttle\Factory\TimeAwareThrottlerFactory;
use Sunspikes\Ratelimit\Time\PhpTimeAdapter;

$cacheAdapter = new DesarrollaCacheAdapter((new DesarrollaCacheFactory())->make());
$timeAdapter = new PhpTimeAdapter();

$throttlerFactory = new TimeAwareThrottlerFactory($cacheAdapter, $timeAdapter);
$hydratorFactory = new HydratorFactory();

// $settings = ...
$ratelimiter = new RateLimiter($throttlerFactory, $hydratorFactory, $settings);

use Sunspikes\Ratelimit\Throttle\Settings\FixedWindowSettings;

// 120 attempts per minute
$settings = new FixedWindowSettings(120, 60);

use Sunspikes\Ratelimit\Throttle\Settings\MovingWindowSettings;

// 120 attempts per minute
$settings = new MovingWindowSettings(120, 60);

use Sunspikes\Ratelimit\Throttle\Settings\LeakyBucketSettings;

// 120 attempts per minute, start delaying after 30 requests
$settings = new LeakyBucketSettings(120, 60000, 30);

use Sunspikes\Ratelimit\Throttle\Settings\RetrialQueueSettings;

// Leaky bucket that delays any overflow
$settings = new RetrialQueueSettings(new LeakyBucketSettings(120, 60000, 120));
bash
composer