Completed
Push — master ( ff6c26...e00939 )
by Kirill
02:42
created

UpdateReceiver::findGame()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
c 0
b 0
f 0
rs 9.4285
cc 3
eloc 12
nc 3
nop 1
1
<?php
2
3
namespace Chrl\AppBundle\UpdateReceiver;
4
5
use Chrl\AppBundle\BuktopuhaBotApi;
6
use Chrl\AppBundle\Entity\Game;
7
use Chrl\AppBundle\Type\Update;
8
use Doctrine\ORM\EntityManagerInterface;
9
10
class UpdateReceiver implements UpdateReceiverInterface
11
{
12
13
    private $config;
14
    private $telegramBotApi;
15
    private $entityManager;
16
17
    public function __construct(BuktopuhaBotApi $telegramBotApi, $config, EntityManagerInterface $entityManager)
18
    {
19
        $this->telegramBotApi = $telegramBotApi;
20
        $this->config = $config;
21
        $this->entityManager = $entityManager;
22
    }
23
24
    public function handleUpdate(Update $update)
25
    {
26
        $message = json_decode(json_encode($update->message), true);
27
        $game = $this->findGame($message);
28
        $this->telegramBotApi->sendMessage(
29
            $message['chat']['id'],
30
            'Hello from '.$this->config['bot_name'].' in game "'.$game->title.'"!'
31
        );
32
    }
33
34
    public function findGame(array $message)
35
    {
36
        $game = $this->entityManager->getRepository('AppBundle:Game')->findOneBy(['chatId'=>$message['chat']['id']]);
37
        if (!$game) {
38
            // create game
39
            $game = new Game();
40
            $game->status = 0;
41
            $game->chatId = $message['chat']['id'];
42
            $game->title = isset($message['chat']['title'])
43
                                ? $message['chat']['title']
44
                                : 'No title';
45
46
            $this->entityManager->persist($game);
47
            $this->entityManager->flush();
48
        }
49
        return $game;
50
    }
51
}
52