/RateLimiter.php Secret
Created
March 22, 2017 16:36
Star
You must be signed in to star a gist
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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