Skip to content

johanderuijter/garrote

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Garrote

Rate Limiter for PHP.

Works with PSR-7 HTTP message interfaces and any PSR-16 SimpleCache implementation.

Usage

Basic usage:

<?php
use JDR\Garrote\Garrote;
use JDR\Garrote\Wire;
use Zend\Diactoros\ServerRequest;

$garrote = new Garrote(new SimpleCache(), new SomeIdentificationStrategy());

$request = new ServerRequest();
$wire = new Wire('api', 10, 5);

if ($garrote->isBlocked($request, $wire)) {
    return;
}
$garrote->constrict($request, $wire);

This library comes with 2 IdentificationStrategies. The RequestAttributeIdentificationStrategy will use a given request attribute with the wire endpoint to compose an identifier.

<?php
use JDR\Garrote\Garrote;
use JDR\Garrote\RequestAttributeIdentificationStrategy;
use JDR\Garrote\Wire;
use Zend\Diactoros\ServerRequest;

$garrote = new Garrote(new SimpleCache(), new RequestAttributeIdentificationStrategy('client_ip'));

$request = (new ServerRequest())->withAttribute('client_ip', '127.0.0.1');
// ...

You can also use the CallbackIdentificationStrategy to use any callable to determine the identifier.

<?php
use JDR\Garrote\Garrote;
use JDR\Garrote\CallbackIdentificationStrategy;
use JDR\Garrote\Wire;
use Psr\Http\Message\ServerRequestInterface;
use Zend\Diactoros\ServerRequest;

$garrote = new Garrote(new SimpleCache(), new CallbackIdentificationStrategy(function (ServerRequestInterface $request, Wire $wire) {
    return sprintf('%s-%s', $request->getAttribute('client_ip'), $wire->getEndpoint());
}));

$request = (new ServerRequest())->withAttribute('client_ip', '127.0.0.1');
// ...

Lastly, you can implement your own IdentificationStrategy.

License

The MIT License (MIT). Please see License File for more information.

About

Rate Limiter for PHP.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages