bandwidthThrottle\tokenBucket\TokenBucket::consume PHP Method

consume() public method

This method consumes only tokens if there are sufficient tokens available. If there aren't sufficient tokens, no tokens will be removed and the remaining seconds to wait are written to $seconds. This method is threadsafe.
public consume ( integer $tokens, &$seconds ) : boolean
$tokens integer The token amount.
return boolean If tokens were consumed.
    public function consume($tokens, &$seconds = 0)
    {
        try {
            if ($tokens > $this->capacity) {
                throw new \LengthException("Token amount ({$tokens}) is larger than the capacity ({$this->capacity}).");
            }
            if ($tokens <= 0) {
                throw new \InvalidArgumentException("Token amount ({$tokens}) should be greater than 0.");
            }
            return $this->storage->getMutex()->synchronized(function () use($tokens, &$seconds) {
                $tokensAndMicrotime = $this->loadTokensAndTimestamp();
                $microtime = $tokensAndMicrotime["microtime"];
                $availableTokens = $tokensAndMicrotime["tokens"];
                $delta = $availableTokens - $tokens;
                if ($delta < 0) {
                    $passed = microtime(true) - $microtime;
                    $seconds = max(0, $this->tokenConverter->convertTokensToSeconds($tokens) - $passed);
                    return false;
                } else {
                    $microtime += $this->tokenConverter->convertTokensToSeconds($tokens);
                    $this->storage->setMicrotime($microtime);
                    $seconds = 0;
                    return true;
                }
            });
        } catch (MutexException $e) {
            throw new StorageException("Could not lock token consumption.", 0, $e);
        }
    }

Usage Example

 /**
  * Test the capacity limit of the bucket
  *
  * @test
  */
 public function testCapacity()
 {
     $rate = new Rate(1, Rate::SECOND);
     $tokenBucket = new TokenBucket(10, $rate, new SingleProcessStorage());
     $tokenBucket->bootstrap();
     sleep(11);
     $this->assertTrue($tokenBucket->consume(10));
     $this->assertFalse($tokenBucket->consume(1));
 }
All Usage Examples Of bandwidthThrottle\tokenBucket\TokenBucket::consume