Ejemplo n.º 1
0
 public function testConsume()
 {
     $this->assertTrue($this->tokenBucket->consume(), 'Consume failed');
     $bucketArray = $this->tokenBucket->getBucket();
     $this->assertEquals(19, $bucketArray['count'], 'Token Count after consume failed');
     $this->assertNotEmpty($this->storage->get($this->tokenBucket->getBucketKey()), 'Key not found at storage');
     $this->assertArrayHasKey('count', $this->storage->get($this->tokenBucket->getBucketKey()), '"count" index not found at storage key');
     $storageVal = $this->storage->get($this->tokenBucket->getBucketKey());
     $this->assertEquals(19, $storageVal['count'], 'Token Count after consume failed');
     sleep(1);
     $this->assertFalse($this->tokenBucket->consume(22), 'Not Consume failed');
     $bucketArray = $this->tokenBucket->getBucket();
     $this->assertEquals(20, $bucketArray['count'], 'Token Count after not consumed failed');
 }
Ejemplo n.º 2
0
 public function fill()
 {
     $this->bucket = $this->storage->get($this->bucketKey);
     $now = time();
     if (is_array($this->bucket) === false || count($this->bucket) == 0 || $now >= $this->bucket['reset']) {
         $this->bucket = array('count' => $this->capacity, 'time' => $now, 'reset' => $now + $this->ttl);
     } else {
         if ($this->bucket['count'] < $this->capacity) {
             $delta = $this->fillRate * ($now - $this->bucket['time']);
             $this->bucket['count'] = min($this->capacity, $this->bucket['count'] + $delta);
         }
         $this->bucket['time'] = $now;
     }
     $this->save();
     return $this->bucket['count'];
 }