Completed
Push — master ( 68ddf1...f17126 )
by Kirill
02:39
created

GameService::checkAnswer()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 29
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 29
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 16
nc 4
nop 1
1
<?php
2
3
namespace Chrl\AppBundle\Service;
4
5
use Chrl\AppBundle\Entity\Question;
6
use Doctrine\ORM\EntityManager;
7
use Doctrine\ORM\EntityManagerInterface;
8
use Chrl\AppBundle\Entity\Game;
9
use Chrl\AppBundle\Entity\User;
10
use Chrl\AppBundle\BuktopuhaBotApi;
11
12
/**
13
 * Game service
14
 *
15
 * @category Symfony
16
 * @package  Chrl_Buktopuha
17
 * @author   Kirill Kholodilin <[email protected]>
18
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
19
 * @link     https://take2.ru/
20
 */
21
22
class GameService
23
{
24
    /** @var EntityManager */
25
    public $em;
26
    /** @var BuktopuhaBotApi */
27
    private $botApi;
28
29
    public function __construct(BuktopuhaBotApi $telegramBotApi, $config, EntityManagerInterface $entityManager)
0 ignored issues
show
Unused Code introduced by
The parameter $config is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
30
    {
31
        $this->em = $entityManager;
0 ignored issues
show
Documentation Bug introduced by
$entityManager is of type object<Doctrine\ORM\EntityManagerInterface>, but the property $em was declared to be of type object<Doctrine\ORM\EntityManager>. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
32
        $this->botApi = $telegramBotApi;
33
    }
34
35
36
    /**
37
     * @return Game
38
     */
39
    public function findGame(array $message)
40
    {
41
        $game = $this->em->getRepository('AppBundle:Game')->findOneBy(['chatId'=>$message['chat']['id']]);
42
        if (!$game) {
43
            // create game
44
            $game = new Game();
45
            $game->status = 0;
46
            $game->chatId = $message['chat']['id'];
47
            $game->title = isset($message['chat']['title'])
48
                ? $message['chat']['title']
49
                : 'No title';
50
51
            $this->em->persist($game);
52
            $this->em->flush();
53
        }
54
        return $game;
55
    }
56
57
58
    public function getCurrentUser(array $message)
59
    {
60
        $user = $this->em->getRepository('AppBundle:User')->findOneBy(['tgId'=>$message['from']['id']]);
61
        if (!$user) {
62
            $user = new User();
63
            $user->setName($message['from']['first_name'].' '.$message['from']['last_name']);
64
            $user->setAlias($message['from']['username']);
65
            $user->setTgId($message['from']['id']);
66
            $user->setGame($this->findGame($message));
0 ignored issues
show
Documentation introduced by
$this->findGame($message) is of type object<Chrl\AppBundle\Entity\Game>, but the function expects a integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
67
            $user->setChatId($message['chat']['id']);
68
            $user->setPoints(0);
69
70
            $this->em->persist($user);
71
            $this->em->flush();
72
        }
73
        return $user;
74
    }
75
76
    public function getActiveGames()
77
    {
78
        $games = $this->em->getRepository('AppBundle:Game')->findBy(['status'=>1]);
79
        return $games;
80
    }
81
    public function getInactiveGames()
82
    {
83
        $games = $this->em->getRepository('AppBundle:Game')->findBy(['status'=>0]);
84
        return $games;
85
    }
86
87
    public function checkAnswer($message)
88
    {
89
        $game = $this->findGame($message);
90
        $user = $this->getCurrentUser($message);
91
92
        if ($game->status == 1) {
93
            /** @var Question $question */
94
            $question = $this->em->getRepository('AppBundle:Question')->find($game->lastQuestion);
95
96
            if (!$question) return;
97
98
            if (mb_strtoupper($question->a1,'UTF-8') == mb_strtoupper($message['text'],'UTF-8')) {
99
                // Correct answer!
100
                $this->botApi->sendMessage($game->chatId, 'Правильно! Следующий вопрос!');
101
                $question = $this->getRandomQuestion();
102
103
                $game->lastQuestion = $question->getId();
104
                $game->lastQuestionTime = new \DateTime('now');
105
106
                $this->em->persist($game);
107
                $this->em->flush();
108
                $this->askQuestion($game, $question);
109
110
            } else {
111
                // Incorrect answer
112
                $this->botApi->sendMessage($game->chatId, 'Неправильно, @'.$user->getAlias().'. Правильный ответ: *'.$question->a1.'*','markdown');
113
            }
114
        }
115
    }
116
117
    public function askQuestion(Game $game, Question $question)
118
    {
119
        $this->botApi->sendMessage($game->chatId, '*[#вопрос]* '.$question->text,'markdown');
120
    }
121
122
    /**
123
     * @return Question
124
     * @throws \Doctrine\ORM\NoResultException
125
     * @throws \Doctrine\ORM\NonUniqueResultException
126
     */
127
    public function getRandomQuestion()
128
    {
129
        $count = $this->em->createQueryBuilder()
130
            ->select('COUNT(u)')->from('AppBundle:Question','u')
131
            ->getQuery()
132
            ->getSingleScalarResult();
133
134
        return $this->em->createQuery('SELECT c FROM AppBundle:Question c ORDER BY c.id ASC')
135
            ->setFirstResult(rand(0, $count - 1))
136
            ->setMaxResults(1)
137
            ->getSingleResult();
138
139
    }
140
}
141