@@ -138,12 +138,12 @@ public function check(string $key, int $capacity, int $seconds, int $cost = 1):
138138 $ tokenName = $ this ->prefix . $ key ;
139139
140140 // Check to see if the bucket has even been created yet.
141- if (($ tokens = $ this ->cache ->get ($ tokenName )) === false )
141+ if (($ tokens = $ this ->cache ->get ($ tokenName )) === null )
142142 {
143143 // If it hasn't been created, then we'll set it to the maximum
144144 // capacity - 1, and save it to the cache.
145145 $ this ->cache ->save ($ tokenName , $ capacity - $ cost , $ seconds );
146- $ this ->cache ->save ($ tokenName . 'Time ' , time ());
146+ $ this ->cache ->save ($ tokenName . 'Time ' , time (), $ seconds );
147147
148148 return true ;
149149 }
@@ -152,32 +152,33 @@ public function check(string $key, int $capacity, int $seconds, int $cost = 1):
152152 // based on how long it's been since the last update.
153153 $ throttleTime = $ this ->cache ->get ($ tokenName . 'Time ' );
154154 $ elapsed = $ this ->time () - $ throttleTime ;
155+
155156 // Number of tokens to add back per second
156157 $ rate = $ capacity / $ seconds ;
157158
158- // We must have a minimum wait of 1 second for a new token
159+ // How many seconds till a new token is available.
160+ // We must have a minimum wait of 1 second for a new token.
159161 // Primarily stored to allow devs to report back to users.
160- $ this ->tokenTime = max (1 , $ rate );
162+ $ newTokenAvailable = (1 / $ rate ) - $ elapsed ;
163+ $ this ->tokenTime = max (1 , $ newTokenAvailable );
161164
162165 // Add tokens based up on number per second that
163166 // should be refilled, then checked against capacity
164167 // to be sure the bucket didn't overflow.
165168 $ tokens += $ rate * $ elapsed ;
166169 $ tokens = $ tokens > $ capacity ? $ capacity : $ tokens ;
167170
168- // If $tokens > 0, then we are save to perform the action, but
171+ // If $tokens > 0, then we are safe to perform the action, but
169172 // we need to decrement the number of available tokens.
170- $ response = false ;
171-
172173 if ($ tokens > 0 )
173174 {
174- $ response = true ;
175+ $ this ->cache ->save ($ tokenName , $ tokens - $ cost , $ seconds );
176+ $ this ->cache ->save ($ tokenName . 'Time ' , time (), $ seconds );
175177
176- $ this ->cache ->save ($ tokenName , $ tokens - $ cost , $ elapsed );
177- $ this ->cache ->save ($ tokenName . 'Time ' , time ());
178+ return true ;
178179 }
179180
180- return $ response ;
181+ return false ;
181182 }
182183
183184 //--------------------------------------------------------------------
0 commit comments