alexpts/php-rate-limiter

0.1.0 2020-12-06 19:00 UTC

This package is auto-updated.

Last update: 2024-11-05 16:25:54 UTC


README

SymfonyInsight Build Status Code Coverage Code Climate Scrutinizer Code Quality

Rate limiter + PSR-15 middleware

Install

composer require alexpts/php-rate-limiter

Example

<?php

use PTS\NextRouter\Router;
use PTS\RateLimiter\Adapter\MemoryAdapter;
use PTS\RateLimiter\Limiter;
use PTS\RateLimiter\RateLimitMiddleware;
use Zend\Diactoros\Response\JsonResponse;
use Zend\Diactoros\ServerRequestFactory;

require_once '../vendor/autoload.php';

$limitStore = new MemoryAdapter;
$rateLimiter = new Limiter($limitStore);
$response = new JsonResponse(['error' => 'Too Many Requests'], 429);

$limiterMiddleware = new RateLimitMiddleware($rateLimiter, $response);
$limiterMiddleware->setKeyAttr('ip');

$psr15Runner = new Next(); // relay or other psr-15 runner
$psr15Runner->getStoreLayers()->middleware($limiterMiddleware);

$psr7Request = ServerRequestFactory::fromGlobals();
$response = $psr15Runner->handle($psr7Request);

// flush response or other
// ...