Code
Explorer
You are a developer and looking for Shopware projects?
Apply Now!
SlidingWindow example
throw
new
ReserveNotSupportedException
(
__CLASS__
)
;
}
public
function
consume
(
int
$tokens
= 1
)
: RateLimit
{
$this
->lock?->
acquire
(
true
)
;
try
{
$window
=
$this
->storage->
fetch
(
$this
->id
)
;
if
(
!
$window
instanceof SlidingWindow
)
{
$window
=
new
SlidingWindow
(
$this
->id,
$this
->interval
)
;
}
elseif
(
$window
->
isExpired
(
)
)
{
$window
= SlidingWindow::
createFromPreviousWindow
(
$window
,
$this
->interval
)
;
}
$hitCount
=
$window
->
getHitCount
(
)
;
$availableTokens
=
$this
->
getAvailableTokens
(
$hitCount
)
;
if
(
$availableTokens
<
$tokens
)
{
return
new
RateLimit
(
$availableTokens
,
$window
->
getRetryAfter
(
)
, false,
$this
->limit
)
;
}
$window
->
add
(
$tokens
)
;
use
Symfony\Bridge\PhpUnit\ClockMock;
use
Symfony\Component\RateLimiter\Exception\InvalidIntervalException;
use
Symfony\Component\RateLimiter\Policy\SlidingWindow;
/** * @group time-sensitive */
class
SlidingWindowTest
extends
TestCase
{
public
function
testGetExpirationTime
(
)
{
$window
=
new
SlidingWindow
(
'foo', 10
)
;
$this
->
assertSame
(
2 * 10,
$window
->
getExpirationTime
(
)
)
;
$this
->
assertSame
(
2 * 10,
$window
->
getExpirationTime
(
)
)
;
$data
=
serialize
(
$window
)
;
sleep
(
10
)
;
$cachedWindow
=
unserialize
(
$data
)
;
$this
->
assertSame
(
10,
$cachedWindow
->
getExpirationTime
(
)
)
;
$new
= SlidingWindow::
createFromPreviousWindow
(
$cachedWindow
, 15
)
;
$this
->
assertSame
(
2 * 15,
$new
->
getExpirationTime
(
)
)
;