table_name = $wpdb->prefix . 'sodino_rules'; $this->cache = Cache::getInstance(); } /** * Get all rules */ public function getAll() { return $this->cache->remember('all_rules', function() { global $wpdb; $results = $wpdb->get_results( "SELECT * FROM {$this->table_name} ORDER BY priority DESC, id ASC", ARRAY_A ); $rules = []; foreach ($results as $result) { $rules[] = new Rule($result); } return $rules; }, $this->cache_duration, $this->cache_group); } /** * Get rule by ID */ public function getById($id) { return $this->cache->remember("rule_{$id}", function() use ($id) { global $wpdb; $result = $wpdb->get_row( $wpdb->prepare("SELECT * FROM {$this->table_name} WHERE id = %d", $id), ARRAY_A ); return $result ? new Rule($result) : null; }, $this->cache_duration, $this->cache_group); } /** * Get enabled rules */ public function getEnabled() { return $this->cache->remember('enabled_rules', function() { global $wpdb; $now = current_time('mysql'); $results = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$this->table_name} WHERE enabled = 1 AND (start_date IS NULL OR start_date <= %s) AND (end_date IS NULL OR end_date >= %s) ORDER BY priority DESC, id ASC", $now, $now ), ARRAY_A ); $rules = []; foreach ($results as $result) { $rules[] = new Rule($result); } return $rules; }, $this->cache_duration, $this->cache_group); } /** * Save rule */ public function save(Rule $rule) { global $wpdb; $data = $rule->toArray(); unset($data['id'], $data['created_at'], $data['updated_at']); if ($rule->id) { $wpdb->update($this->table_name, $data, ['id' => $rule->id]); $id = $rule->id; } else { $wpdb->insert($this->table_name, $data); $id = $wpdb->insert_id; } // Clear cache $this->clearCache(); return $id; } /** * Delete rule */ public function delete($id) { global $wpdb; $result = $wpdb->delete($this->table_name, ['id' => $id]); // Clear cache $this->clearCache(); return $result; } /** * Increment usage count */ public function incrementUsage($id) { global $wpdb; return $wpdb->query( $wpdb->prepare( "UPDATE {$this->table_name} SET usage_count = usage_count + 1 WHERE id = %d", $id ) ); } /** * Clear cache */ private function clearCache() { $this->cache->clearGroup($this->cache_group); } }