Code
Explorer
You are a developer and looking for Shopware projects?
Apply Now!
setAttempts example
$limit
=
$backoff
->
getCurrentLimit
(
$now
)
;
if
(
$tokens
>
$limit
)
{
throw
new
\
InvalidArgumentException
(
sprintf
(
'Cannot reserve more tokens (%d) than the size of the rate limiter (%d).',
$tokens
,
$limit
)
)
;
}
$attempts
=
$backoff
->
getAttempts
(
)
;
if
(
$backoff
->
shouldThrottle
(
$attempts
+
$tokens
,
$now
)
)
{
return
new
RateLimit
(
$backoff
->
getAvailableAttempts
(
$now
)
,
$backoff
->
getRetryAfter
(
)
, false,
$backoff
->
getCurrentLimit
(
$now
)
)
;
}
$backoff
->
setAttempts
(
$attempts
+
$tokens
)
;
$backoff
->
setTimer
(
$now
)
;
$backoff
->
setExpiresAt
(
$this
->reset
)
;
$this
->storage->
save
(
$backoff
)
;
return
new
RateLimit
(
$backoff
->
getAvailableAttempts
(
$now
)
,
$backoff
->
getRetryAfter
(
)
, true,
$backoff
->
getCurrentLimit
(
$now
)
)
;
}
finally
{
$this
->lock?->
release
(
)
;
}
}
}
$this
->limiter->
reserve
(
)
;
}
public
function
testThrottle
(
)
: void
{
$backoff
=
new
TimeBackoff
(
$this
->id,
$this
->config
[
'limits'
]
)
;
static
::
assertEquals
(
0,
$backoff
->
getAttempts
(
)
)
;
static
::
assertEquals
(
$this
->config
[
'limits'
]
[
0
]
[
'limit'
]
,
$backoff
->
getAvailableAttempts
(
time
(
)
)
)
;
$backoff
->
setTimer
(
time
(
)
)
;
$backoff
->
setAttempts
(
3
)
;
static
::
assertEquals
(
3,
$backoff
->
getAttempts
(
)
)
;
foreach
(
$this
->config
[
'limits'
]
as
$limit
)
{
for
(
$i
= 0;
$i
< 2; ++
$i
)
{
// request should be thorttled for new request
static
::
assertTrue
(
$backoff
->
shouldThrottle
(
$backoff
->
getAttempts
(
)
+ 1,
time
(
)
)
)
;
static
::
assertEquals
(
0,
$backoff
->
getAvailableAttempts
(
time
(
)
)
)
;
// after wait time, request could be send again
static
::
assertFalse
(
$backoff
->
shouldThrottle
(
$backoff
->
getAttempts
(
)
+ 1,
time
(
)
+
$this
->
intervalToSeconds
(
$limit
[
'interval'
]
)
)
)
;