PHP code example of maatify / php-rate-limiter

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

    

maatify / php-rate-limiter example snippets


use Maatify\RateLimiter\Builder\RateLimiterBuilder;
use Maatify\RateLimiter\Config\RateLimiterConfig;

/** @var FullCapabilityStoreInterface $fullCapabilityStore */
/** @var FailureSignalEmitterInterface $failureSignalEmitter */

$config = new RateLimiterConfig(
    keySecret: $activeKeySecret,
    fingerprintSecret: $activeFingerprintSecret,
    environmentScope: 'production',
);

$limiter = RateLimiterBuilder::fromFullCapabilityStore(
    $config,
    $fullCapabilityStore,
    $failureSignalEmitter,
)
    ->withPolicy($customPolicy) // Optional typed policy extension.
    ->build();

use Maatify\RateLimiter\Builder\RateLimiterBuilder;
use Maatify\RateLimiter\Command\RateLimitCommand;
use Maatify\RateLimiter\Config\RateLimiterConfig;
use Maatify\RateLimiter\DTO\RateLimitContextDTO;

/** @var RateLimitStoreInterface $rateLimitStore */
/** @var CorrelationStoreInterface $correlationStore */
/** @var CircuitBreakerStoreInterface $circuitBreakerStore */
/** @var FailureSignalEmitterInterface $failureSignalEmitter */

$limiter = new RateLimiterBuilder(
    new RateLimiterConfig($activeKeySecret, $activeFingerprintSecret, 'production'),
    $rateLimitStore,
    $correlationStore,
    $circuitBreakerStore,
    $failureSignalEmitter,
)->build();

$context = new RateLimitContextDTO(
    ip: '203.0.113.10',
    ua: 'Mozilla/5.0 Chrome/123',
    accountId: 'account-123'
);
$result = $limiter->limit($context, RateLimitCommand::checkOnly('login_protection'));

if ($result->isBlocked()) {
    http_response_code(429);
    header('Retry-After: ' . (string) $result->retryAfter);
}