PHP code example of nikolaposa / rate-limit-middleware

1. Go to this page and download the library: Download nikolaposa/rate-limit-middleware 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/ */

    

nikolaposa / rate-limit-middleware example snippets


use Laminas\Diactoros\Response\JsonResponse;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use RateLimit\Middleware\RateLimitMiddleware;
use RateLimit\Middleware\ResolveIpAddressAsUserIdentity;
use RateLimit\Middleware\ResolveUserIdentity;
use RateLimit\Rate;
use RateLimit\RateLimiter;
use RateLimit\RedisRateLimiter;

return [
    'dependencies' => [
        'invokables' => [
            ResolveUserIdentity::class => ResolveIpAddressAsUserIdentity::class,
        ],
        'factories'  => [
            'RateLimit\\Strategy\\Api' => function (ContainerInterface $container) {
                return new RedisRateLimiter(Rate::perSecond(5), $container->get(Redis::class), 'rate_limit:api:');
            },
            'RateLimit\\Strategy\\CreatePost' => function (ContainerInterface $container) {
                return new RedisRateLimiter(Rate::perDay(20), $container->get(Redis::class), 'rate_limit:web:post');
            },
            // default limit exceeded handler; anonymous class is used only for the sake 
            // of simplicity of the example
            'RateLimit\\LimitExceededRequestHandler' => function () {
                return new class implements RequestHandlerInterface {
                    public function handle(ServerRequestInterface $request): ResponseInterface
                    {
                        return new JsonResponse(['error' => 'Too many requests']);
                    }
                };
            },
            // rate limit middleware for different endpoints
            'RateLimit\\ApiRateLimitMiddleware' => function (ContainerInterface $container) {
                return new RateLimitMiddleware(
                   $container->get('RateLimiter\\Strategy\\Api'),
                   'api',
                   $container->get(ResolveUserIdentity::class),
                   $container->get('RateLimit\\LimitExceededRequestHandler')
               );
            },
            'RateLimit\\CreatePostRateLimitMiddleware' => function (ContainerInterface $container) {
                return new RateLimitMiddleware(
                   $container->get('RateLimiter\\Strategy\\CreatePost'),
                   'post.create',
                   $container->get(ResolveUserIdentity::class),
                   $container->get('RateLimit\\LimitExceededRequestHandler')
               );
            },
        ],
    ],
];

$app->get('/', App\Handler\HomePageHandler::class, 'home');

$app->get('/posts', [
    App\Handler\ListPostsHandler::class,
], 'post.list');
$app->post('/posts', [
    'RateLimit\\CreatePostRateLimitMiddleware',
    App\Handler\CreatePostHandler::class,
], 'post.create');
$app->put('/posts/:id', App\Handler\UpdatePostHandler::class, 'post.edit');

$app->route('/api/resource[/{id:[a-f0-9]{32}}]', [
    AuthenticationMiddleware::class,
    'RateLimit\\ApiRateLimitMiddleware',
    ApiResource::class,
], ['GET', 'POST', 'PATCH', 'DELETE'], 'api-resource');