%s`. If rows_affected * is 1 the caller wins; SELECT + return the row. Otherwise return null. * * Mirrors CliAuthLog\Query::redeem_atomic (B10) exactly. * * @param string $code_hash SHA-256 hex of the raw code. * @param string $now Current GMT time in mysql format. * @return Row|null */ public function consume_atomic( string $code_hash, string $now ): ?Row { global $wpdb; if ( '' === $code_hash ) { return null; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $wpdb->query( $wpdb->prepare( 'UPDATE %i SET used = 1 WHERE code_hash = %s AND used = 0 AND expires_at > %s', $wpdb->prefix . $this->table_name, $code_hash, $now ) ); if ( 1 !== (int) $wpdb->rows_affected ) { return null; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE code_hash = %s', $wpdb->prefix . $this->table_name, $code_hash ) ); return $row ? new Row( $row ) : null; } /** * Daily cron cleanup: rows past expiry OR already used. * * @param string $now Current GMT time (mysql format). * @return int Rows deleted. */ public function delete_expired( string $now ): int { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $result = $wpdb->query( $wpdb->prepare( 'DELETE FROM %i WHERE expires_at < %s OR used = 1', $wpdb->prefix . $this->table_name, $now ) ); return is_int( $result ) ? $result : 0; } /** * FR-042 cascade: delete every pending auth code for the deleted user. * * @param int $user_id WordPress user id. * @return int Rows deleted. */ public function delete_by_user_id( int $user_id ): int { global $wpdb; if ( $user_id <= 0 ) { return 0; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $result = $wpdb->query( $wpdb->prepare( 'DELETE FROM %i WHERE user_id = %d', $wpdb->prefix . $this->table_name, $user_id ) ); return is_int( $result ) ? $result : 0; } }