HandleConversation::handle()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 20
c 0
b 0
f 0
ccs 0
cts 10
cp 0
rs 9.9332
cc 2
nc 2
nop 1
crap 6
1
<?php
2
3
declare(strict_types=1);
4
5
namespace FondBot\Foundation\Listeners;
6
7
use FondBot\FondBot;
8
use FondBot\Conversation\Context;
9
use FondBot\Events\MessageReceived;
10
use FondBot\Conversation\ConversationManager;
11
use Illuminate\Foundation\Bus\DispatchesJobs;
12
13
class HandleConversation
14
{
15
    use DispatchesJobs;
16
17
    private $kernel;
18
    private $conversationManager;
19
20
    public function __construct(FondBot $kernel, ConversationManager $conversationManager)
21
    {
22
        $this->kernel = $kernel;
23
        $this->conversationManager = $conversationManager;
24
    }
25
26
    public function handle(MessageReceived $messageReceived): void
27
    {
28
        /** @var Context $context */
29
        $context = $this->conversationManager->resolveContext(
30
            $this->kernel->getChannel(),
31
            $messageReceived->getChat(),
32
            $messageReceived->getFrom()
33
        );
34
35
        // If there is no interaction in session
36
        // Try to match intent and run it
37
        // Otherwise, run interaction
38
        if (!$this->isInConversation($context)) {
39
            $conversable = $this->conversationManager->matchIntent($messageReceived);
40
        } else {
41
            $conversable = $context->getInteraction();
42
        }
43
44
        $this->conversationManager->setReceivedMessage($messageReceived);
45
        $this->conversationManager->converse($conversable);
46
    }
47
48
    /**
49
     * Determine if conversation started.
50
     *
51
     * @param Context $context
52
     *
53
     * @return bool
54
     */
55
    private function isInConversation(Context $context): bool
56
    {
57
        return $context->getInteraction() !== null;
58
    }
59
}
60