Passed
Push — develop ( c9c887...c18356 )
by Michele
53s queued 11s
created

ConversationManager   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 20
c 1
b 0
f 0
dl 0
loc 60
rs 10
wmc 8

5 Methods

Rating   Name   Duplication   Size   Complexity  
A getConversationKey() 0 3 1
A __construct() 0 3 1
A getConversationHandler() 0 14 3
A deleteConversationCache() 0 3 1
A setConversationHandler() 0 8 2
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