Files
wp-donations/includes/Rules/AddTimeRule.php
T

70 lines
2.7 KiB
PHP
Raw Permalink Normal View History

<?php
declare( strict_types=1 );
namespace StreamGoals\Rules;
/**
* Adds seconds to a goal timer. Proportional: seconds = floor(amount * seconds_per_unit / unit_minor).
* cap_seconds_per_donation limits one donation; max_total_seconds limits the cumulative seconds
* this rule may ever add (net of reversals). maxTimer caps the remaining time on the clock (ends_at - now);
* null = uncapped. A timer already above the cap is never shortened, it just gets 0 added. The timer is an absolute ends_at timestamp.
*/
final class AddTimeRule {
public function __construct(
public readonly int $secondsPerUnit,
public readonly int $unitMinor,
public readonly ?int $capPerDonation = null,
public readonly ?int $maxTotal = null,
public readonly string $basis = 'base',
public readonly ?int $maxTimer = null
) {
if ( $unitMinor <= 0 || $secondsPerUnit < 0 || ( null !== $maxTimer && $maxTimer < 1 ) ) {
throw new \InvalidArgumentException( 'Invalid add_time config.' );
}
}
public static function fromConfig( array $c ): self {
return new self(
(int) ( $c['seconds_per_unit'] ?? 0 ),
(int) ( $c['unit_minor'] ?? 0 ),
isset( $c['cap_seconds_per_donation'] ) ? (int) $c['cap_seconds_per_donation'] : null,
isset( $c['max_total_seconds'] ) ? (int) $c['max_total_seconds'] : null,
'total' === ( $c['basis'] ?? 'base' ) ? 'total' : 'base',
isset( $c['max_timer_seconds'] ) ? (int) $c['max_timer_seconds'] : null
);
}
/** @return array{delta:int, ends_at:int, added_total:int} */
public function apply( Donation $d, int $endsAt, int $addedTotal, int $now ): array {
$delta = intdiv( $d->amountFor( $this->basis ) * $this->secondsPerUnit, $this->unitMinor );
if ( null !== $this->capPerDonation ) {
$delta = min( $delta, max( 0, $this->capPerDonation ) );
}
if ( null !== $this->maxTotal ) {
$delta = min( $delta, max( 0, $this->maxTotal - $addedTotal ) );
}
// Expired (or never started) timers restart from now.
$start = max( $endsAt, $now );
if ( null !== $this->maxTimer ) {
$delta = min( $delta, max( 0, $this->maxTimer - ( $start - $now ) ) );
}
$delta = max( 0, $delta );
if ( 0 === $delta ) {
return array( 'delta' => 0, 'ends_at' => $endsAt, 'added_total' => $addedTotal );
}
return array(
'delta' => $delta,
'ends_at' => $start + $delta,
'added_total' => $addedTotal + $delta,
);
}
/** @return array{ends_at:int, added_total:int} Never reduces below now; expired timers are untouched. */
public function reverse( int $delta, int $endsAt, int $addedTotal, int $now ): array {
if ( $endsAt > $now ) {
$endsAt = max( $now, $endsAt - $delta );
}
return array( 'ends_at' => $endsAt, 'added_total' => max( 0, $addedTotal - $delta ) );
}
}