1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Zanzara; |
6
|
|
|
|
7
|
|
|
use Closure; |
8
|
|
|
use Opis\Closure\SerializableClosure; |
9
|
|
|
use React\Promise\PromiseInterface; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* |
13
|
|
|
*/ |
14
|
|
|
class ConversationManager |
15
|
|
|
{ |
16
|
|
|
|
17
|
|
|
private const CONVERSATION = "CONVERSATION"; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var ZanzaraCache |
21
|
|
|
*/ |
22
|
|
|
private $cache; |
23
|
|
|
|
24
|
|
|
public function __construct(ZanzaraCache $cache) |
25
|
|
|
{ |
26
|
|
|
$this->cache = $cache; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Get key of the conversation by chatId |
31
|
|
|
* @param $chatId |
32
|
|
|
* @return string |
33
|
|
|
*/ |
34
|
|
|
private function getConversationKey($chatId): string |
35
|
|
|
{ |
36
|
|
|
return self::CONVERSATION . strval($chatId); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
public function setConversationHandler($chatId, $handler, bool $skipListeners): PromiseInterface |
40
|
|
|
{ |
41
|
|
|
$key = "state"; |
42
|
|
|
$cacheKey = $this->getConversationKey($chatId); |
43
|
|
|
if ($handler instanceof Closure) { |
44
|
|
|
$handler = new SerializableClosure($handler); |
45
|
|
|
} |
46
|
|
|
return $this->cache->doSet($cacheKey, $key, [serialize($handler), $skipListeners]); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
public function getConversationHandler($chatId): PromiseInterface |
50
|
|
|
{ |
51
|
|
|
return $this->cache->get($this->getConversationKey($chatId)) |
52
|
|
|
->then(function ($conversation) { |
53
|
|
|
if (empty($conversation["state"])) { |
54
|
|
|
return null; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
$handler = $conversation["state"][0]; |
58
|
|
|
$handler = unserialize($handler); |
59
|
|
|
if ($handler instanceof SerializableClosure) { |
60
|
|
|
$handler = $handler->getClosure(); |
61
|
|
|
} |
62
|
|
|
return [$handler, $conversation["state"][1]]; |
63
|
|
|
}); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* delete a cache iteam and return the promise |
68
|
|
|
* @param $chatId |
69
|
|
|
* @return PromiseInterface |
70
|
|
|
*/ |
71
|
|
|
public function deleteConversationCache($chatId): PromiseInterface |
72
|
|
|
{ |
73
|
|
|
return $this->cache->deleteCache([$this->getConversationKey($chatId)]); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
} |
77
|
|
|
|