php-github-api icon indicating copy to clipboard operation
php-github-api copied to clipboard

Feature idea - throttling rate limiter plugin

Open ondrejmirtes opened this issue 4 years ago • 0 comments

Something like this would come in handy:

<?php declare(strict_types = 1);

use Github\Api\RateLimit\RateLimitResource;
use Github\Client;
use Http\Client\Common\Plugin;
use Http\Promise\Promise;
use Psr\Http\Message\RequestInterface;

class RateLimitPlugin implements Plugin
{

	private Client $client;

	public function setClient(Client $client): void
	{
		$this->client = $client;
	}

	public function handleRequest(RequestInterface $request, callable $next, callable $first): Promise
	{
		$path = $request->getUri()->getPath();
		if ($path === '/rate_limit') {
			return $next($request);
		}

		/** @var RateLimitResource $resource */
		$resource = $this->client->api('rate_limit')->getResource('core');
		if ($resource->getRemaining() < 10) {
			$reset = $resource->getReset();
			$sleepFor = $reset - time();
			if ($sleepFor > 0) {
				sleep($sleepFor);
			}
		}

		return $next($request);
	}

}

ondrejmirtes avatar Mar 02 '21 13:03 ondrejmirtes