Core\RateLimit\Decision::remaining
$decision->remaining(): uintReturns how many units a key can still use after a rate-limited call.
The number is counted after the call itself. With a limit of 3 per minute, the first call gives 2, the second gives 1 and the third gives 0. A result of 0 means the next call has to wait.
A call that is not allowed uses no units. With 6 units left, a call that costs 7 is not allowed, and remaining is still 6.
Good to know: units come back as time passes, so the number is correct only for the moment of the call. Use it for a RateLimit-Remaining header or for a message such as "2 exports left today".
Return value
Returns uint. The units left in the burst, after this call was charged. It is 0 when the next unit has to wait.
Examples
Counts down to zero
<?nvs// Shows how `remaining` counts the calls that are still allowed.
// The limit is 3 calls per minute. `remaining` is counted after each call,// so this prints 2, 1 and 0. The fourth call is refused, and it is also 0.uint $call = 1;while ($call <= 4) { var $decision = Core\RateLimit::consumeLocally('search:user:5', 3, 1m); echo 'call ', $call, ': ', $decision->remaining(), " left\n"; $call = $call + 1;}call 1: 2 leftcall 2: 1 leftcall 3: 0 leftcall 4: 0 leftA large call that does not fit
<?nvs// Shows `remaining` when each call has a cost. A refused call uses no units.
class Report{ public static function run(uint $pages): void { // Each user may print 10 pages per hour. var $decision = Core\RateLimit::consumeLocally('print:user:2', 10, 1h, { cost: $pages }); echo $pages, ' pages: ', $decision->isAllowed() ? 'printed' : 'refused'; echo ', ', $decision->remaining(), " pages left\n"; }}
// 4 pages leave 6. 7 pages do not fit, so 6 are still left.// 6 pages then use the rest, and 0 are left.Report::run(4);Report::run(7);Report::run(6);4 pages: printed, 6 pages left7 pages: refused, 6 pages left6 pages: printed, 0 pages leftExports left today
<?nvs// Shows a message that tells a user how many exports they have left today.
class Export{ public static function message(string $user): string { // Each user may export 3 files per day. var $decision = Core\RateLimit::consumeLocally('export:' . $user, 3, 24h); if (!$decision->isAllowed()) { return 'You have no exports left today.'; } if ($decision->remaining() == 0) { return 'Your file is ready. This was your last export today.'; } return 'Your file is ready. Exports left today: ' . $decision->remaining(); }}
uint $i = 0;while ($i < 4) { echo Export::message('maria'), "\n"; $i = $i + 1;}Your file is ready. Exports left today: 2Your file is ready. Exports left today: 1Your file is ready. This was your last export today.You have no exports left today.