Completed
Push — master ( 7bf019...08e6f3 )
by Kirill
01:45
created

GameService::getCurrentUser()   B

Complexity

Conditions 4
Paths 2

Size

Total Lines 29
Code Lines 20

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 20
nc 2
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(
64
                (
65
                    isset($message['from']['first_name'])
66
                    ? $message['from']['first_name']
67
                    : ''
68
                )
69
                .' '.
70
                (
71
                isset($message['from']['last_name'])
72
                    ? $message['from']['last_name']
73
                    : ''
74
                )
75
            );
76
            $user->setAlias($message['from']['username']);
77
            $user->setTgId($message['from']['id']);
78
            $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...
79
            $user->setChatId($message['chat']['id']);
80
            $user->setPoints(0);
81
82
            $this->em->persist($user);
83
            $this->em->flush();
84
        }
85
        return $user;
86
    }
87
88
    public function getActiveGames()
89
    {
90
        $games = $this->em->getRepository('AppBundle:Game')->findBy(['status'=>1]);
91
        return $games;
92
    }
93
    public function getInactiveGames()
94
    {
95
        $games = $this->em->getRepository('AppBundle:Game')->findBy(['status'=>0]);
96
        return $games;
97
    }
98
99
    public function checkAnswer($message)
100
    {
101
        $game = $this->findGame($message);
102
        $user = $this->getCurrentUser($message);
103
104
        if ($game->status == 1) {
105
            /** @var Question $question */
106
            $question = $this->em->getRepository('AppBundle:Question')->find($game->lastQuestion);
107
108
            if (!$question) {
109
                return;
110
            }
111
112
            if (mb_strtoupper($question->a1, 'UTF-8') == mb_strtoupper($message['text'], 'UTF-8')) {
113
                // Correct answer!
114
115
                $user->setPoints($user->getPoints()+$question->price);
116
                $this->em->persist($user);
117
118
                $this->botApi->sendMessage(
119
                    $game->chatId,
120
                    'Correct! @'.$user->getAlias().' gets *'.
121
                    $question->price.'* and now has *'.$user->getPoints().'* points!',
122
                    'markdown',
123
                    false,
124
                    $message['message_id']
125
                );
126
127
                $question->correct++;
128
                $this->em->persist($question);
129
130
                $question = $this->getRandomQuestion();
131
132
                $game->lastQuestion = $question->getId();
133
                $game->lastQuestionTime = new \DateTime('now');
134
                $game->incorrectTries = 0;
135
                
136
                $this->askQuestion($game, $question);
137
            } else {
138
                // Incorrect answer
139
                $game->incorrectTries++;
140
                $this->botApi->sendMessage(
141
                    $game->chatId,
142
                    'Wrong, @'.$user->getAlias().'. Correct answer: *'.$question->a1.'*',
143
                    'markdown'
144
                );
145
            }
146
147
            $this->em->persist($game);
148
            $this->em->flush();
149
        }
150
    }
151
152
    public function askQuestion(Game $game, Question $question)
153
    {
154
        $this->botApi->sendMessage($game->chatId, '*[question]* '.$question->text, 'markdown');
155
    }
156
157
    /**
158
     * @return Question
159
     * @throws \Doctrine\ORM\NoResultException
160
     * @throws \Doctrine\ORM\NonUniqueResultException
161
     */
162
    public function getRandomQuestion()
163
    {
164
        $count = $this->em->createQueryBuilder()
165
            ->select('COUNT(u)')->from('AppBundle:Question', 'u')
166
            ->getQuery()
167
            ->getSingleScalarResult();
168
169
        return $this->em->createQuery('SELECT c FROM AppBundle:Question c ORDER BY c.id ASC')
170
            ->setFirstResult(rand(0, $count - 1))
171
            ->setMaxResults(1)
172
            ->getSingleResult();
173
    }
174
}
175