Passed
Push — master ( f88249...2775f1 )
by Vladimir
03:28
created

SessionManager::close()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 6
ccs 4
cts 4
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
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\Contracts\Cache;
11
use Psr\Container\ContainerInterface;
12
13
class SessionManager
14
{
15
    private $container;
16
    private $cache;
17
18 4
    public function __construct(ContainerInterface $container, Cache $cache)
19
    {
20 4
        $this->container = $container;
21 4
        $this->cache = $cache;
22 4
    }
23
24
    /**
25
     * Load session.
26
     *
27
     * @param string $channel
28
     * @param Driver $driver
29
     *
30
     * @return Session
31
     *
32
     * @throws \Psr\Container\ContainerExceptionInterface
33
     */
34 1
    public function load(string $channel, Driver $driver): Session
35
    {
36 1
        $chat = $driver->getChat();
37 1
        $sender = $driver->getUser();
38 1
        $message = $driver->getMessage();
39 1
        $key = $this->key($channel, $chat, $sender);
40 1
        $value = $this->cache->get($key);
41
42 1
        $intent = $value['intent'] !== null ? $this->container->get($value['intent']) : null;
43 1
        $interaction = $value['interaction'] !== null ? $this->container->get($value['interaction']) : null;
44
45 1
        return new Session($channel, $chat, $sender, $message, $intent, $interaction, $value['values'] ?? []);
46
    }
47
48
    /**
49
     * Save session.
50
     *
51
     * @param Session $session
52
     */
53 1
    public function save(Session $session): void
54
    {
55 1
        $key = $this->key($session->getChannel(), $session->getChat(), $session->getUser());
56
57 1
        $this->cache->store($key, $session->toArray());
58 1
    }
59
60
    /**
61
     * Close session.
62
     *
63
     * @param Session $session
64
     */
65 1
    public function close(Session $session): void
66
    {
67 1
        $key = $this->key($session->getChannel(), $session->getChat(), $session->getUser());
68
69 1
        $this->cache->forget($key);
70 1
    }
71
72
    /**
73
     * Get key of session.
74
     *
75
     * @param string $channel
76
     * @param Chat   $chat
77
     * @param User   $user
78
     *
79
     * @return string
80
     */
81 3
    private function key(string $channel, Chat $chat, User $user): string
82
    {
83 3
        return 'session.'.$channel.'.'.$chat->getId().'.'.$user->getId();
84
    }
85
}
86