41 lines
1.2 KiB
PHP
41 lines
1.2 KiB
PHP
<?php
|
|
declare( strict_types=1 );
|
|
|
|
namespace StreamGoals\Rules;
|
|
|
|
/** $wpdb-backed EventStore over sg_rule_events. Requires live WordPress. */
|
|
final class WpEventStore implements EventStore {
|
|
|
|
private \wpdb $db;
|
|
|
|
public function __construct( ?\wpdb $db = null ) {
|
|
$this->db = $db ?? $GLOBALS['wpdb'];
|
|
}
|
|
|
|
public function record( int $ruleId, int $donationId, int $delta ): bool {
|
|
$t = $this->db->prefix . 'sg_rule_events';
|
|
$n = $this->db->query(
|
|
$this->db->prepare(
|
|
"INSERT IGNORE INTO {$t} (rule_id, donation_id, delta, reversed, created_at) VALUES (%d, %d, %d, 0, %s)",
|
|
$ruleId,
|
|
$donationId,
|
|
$delta,
|
|
gmdate( 'Y-m-d H:i:s' )
|
|
)
|
|
);
|
|
return 1 === $n;
|
|
}
|
|
|
|
public function markReversed( int $ruleId, int $donationId ): ?int {
|
|
$t = $this->db->prefix . 'sg_rule_events';
|
|
$n = $this->db->query(
|
|
$this->db->prepare( "UPDATE {$t} SET reversed = 1 WHERE rule_id = %d AND donation_id = %d AND reversed = 0", $ruleId, $donationId )
|
|
);
|
|
if ( 1 !== $n ) {
|
|
return null;
|
|
}
|
|
$delta = $this->db->get_var( $this->db->prepare( "SELECT delta FROM {$t} WHERE rule_id = %d AND donation_id = %d", $ruleId, $donationId ) );
|
|
return null === $delta ? null : (int) $delta;
|
|
}
|
|
}
|