Skip to content

Instantly share code, notes, and snippets.

@codemasher codemasher/RateLimiter.php Secret
Created Mar 22, 2017

Embed
What would you like to do?
<?php
/**
* Class RateLimiter
*
* @link http://stackoverflow.com/questions/4257678/php-rate-limiting-client
*/
class RateLimiter{
/**
* @var int
*/
protected $limit;
/**
* @var int
*/
protected $per;
/**
* @var float
*/
protected $last_check;
/**
* @var float
*/
protected $window;
/**
* @var float|int
*/
protected $allowance;
/**
* RateLimiter constructor.
*
* @param int $limit
* @param int $per
*/
public function __construct(int $limit, int $per){
$this->limit = $limit;
$this->per = $per;
$this->last_check = microtime(true);
$this->allowance = $this->limit;
$this->window = $this->last_check + $per;
}
/**
* @param int $consumed
* @param bool $sleep
*
* @return bool
*/
public function consume($consumed = 1, $sleep = true){
$current = microtime(true);
$time_passed = $current - $this->last_check;
$this->last_check = $current;
$this->allowance += $time_passed * ($this->limit / $this->per);
if($this->allowance > $this->limit || $current > $this->window){
if($current > $this->window){
$this->window = $current + $this->per;
}
$this->allowance = $this->limit;
}
if($this->allowance < $consumed){
$duration = ($consumed - $this->allowance) * ($this->per / $this->limit);
$this->last_check += $duration;
$this->allowance = 0;
if($sleep){
usleep($duration * 1000000);
}
return false;
}
else{
$this->allowance -= $consumed;
return true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.