|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace FondBot\Conversation; |
|
6
|
|
|
|
|
7
|
|
|
use FondBot\Drivers\Chat; |
|
8
|
|
|
use FondBot\Drivers\User; |
|
9
|
|
|
use FondBot\Drivers\Driver; |
|
10
|
|
|
use FondBot\Channels\Channel; |
|
11
|
|
|
use Psr\SimpleCache\CacheInterface; |
|
12
|
|
|
|
|
13
|
|
|
class ContextManager |
|
14
|
|
|
{ |
|
15
|
|
|
private $cache; |
|
16
|
|
|
|
|
17
|
|
|
public function __construct(CacheInterface $cache) |
|
18
|
|
|
{ |
|
19
|
|
|
$this->cache = $cache; |
|
20
|
|
|
} |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* Load context. |
|
24
|
|
|
* |
|
25
|
|
|
* @param Channel $channel |
|
26
|
|
|
* @param Driver $driver |
|
27
|
|
|
* |
|
28
|
|
|
* @return Context |
|
29
|
|
|
*/ |
|
30
|
|
|
public function load(Channel $channel, Driver $driver): Context |
|
31
|
|
|
{ |
|
32
|
|
|
$chat = $driver->getChat(); |
|
33
|
|
|
$user = $driver->getUser(); |
|
34
|
|
|
$key = $this->key($channel, $chat, $user); |
|
35
|
|
|
|
|
36
|
|
|
$value = $this->cache->get($key, []); |
|
37
|
|
|
|
|
38
|
|
|
return new Context($value['chat'], $value['user'], $value['items']); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
/** |
|
42
|
|
|
* Save context. |
|
43
|
|
|
* |
|
44
|
|
|
* @param Context $context |
|
45
|
|
|
*/ |
|
46
|
|
|
public function save(Context $context): void |
|
47
|
|
|
{ |
|
48
|
|
|
$key = $this->key($context->getChannel(), $context->getChat(), $context->getUser()); |
|
49
|
|
|
|
|
50
|
|
|
$this->cache->set($key, $context->toArray()); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
/** |
|
54
|
|
|
* Clear context. |
|
55
|
|
|
* |
|
56
|
|
|
* @param Context $context |
|
57
|
|
|
*/ |
|
58
|
|
|
public function clear(Context $context): void |
|
59
|
|
|
{ |
|
60
|
|
|
$key = $this->key($context->getChannel(), $context->getChat(), $context->getUser()); |
|
61
|
|
|
|
|
62
|
|
|
$this->cache->delete($key); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
/** |
|
66
|
|
|
* Get key of context. |
|
67
|
|
|
* |
|
68
|
|
|
* @param Channel $channel |
|
69
|
|
|
* @param Chat $chat |
|
70
|
|
|
* @param User $user |
|
71
|
|
|
* |
|
72
|
|
|
* @return string |
|
73
|
|
|
*/ |
|
74
|
|
|
private function key(Channel $channel, Chat $chat, User $user): string |
|
75
|
|
|
{ |
|
76
|
|
|
return 'context.'.$channel->getName().'.'.$chat->getId().'.'.$user->getId(); |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
|