Last active
December 4, 2015 09:13
-
-
Save younes0/f90bce3ebfde005ee059 to your computer and use it in GitHub Desktop.
Rate Limit Subscriber for Guzzle 4.x + Laravel
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 | |
/** | |
* Todo: Decouple from Laravel's Caching system | |
**/ | |
use GuzzleHttp\Collection; | |
use GuzzleHttp\Event\BeforeEvent; | |
use GuzzleHttp\Event\CompleteEvent; | |
use GuzzleHttp\Event\EmitterInterface; | |
use GuzzleHttp\Event\SubscriberInterface; | |
class RateLimitSubscriber implements SubscriberInterface | |
{ | |
/** @var Collection Configuration settings */ | |
private $config; | |
public function __construct(array $config = []) | |
{ | |
$this->config = Collection::fromConfig($config, [ | |
'msBetweenRequests' => '1000', | |
]); | |
} | |
public function getEvents() | |
{ | |
return [ | |
'before' => ['onBefore'], | |
'complete' => ['onComplete'], | |
]; | |
} | |
public function onBefore(BeforeEvent $event) | |
{ | |
$ms = $this->config['msBetweenRequests'] * 1000; | |
if ($time = \Cache::get('guzzleRateLimit.'.$this->getKey($event)) ) { | |
$elapsed = microtime(true) - $time; | |
if ($elapsed < $ms) { | |
usleep($ms - $elapsed); | |
} | |
} | |
} | |
public function onComplete(CompleteEvent $event) | |
{ | |
\Cache::forever('guzzleRateLimit.'.$this->getKey($event), microtime(true)); | |
} | |
protected function getKey($event) | |
{ | |
return $event->getRequest()->getHost(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: