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

153 lines
5.2 KiB
PHP
Raw Permalink Normal View History

<?php
declare( strict_types=1 );
namespace StreamGoals\Rules;
/**
* Applies/reverses donations against a goal's enabled rules. Idempotent per (rule_id, donation_id):
* the event row is recorded first, and state is only touched if that insert was new.
*
* Known limitation: state updates are read-modify-write without a lock; concurrent captures for
* the same goal could race. Wrap calls in a goal-level lock if that matters.
*/
final class Engine {
/** @var callable(string,RuleDef,Donation,bool):void|null ($event, $rule, $donation, $reversed) */
private $onBonus;
/** @var callable():int */
private $clock;
/** Production wiring: $wpdb-backed stores. */
public static function default(): self {
$onBonus = static function ( string $event, RuleDef $rule, Donation $d, bool $reversed ): void {
if ( function_exists( 'do_action' ) ) {
/**
* Fires when a big-donation bonus rule triggers (or is reversed by a refund).
*
* @param string $event Rule's event name.
* @param int $donationId Donation id.
* @param int $ruleId Rule id.
* @param bool $reversed True when the bonus was undone.
*/
do_action( 'streamgoals_bonus', $event, $d->id, $rule->id, $reversed );
}
};
return new self( new WpRuleStore(), new WpEventStore(), new \StreamGoals\Core\StateStore(), null, $onBonus );
}
/**
* Serialize state updates per goal using a MySQL named lock, so simultaneous captures
* (e.g. a raid) cannot lose timer/counter updates. Falls back to running unlocked if the lock is unavailable.
*/
public static function withGoalLock( int $goalId, callable $fn ): void {
global $wpdb;
$name = 'sg_goal_' . $goalId;
$locked = $wpdb && 1 === (int) $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s, 5)', $name ) );
try {
$fn();
} finally {
if ( $locked ) {
$wpdb->get_var( $wpdb->prepare( 'SELECT RELEASE_LOCK(%s)', $name ) );
}
}
}
public function __construct(
private readonly RuleStore $rules,
private readonly EventStore $events,
private readonly StateRepository $state,
?callable $clock = null,
?callable $onBonus = null
) {
$this->clock = $clock ?? static fn(): int => time();
$this->onBonus = $onBonus;
}
public function applyDonation( Donation $d ): void {
foreach ( $this->rules->enabledForGoal( $d->goalId ) as $def ) {
try {
$this->applyRule( $def, $d );
} catch ( \InvalidArgumentException ) {
continue; // Misconfigured rule must not block the others.
}
}
}
public function reverseDonation( Donation $d ): void {
foreach ( $this->rules->enabledForGoal( $d->goalId ) as $def ) {
if ( ! $def->reverseOnRefund() ) {
continue;
}
try {
$this->reverseRule( $def, $d );
} catch ( \InvalidArgumentException ) {
continue;
}
}
}
private function applyRule( RuleDef $def, Donation $d ): void {
$g = $d->goalId;
switch ( $def->type ) {
case 'add_time':
$rule = AddTimeRule::fromConfig( $def->config );
$k = "timer_added:{$def->id}";
$r = $rule->apply( $d, $this->state->getInt( $g, 'timer_ends_at' ), $this->state->getInt( $g, $k ), ( $this->clock )() );
if ( ! $this->events->record( $def->id, $d->id, $r['delta'] ) ) {
return;
}
if ( $r['delta'] > 0 ) {
$this->state->setInt( $g, 'timer_ends_at', $r['ends_at'] );
$this->state->setInt( $g, $k, $r['added_total'] );
}
return;
case 'counter':
$rule = CounterRule::fromConfig( $def->config );
$r = $rule->apply( $d, $this->state->getInt( $g, "counter:{$def->id}" ), $this->state->getInt( $g, "carry:{$def->id}" ) );
if ( ! $this->events->record( $def->id, $d->id, $r['delta'] ) ) {
return;
}
$this->state->setInt( $g, "counter:{$def->id}", $r['counter'] );
$this->state->setInt( $g, "carry:{$def->id}", $r['carry'] );
return;
case 'bonus':
$rule = BonusRule::fromConfig( $def->config );
$fired = $rule->apply( $d );
if ( ! $this->events->record( $def->id, $d->id, $fired ) ) {
return;
}
if ( $fired && $this->onBonus ) {
( $this->onBonus )( $rule->event, $def, $d, false );
}
return;
}
}
private function reverseRule( RuleDef $def, Donation $d ): void {
$g = $d->goalId;
$delta = $this->events->markReversed( $def->id, $d->id );
if ( null === $delta ) {
return; // Never applied, or already reversed.
}
switch ( $def->type ) {
case 'add_time':
$k = "timer_added:{$def->id}";
$r = AddTimeRule::fromConfig( $def->config )->reverse( $delta, $this->state->getInt( $g, 'timer_ends_at' ), $this->state->getInt( $g, $k ), ( $this->clock )() );
if ( $delta > 0 ) {
$this->state->setInt( $g, 'timer_ends_at', $r['ends_at'] );
$this->state->setInt( $g, $k, $r['added_total'] );
}
return;
case 'counter':
$r = CounterRule::fromConfig( $def->config )->reverse( $d, $delta, $this->state->getInt( $g, "counter:{$def->id}" ), $this->state->getInt( $g, "carry:{$def->id}" ) );
$this->state->setInt( $g, "counter:{$def->id}", $r['counter'] );
$this->state->setInt( $g, "carry:{$def->id}", $r['carry'] );
return;
case 'bonus':
if ( $delta > 0 && $this->onBonus ) {
( $this->onBonus )( BonusRule::fromConfig( $def->config )->event, $def, $d, true );
}
return;
}
}
}