Add goals repository and configurable rules engine
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
939193f258
commit
7155396312
19 files changed
+882
No files matched your search
@@ -0,0 +1,63 @@
|
||||
<?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). 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'
|
||||
) {
|
||||
if ( $unitMinor <= 0 || $secondsPerUnit < 0 ) {
|
||||
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'
|
||||
);
|
||||
}
|
||||
|
||||
/** @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 ) );
|
||||
}
|
||||
$delta = max( 0, $delta );
|
||||
if ( 0 === $delta ) {
|
||||
return array( 'delta' => 0, 'ends_at' => $endsAt, 'added_total' => $addedTotal );
|
||||
}
|
||||
// Expired (or never started) timers restart from now.
|
||||
return array(
|
||||
'delta' => $delta,
|
||||
'ends_at' => max( $endsAt, $now ) + $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 ) );
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user