id = $data['id'] ?? null; $this->name = $data['name'] ?? ''; $this->conditions = $this->parseJsonField($data['conditions'] ?? '[]'); $this->actions = $this->parseJsonField($data['actions'] ?? '[]'); $this->priority = isset($data['priority']) ? (int) $data['priority'] : 10; $this->usage_limit = isset($data['usage_limit']) ? (int) $data['usage_limit'] : 0; $this->user_roles = $this->parseRolesField($data['user_roles'] ?? ''); $this->start_date = $data['start_date'] ?? null; $this->end_date = $data['end_date'] ?? null; $this->enabled = isset($data['enabled']) ? (int) $data['enabled'] : 1; $this->condition_type = $data['condition_type'] ?? ''; $this->condition_value = $data['condition_value'] ?? ''; $this->action_type = $data['action_type'] ?? ''; $this->action_value = $data['action_value'] ?? ''; $this->created_at = $data['created_at'] ?? null; $this->updated_at = $data['updated_at'] ?? null; if (empty($this->conditions) && !empty($this->condition_type)) { $this->conditions = [ ['type' => $this->condition_type, 'value' => $this->condition_value], ]; } if (empty($this->actions) && !empty($this->action_type)) { $this->actions = [ ['type' => $this->action_type, 'value' => $this->action_value], ]; } } private function parseJsonField($value) { if (is_array($value)) { return $value; } $decoded = json_decode($value, true); return is_array($decoded) ? $decoded : []; } private function parseRolesField($value) { if (is_array($value)) { return array_filter(array_map('trim', $value)); } if (!is_string($value)) { return []; } return array_filter(array_map('trim', explode(',', $value))); } /** * Convert to array */ public function toArray() { return [ 'id' => $this->id, 'name' => $this->name, 'conditions' => wp_json_encode($this->conditions), 'actions' => wp_json_encode($this->actions), 'priority' => $this->priority, 'usage_limit' => $this->usage_limit, 'user_roles' => is_array($this->user_roles) ? implode(',', $this->user_roles) : $this->user_roles, 'start_date' => $this->start_date, 'end_date' => $this->end_date, 'enabled' => $this->enabled, 'condition_type' => $this->condition_type, 'condition_value' => $this->condition_value, 'action_type' => $this->action_type, 'action_value' => $this->action_value, 'created_at' => $this->created_at, 'updated_at' => $this->updated_at, ]; } }