Skip to content

Commit

Permalink
RateLimiter :: headers
Browse files Browse the repository at this point in the history
  • Loading branch information
atakde committed Dec 7, 2022
1 parent 63a5884 commit 0df30b5
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/RateLimiter.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,18 @@ class RateLimiter
private int $maxAmmount;
private int $refillTime;
private StorageInterface $storage;
private array $headers = [
'X-RateLimit-Limit' => '{{maxAmmount}}',
'X-RateLimit-Remaining' => '{{currentAmmount}}',
'X-RateLimit-Reset' => '{{reset}}',
];

public function __construct(array $options, StorageInterface $storage)
{
$this->prefix = $options['prefix'];
$this->maxAmmount = $options['maxAmmount'];
$this->refillTime = $options['refillTime'];
$this->headers = $options['headers'] ?? $this->headers;
$this->storage = $storage;
}

Expand Down Expand Up @@ -74,4 +80,18 @@ public function delete(string $identifier): void
$key = $this->prefix . $identifier;
$this->storage->delete($key);
}

public function headers(string $identifier): array
{
$key = $this->prefix . $identifier;
$lastCheck = $this->storage->get($key . 'last_check');
$headers = [];
foreach ($this->headers as $key => $value) {
$headers[$key] = str_replace('{{maxAmmount}}', $this->maxAmmount, $value);
$headers[$key] = str_replace('{{currentAmmount}}', $this->get($identifier), $headers[$key]);
$headers[$key] = str_replace('{{reset}}', $lastCheck + $this->refillTime, $headers[$key]);
}

return $headers;
}
}

0 comments on commit 0df30b5

Please sign in to comment.