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
|
3 |
|
public function __construct(CacheInterface $cache) |
18
|
|
|
{ |
19
|
3 |
|
$this->cache = $cache; |
20
|
3 |
|
} |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Load context. |
24
|
|
|
* |
25
|
|
|
* @param Channel $channel |
26
|
|
|
* @param Driver $driver |
27
|
|
|
* |
28
|
|
|
* @return Context |
29
|
|
|
*/ |
30
|
1 |
|
public function load(Channel $channel, Driver $driver): Context |
31
|
|
|
{ |
32
|
1 |
|
$chat = $driver->getChat(); |
33
|
1 |
|
$user = $driver->getUser(); |
34
|
1 |
|
$key = $this->key($channel, $chat, $user); |
35
|
|
|
|
36
|
1 |
|
$value = $this->cache->get($key, []); |
37
|
|
|
|
38
|
1 |
|
return new Context($value['chat'], $value['user'], $value['items']); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* Save context. |
43
|
|
|
* |
44
|
|
|
* @param Context $context |
45
|
|
|
*/ |
46
|
1 |
|
public function save(Context $context): void |
47
|
|
|
{ |
48
|
1 |
|
$key = $this->key($context->getChannel(), $context->getChat(), $context->getUser()); |
49
|
|
|
|
50
|
1 |
|
$this->cache->set($key, $context->toArray()); |
51
|
1 |
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* Clear context. |
55
|
|
|
* |
56
|
|
|
* @param Context $context |
57
|
|
|
*/ |
58
|
1 |
|
public function clear(Context $context): void |
59
|
|
|
{ |
60
|
1 |
|
$key = $this->key($context->getChannel(), $context->getChat(), $context->getUser()); |
61
|
|
|
|
62
|
1 |
|
$this->cache->delete($key); |
63
|
1 |
|
} |
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
|
3 |
|
private function key(Channel $channel, Chat $chat, User $user): string |
75
|
|
|
{ |
76
|
3 |
|
return 'context.'.$channel->getName().'.'.$chat->getId().'.'.$user->getId(); |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|