Skip to content

Instantly share code, notes, and snippets.

@younes0
Last active December 4, 2015 09:13
Show Gist options
  • Save younes0/f90bce3ebfde005ee059 to your computer and use it in GitHub Desktop.
Save younes0/f90bce3ebfde005ee059 to your computer and use it in GitHub Desktop.
Rate Limit Subscriber for Guzzle 4.x + Laravel
<?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();
}
}
@younes0
Copy link
Author

younes0 commented Aug 4, 2014

Usage:

$client->getEmitter()->attach(new RateLimitSubscriber([
    'msBetweenRequests' => 2000,
]));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment