Update ConversationStateService.php

This commit is contained in:
Lizandro Guarnizo
2026-01-24 01:58:05 -05:00
parent 6e89b1868b
commit d5ff1f2df9
+21 -40
View File
@@ -37,14 +37,10 @@ class ConversationStateService
*/
public function getState(string $phoneNumber): ?array
{
$stmt = $this->db->prepare("
SELECT * FROM user_states
WHERE phone_number = ?
ORDER BY id DESC
LIMIT 1
");
$stmt->execute([$phoneNumber]);
$state = $stmt->fetch(PDO::FETCH_ASSOC);
$state = $this->db->fetch(
"SELECT * FROM user_states WHERE phone_number = :phone ORDER BY id DESC LIMIT 1",
['phone' => $phoneNumber]
);
if ($state && $state['state_data']) {
$state['state_data'] = json_decode($state['state_data'], true);
@@ -62,18 +58,17 @@ class ConversationStateService
*/
public function setState(string $phoneNumber, string $state, array $data = []): bool
{
$stmt = $this->db->prepare("
INSERT INTO user_states (phone_number, state, state_data, created_at, updated_at)
VALUES (?, ?, ?, NOW(), NOW())
$sql = "INSERT INTO user_states (phone_number, state, state_data, created_at, updated_at)
VALUES (:phone, :state, :state_data, NOW(), NOW())
ON DUPLICATE KEY UPDATE
state = VALUES(state),
state_data = VALUES(state_data),
updated_at = NOW()
");
updated_at = NOW()";
$stateDataJson = !empty($data) ? json_encode($data, JSON_UNESCAPED_UNICODE) : null;
return $stmt->execute([$phoneNumber, $state, $stateDataJson]);
$this->db->query($sql, ['phone' => $phoneNumber, 'state' => $state, 'state_data' => $stateDataJson]);
return true;
}
/**
@@ -93,16 +88,11 @@ class ConversationStateService
$existingData = $currentState['state_data'] ?? [];
$mergedData = array_merge($existingData, $data);
$stmt = $this->db->prepare("
UPDATE user_states
SET state_data = ?, updated_at = NOW()
WHERE phone_number = ?
");
return $stmt->execute([
json_encode($mergedData, JSON_UNESCAPED_UNICODE),
$phoneNumber
]);
$this->db->query(
"UPDATE user_states SET state_data = :sd, updated_at = NOW() WHERE phone_number = :phone",
['sd' => json_encode($mergedData, JSON_UNESCAPED_UNICODE), 'phone' => $phoneNumber]
);
return true;
}
/**
@@ -129,12 +119,7 @@ class ConversationStateService
*/
public function clearState(string $phoneNumber): bool
{
$stmt = $this->db->prepare("
DELETE FROM user_states
WHERE phone_number = ?
");
return $stmt->execute([$phoneNumber]);
return $this->db->delete('user_states', 'phone_number = :phone', ['phone' => $phoneNumber]);
}
/**
@@ -232,18 +217,14 @@ class ConversationStateService
*/
public function cleanExpiredStates(): int
{
$stmt = $this->db->prepare("
DELETE FROM user_states
$sql = "DELETE FROM user_states
WHERE updated_at < DATE_SUB(NOW(), INTERVAL 30 MINUTE)
AND state NOT IN (?, ?)
");
$stmt->execute([
AND state NOT IN (?, ?)";
return $this->db->execute($sql, [
self::STATE_SCHEDULED,
self::STATE_WITH_ADVISOR
]);
return $stmt->rowCount();
}
/**