Files
wordpress-theme-aksrt/src/User/BadgeAutoAward.php
T
kate522 8c5b1555c9 refactor: flatten src/AKSRT → src (drop theme-identifier dir)
Move all domain folders from src/AKSRT/{Domain} to src/{Domain}; remap
Composer PSR-4 "AKSRT\\": "src/"; update audit script + README + ADR
paths; remove dead tools/build-psr4-map.php (scanned deleted inc/classes).
2026-08-02 22:06:06 +08:00

83 lines
2.0 KiB
PHP

<?php
/**
* Auto-grant medals from catalog thresholds (zibll zib_auto_add_user_medal lite).
*
* @package AKSRT
*/
namespace AKSRT\User;
defined('ABSPATH') || exit;
class BadgeAutoAward {
private static $instance = null;
public static function get_instance(): self {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
public function init(): void {
// Run after login / current user bootstrap.
add_action('wp_login', [$this, 'on_login'], 20, 2);
add_action('wp', [$this, 'maybe_for_current_user'], 30);
// Cheap hooks for common counters.
add_action('publish_post', [$this, 'on_content_change'], 20, 1);
add_action('comment_post', [$this, 'on_content_change'], 20, 1);
add_action('aksrt_user_followed', [$this, 'on_follow'], 20, 2);
add_action('aksrt_checkin_done', [$this, 'on_checkin'], 20, 1);
}
public function on_login($user_login, $user): void {
if ($user instanceof \WP_User) {
$this->evaluate((int) $user->ID);
}
}
public function maybe_for_current_user(): void {
if (!is_user_logged_in() || is_admin()) {
return;
}
// Throttle: once per 10 minutes per user.
$uid = get_current_user_id();
$key = 'aksrt_badge_auto_' . $uid;
if (get_transient($key)) {
return;
}
set_transient($key, 1, 10 * MINUTE_IN_SECONDS);
$this->evaluate($uid);
}
public function on_content_change($arg = null): void {
$uid = get_current_user_id();
if ($uid > 0) {
$this->evaluate($uid);
}
}
public function on_follow(int $follower_id, int $following_id): void {
if ($following_id > 0) {
$this->evaluate($following_id);
}
if ($follower_id > 0) {
$this->evaluate($follower_id);
}
}
public function on_checkin(int $user_id): void {
if ($user_id > 0) {
$this->evaluate($user_id);
}
}
public function evaluate(int $user_id): void {
if ($user_id <= 0 || !class_exists('\AKSRT\User\Badges') || !Badges::enabled()) {
return;
}
Badges::auto_evaluate($user_id);
}
}