Final Class Yiisoft\Yii\RateLimiter\LimitRequestsMiddleware
| Inheritance | Yiisoft\Yii\RateLimiter\LimitRequestsMiddleware |
|---|---|
| Implements | Psr\Http\Server\MiddlewareInterface |
RateLimiter helps to prevent abuse by limiting the number of requests that could be me made consequentially.
For example, you may want to limit the API usage of each user to be at most 100 API calls within a period of 10 minutes. If too many requests are received from a user within the stated period of the time, a response with status code 429 (meaning "Too Many Requests") should be returned.
Psalm Types
| Name | Value |
|---|---|
| CounterIdCallback | callable |
Public Methods
| Method | Description | Defined By |
|---|---|---|
| __construct() | Yiisoft\Yii\RateLimiter\LimitRequestsMiddleware | |
| process() | Yiisoft\Yii\RateLimiter\LimitRequestsMiddleware |
Method Details
| public mixed __construct ( Yiisoft\Yii\RateLimiter\CounterInterface $counter, \Psr\Http\Message\ResponseFactoryInterface $responseFactory, Yiisoft\Yii\RateLimiter\Policy\LimitPolicyInterface|null $limitingPolicy = null, \Psr\Http\Server\MiddlewareInterface|null $failStoreUpdatedDataMiddleware = null ) | ||
| $counter | Yiisoft\Yii\RateLimiter\CounterInterface | |
| $responseFactory | \Psr\Http\Message\ResponseFactoryInterface | |
| $limitingPolicy | Yiisoft\Yii\RateLimiter\Policy\LimitPolicyInterface|null | |
| $failStoreUpdatedDataMiddleware | \Psr\Http\Server\MiddlewareInterface|null | |
public function __construct(
private CounterInterface $counter,
private ResponseFactoryInterface $responseFactory,
LimitPolicyInterface|null $limitingPolicy = null,
private ?MiddlewareInterface $failStoreUpdatedDataMiddleware = null,
) {
$this->limitingPolicy = $limitingPolicy ?: new LimitPerIp();
}
| public \Psr\Http\Message\ResponseInterface process ( \Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Server\RequestHandlerInterface $handler ) | ||
| $request | \Psr\Http\Message\ServerRequestInterface | |
| $handler | \Psr\Http\Server\RequestHandlerInterface | |
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$state = $this->counter->hit($this->limitingPolicy->fingerprint($request));
if ($state->isLimitReached()) {
$response = $this->createErrorResponse();
} elseif ($state->isFailStoreUpdatedData() && $this->failStoreUpdatedDataMiddleware !== null) {
$response = $this->failStoreUpdatedDataMiddleware->process($request, $handler);
} else {
$response = $handler->handle($request);
}
return $this->addHeaders($response, $state);
}
Signup or Login in order to comment.