52 lines
1.9 KiB
PHP
52 lines
1.9 KiB
PHP
<?php
|
|||
|
|
declare( strict_types=1 );
|
||
|
|
|
||
|
|
namespace StreamGoals\Overlay;
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Short-lived queue of "play this alert again" requests. The alerts overlay already knows a donation's id, so
|
||
|
|
* every request gets its own strictly increasing sequence number and the overlay plays each number once.
|
||
|
|
* Replaying only shows the alert: totals, timers, counters, rewards and tiers are never touched.
|
||
|
|
*/
|
||
|
|
final class Replays {
|
||
|
|
|
||
|
|
public const OPTION = 'sg_alert_replays';
|
||
|
|
|
||
|
|
/** Seconds a request stays on the feed. An overlay that is not open during this time never plays it. */
|
||
|
|
public const TTL = 60;
|
||
|
|
|
||
|
|
public const MAX = 10;
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Pure: well-formed, unexpired requests, oldest first.
|
||
|
|
*
|
||
|
|
* @return array<int,array{seq:int,id:int,at:int}>
|
||
|
|
*/
|
||
|
|
public static function active( mixed $stored, int $now ): array {
|
||
|
|
$out = array();
|
||
|
|
foreach ( is_array( $stored ) ? $stored : array() as $r ) {
|
||
|
|
if ( ! is_array( $r ) || ! isset( $r['seq'], $r['id'], $r['at'] ) || (int) $r['id'] <= 0 || $now - (int) $r['at'] >= self::TTL ) {
|
||
|
|
continue;
|
||
|
|
}
|
||
|
|
$out[] = array( 'seq' => (int) $r['seq'], 'id' => (int) $r['id'], 'at' => (int) $r['at'] );
|
||
|
|
}
|
||
|
|
return $out;
|
||
|
|
}
|
||
|
|
|
||
|
|
/** Pure: the queue after asking for $donationId again. The number never drops below the clock, so it cannot repeat after the queue empties. */
|
||
|
|
public static function push( mixed $stored, int $donationId, int $now ): array {
|
||
|
|
$list = self::active( $stored, $now );
|
||
|
|
$last = $list ? max( array_column( $list, 'seq' ) ) : 0;
|
||
|
|
$list[] = array( 'seq' => max( $last + 1, $now ), 'id' => $donationId, 'at' => $now );
|
||
|
|
return array_slice( $list, -self::MAX );
|
||
|
|
}
|
||
|
|
|
||
|
|
public static function request( int $donationId ): void {
|
||
|
|
update_option( self::OPTION, self::push( get_option( self::OPTION, array() ), $donationId, time() ), false );
|
||
|
|
}
|
||
|
|
|
||
|
|
/** @return array<int,array{seq:int,id:int,at:int}> */
|
||
|
|
public static function pending( int $now ): array {
|
||
|
|
return self::active( get_option( self::OPTION, array() ), $now );
|
||
|
|
}
|
||
|
|
}
|