Completed
Push — master ( 92f9ab...467cb1 )
by greg
05:24 queued 02:28
created

Quiz::updatePrediction()   C

Complexity

Conditions 8
Paths 10

Size

Total Lines 89

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 89
rs 6.9955
c 0
b 0
f 0
cc 8
nc 10
nop 1

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace PlaygroundGame\Service;
4
5
use PlaygroundGame\Entity\QuizReply;
6
use PlaygroundGame\Entity\QuizReplyAnswer;
7
use PlaygroundGame\Mapper\GameInterface as GameMapperInterface;
8
use Zend\Stdlib\ErrorHandler;
9
10
class Quiz extends Game
11
{
12
    /**
13
     * @var QuizMapperInterface
14
     */
15
    protected $quizMapper;
16
17
    /**
18
     * @var QuizAnswerMapperInterface
19
     */
20
    protected $quizAnswerMapper;
21
22
    /**
23
     * @var QuizQuestionMapperInterface
24
     */
25
    protected $quizQuestionMapper;
26
27
    /**
28
     * @var QuizReplyMapperInterface
29
     */
30
    protected $quizReplyMapper;
31
32
    /**
33
     * @var quizReplyAnswerMapper
34
     */
35
    protected $quizReplyAnswerMapper;
36
37
    /**
38
     *
39
     *
40
     * @param  array                  $data
41
     * @return \PlaygroundGame\Entity\Game
42
     */
43
    public function createQuestion(array $data)
44
    {
45
        $path      = $this->getOptions()->getMediaPath().DIRECTORY_SEPARATOR;
46
        $media_url = $this->getOptions()->getMediaUrl().'/';
47
48
        $question = new \PlaygroundGame\Entity\QuizQuestion();
49
        $form     = $this->serviceLocator->get('playgroundgame_quizquestion_form');
50
        $form->bind($question);
51
        $form->setData($data);
52
53
        $quiz = $this->getGameMapper()->findById($data['quiz_id']);
54
        if (!$form->isValid()) {
55
56
            return false;
57
        }
58
59
        $question->setQuiz($quiz);
60
61
        // Max points and correct answers calculation for the question
62
        if (!$question = $this->calculateMaxAnswersQuestion($question)) {
63
            return false;
64
        }
65
66
        // Max points and correct answers recalculation for the quiz
67
        $quiz = $this->calculateMaxAnswersQuiz($question->getQuiz());
0 ignored issues
show
Bug introduced by
The method getQuiz cannot be called on $question (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
68
69
        $this->getEventManager()->trigger(__FUNCTION__, $this, array('game' => $question, 'data' => $data));
70
        $this->getQuizQuestionMapper()->insert($question);
71
        $this->getEventManager()->trigger(__FUNCTION__ .'.post', $this, array('game' => $question, 'data' => $data));
72
73 View Code Duplication
        if (!empty($data['upload_image']['tmp_name'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
74
            ErrorHandler::start();
75
            $data['upload_image']['name'] = $this->fileNewname(
76
                $path,
77
                $question->getId()."-".$data['upload_image']['name']
0 ignored issues
show
Bug introduced by
The method getId cannot be called on $question (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
78
            );
79
            move_uploaded_file($data['upload_image']['tmp_name'], $path.$data['upload_image']['name']);
80
            $question->setImage($media_url.$data['upload_image']['name']);
0 ignored issues
show
Bug introduced by
The method setImage cannot be called on $question (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
81
            ErrorHandler::stop(true);
82
        }
83
84
        $this->getQuizQuestionMapper()->update($question);
85
        $this->getQuizMapper()->update($quiz);
86
87
        return $question;
88
    }
89
90
    /**
91
     * @param  array $data
92
     * @return \PlaygroundGame\Entity\Game
93
     */
94
    public function updateQuestion(array $data, $question)
95
    {
96
        $path      = $this->getOptions()->getMediaPath().DIRECTORY_SEPARATOR;
97
        $media_url = $this->getOptions()->getMediaUrl().'/';
98
99
        $form = $this->serviceLocator->get('playgroundgame_quizquestion_form');
100
        $form->bind($question);
101
        $form->setData($data);
102
103
        if (!$form->isValid()) {
104
            return false;
105
        }
106
107
        // Max points and correct answers calculation for the question
108
        if (!$question = $this->calculateMaxAnswersQuestion($question)) {
109
            return false;
110
        }
111
112 View Code Duplication
        if (!empty($data['upload_image']['tmp_name'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
113
            ErrorHandler::start();
114
            $data['upload_image']['name'] = $this->fileNewname(
115
                $path,
116
                $question->getId()."-".$data['upload_image']['name']
0 ignored issues
show
Bug introduced by
The method getId cannot be called on $question (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
117
            );
118
            move_uploaded_file($data['upload_image']['tmp_name'], $path.$data['upload_image']['name']);
119
            $question->setImage($media_url.$data['upload_image']['name']);
0 ignored issues
show
Bug introduced by
The method setImage cannot be called on $question (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
120
            ErrorHandler::stop(true);
121
        }
122
123
        if (isset($data['delete_image']) && !empty($data['delete_image']) && empty($data['upload_image']['tmp_name'])) {
124
            ErrorHandler::start();
125
            $image = $question->getImage();
0 ignored issues
show
Bug introduced by
The method getImage cannot be called on $question (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
126
            $image = str_replace($media_url, '', $image);
127
            if (file_exists($path.$image)) {
128
                unlink($path.$image);
129
            }
130
            $question->setImage(null);
0 ignored issues
show
Bug introduced by
The method setImage cannot be called on $question (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
131
            ErrorHandler::stop(true);
132
        }
133
134
        $i = 0;
135
        foreach ($question->getAnswers() as $answer) {
0 ignored issues
show
Bug introduced by
The method getAnswers cannot be called on $question (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
136
            if (!empty($data['answers'][$i]['upload_image']['tmp_name'])) {
137
                ErrorHandler::start();
138
                $data['answers'][$i]['upload_image']['name'] = $this->fileNewname(
139
                    $path,
140
                    $question->getId()."-".$data['answers'][$i]['upload_image']['name']
0 ignored issues
show
Bug introduced by
The method getId cannot be called on $question (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
141
                );
142
                move_uploaded_file(
143
                    $data['answers'][$i]['upload_image']['tmp_name'],
144
                    $path.$data['answers'][$i]['upload_image']['name']
145
                );
146
                $answer->setImage($media_url.$data['answers'][$i]['upload_image']['name']);
147
                ErrorHandler::stop(true);
148
            }
149
            $i++;
150
        }
151
152
        // Max points and correct answers recalculation for the quiz
153
        $quiz = $this->calculateMaxAnswersQuiz($question->getQuiz());
0 ignored issues
show
Bug introduced by
The method getQuiz cannot be called on $question (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
154
155
        // If the question was a pronostic, I update entries with the results !
156
        if ($question->getPrediction()) {
0 ignored issues
show
Bug introduced by
The method getPrediction cannot be called on $question (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
157
            $this->updatePrediction($question);
158
        }
159
160
        $this->getEventManager()->trigger(
161
            __FUNCTION__,
162
            $this,
163
            array('question' => $question, 'data' => $data)
164
        );
165
        $this->getQuizQuestionMapper()->update($question);
166
        $this->getEventManager()->trigger(
167
            __FUNCTION__ .'.post',
168
            $this,
169
            array('question' => $question, 'data' => $data)
170
        );
171
172
        $this->getQuizMapper()->update($quiz);
173
174
        return $question;
175
    }
176
177
    public function findRepliesByGame($game)
178
    {
179
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
180
        $qb = $em->createQueryBuilder();
181
        $qb->select('r')
182
           ->from('PlaygroundGame\Entity\QuizReply', 'r')
183
           ->innerJoin('r.entry', 'e')
184
           ->where('e.game = :game')
185
           ->setParameter('game', $game);
186
        $query = $qb->getQuery();
187
188
        $replies = $query->getResult();
189
190
        return $replies;
191
    }
192
193
    public function updatePrediction($question)
194
    {
195
        set_time_limit(0);
196
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
197
198
        /* @var $dbal \Doctrine\DBAL\Connection */
199
        $dbal = $em->getConnection();
200
201
        $answers = $question->getAnswers();
202
        $victoryCondition = $question->getQuiz()->getVictoryConditions()/100;
203
        $maxCorrectAnswers = $question->getQuiz()->getMaxCorrectAnswers();
204
        $nbQuestionsWinner = $victoryCondition * $maxCorrectAnswers;
205
206
        // I update all the answers with points and correctness
207
        // Very fast (native query inside)
208
        if ($question->getType() == 2) {
209
            foreach ($answers as $answer) {
210
                $correct = ($answer->getCorrect() == 1)?$answer->getCorrect():0;
211
                $value  = trim(strip_tags($answer->getAnswer()));
212
                $points = ($correct)?$answer->getPoints():0;
213
                $sql    = "
214
                UPDATE game_quiz_reply_answer AS ra
215
                SET ra.points=IF(ra.answer=:answer, :points, 0),
216
                    ra.correct = IF(ra.answer=:answer, :isCorrect, 0)
217
                WHERE ra.question_id = :questionId
218
                ";
219
                $stmt = $dbal->prepare($sql);
220
                $stmt->execute(
221
                    array(
222
                        'answer'     => $value,
223
                        'points'     => $points,
224
                        'isCorrect'  => $correct,
225
                        'questionId' => $question->getId()
226
                    )
227
                );
228
            }
229
        } else {
230
            foreach ($answers as $answer) {
231
                $correct = ($answer->getCorrect() == 1)?$answer->getCorrect():0;
232
                $points = ($correct)?$answer->getPoints():0;
233
                $sql    = "
234
                UPDATE game_quiz_reply_answer AS ra
235
                SET ra.points=:points,
236
                    ra.correct = :isCorrect
237
                WHERE ra.question_id = :questionId
238
                    AND ra.answer_id = :answerId
239
                ";
240
241
                $stmt = $dbal->prepare($sql);
242
                $stmt->execute(
243
                    array(
244
                        'points'     => $points,
245
                        'isCorrect'  => $correct,
246
                        'questionId' => $question->getId(),
247
                        'answerId'   => $answer->getId()
248
                    )
249
                );
250
            }
251
        }
252
253
        // Entry update with points. WINNER is calculated also !
254
        $sql = "
255
        UPDATE game_entry as e
256
        INNER JOIN
257
        (
258
            SELECT e.id, SUM(ra.points) as points, SUM(ra.correct) as correct
259
            FROM game_entry as e
260
            INNER JOIN game_quiz_reply AS r ON r.entry_id = e.id
261
            INNER JOIN game_quiz_reply_answer AS ra ON ra.reply_id = r.id
262
            GROUP BY e.id
263
        ) i ON e.id = i.id
264
        SET e.points = i.points, e.winner = IF( i.correct >= :nbQuestionsWinner, 1, 0)
265
        WHERE e.game_id = :gameId
266
        ";
267
268
        $stmt = $dbal->prepare($sql);
269
        $stmt->execute(
270
            array(
271
                'gameId' => $question->getQuiz()->getId(),
272
                'nbQuestionsWinner' => $nbQuestionsWinner
273
            )
274
        );
275
276
        $this->getEventManager()->trigger(
277
            __FUNCTION__ .'.post',
278
            $this,
279
            array('question' => $question)
280
        );
281
    }
282
    /**
283
     * This function update the sort order of the questions in a Quiz
284
     * BEWARE : This function is time consuming (1s for 11 updates)
285
     * If you have many replies, switch to a  batch
286
     *
287
     * To improve performance, usage of DQL update
288
     * http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html
289
     *
290
     * @param  string $data
0 ignored issues
show
Bug introduced by
There is no parameter named $data. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
291
     * @return boolean
292
     */
293
    public function updatePredictionOLD($question)
294
    {
295
        set_time_limit(0);
296
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
297
298
        $replies = $this->findRepliesByGame($question->getQuiz());
299
300
        $answers = $question->getAnswers($question->getQuiz());
301
302
        $answersarray = array();
303
        foreach ($answers as $answer) {
304
            $answersarray[$answer->getId()] = $answer;
305
        }
306
307
        foreach ($replies as $reply) {
308
            $quizPoints         = 0;
309
            $quizCorrectAnswers = 0;
310
311
            foreach ($reply->getAnswers() as $quizReplyAnswer) {
312
                if (2 != $question->getType() && $quizReplyAnswer->getQuestionId() === $question->getId()) {
313
                    if ($answersarray[$quizReplyAnswer->getAnswerId()]) {
314
                        $updatedAnswer = $answersarray[$quizReplyAnswer->getAnswerId()];
315
                        $quizReplyAnswer->setPoints($updatedAnswer->getPoints());
316
                        $quizReplyAnswer->setCorrect($updatedAnswer->getCorrect());
317
                        $q = $em->createQuery('
318
							UPDATE PlaygroundGame\Entity\QuizReplyAnswer a
319
              SET a.points = :points, a.correct=:isCorrect
320
              WHERE a.id=:answerId
321
						');
322
                        $q->setParameter('points', $updatedAnswer->getPoints());
323
                        $q->setParameter('isCorrect', $updatedAnswer->getCorrect());
324
                        $q->setParameter('answerId', $quizReplyAnswer->getId());
325
                        $q->execute();
326
                    }
327
                } elseif ($quizReplyAnswer->getQuestionId() === $question->getId()) {
328
                    // question is a textarea
329
                    // search for a matching answer
330
                    foreach ($answers as $answer) {
331
                        if (trim(strip_tags($answer->getAnswer())) == trim(
332
                            strip_tags($quizReplyAnswer->getAnswer())
333
                        )
334
                        ) {
335
                            $quizReplyAnswer->setPoints($answer->getPoints());
336
                            $quizReplyAnswer->setCorrect($answer->getCorrect());
337
                            $q = $em->createQuery('
338
                              UPDATE PlaygroundGame\Entity\QuizReplyAnswer a
339
                              SET a.points = :points, a.correct=:isCorrect
340
                              WHERE a.id=:answerId
341
                            ');
342
                            $q->setParameter('points', $updatedAnswer->getPoints());
0 ignored issues
show
Bug introduced by
The variable $updatedAnswer does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
343
                            $q->setParameter('isCorrect', $updatedAnswer->getCorrect());
344
                            $q->setParameter('answerId', $quizReplyAnswer->getId());
345
                            $q->execute();
346
                        } else {
347
                            $quizReplyAnswer->setPoints(0);
348
                            $quizReplyAnswer->setCorrect(false);
349
                            $q = $em->createQuery('
350
                              UPDATE PlaygroundGame\Entity\QuizReplyAnswer a
351
                              SET a.points = 0, a.correct = false
352
                              WHERE a.id=:answerId
353
                            ');
354
                            $q->setParameter('answerId', $quizReplyAnswer->getId());
355
                            $q->execute();
356
                        }
357
                    }
358
                }
359
360
                // The reply has been updated with correct answers and points for this question.
361
                // I count the whole set of points for this reply and update the entry
362
                if ($quizReplyAnswer->getCorrect()) {
363
                    $quizPoints += $quizReplyAnswer->getPoints();
364
                    $quizCorrectAnswers += $quizReplyAnswer->getCorrect();
365
                }
366
            }
367
368
            $winner = $this->isWinner($question->getQuiz(), $quizCorrectAnswers);
369
            $reply->getEntry()->setWinner($winner);
370
            $reply->getEntry()->setPoints($quizPoints);
371
            // The entry should be inactive : entry->setActive(false);
372
            $this->getEntryMapper()->update($reply->getEntry());
373
        }
374
375
        $this->getEventManager()->trigger(
376
            __FUNCTION__ .'.post',
377
            $this,
378
            array('question' => $question)
379
        );
380
    }
381
382
    /**
383
     * This function update the sort order of the questions in a Quiz
384
     *
385
     * @param  string $data
386
     * @return boolean
387
     */
388
    public function sortQuestion($data)
389
    {
390
        $arr = explode(",", $data);
391
392
        foreach ($arr as $k => $v) {
393
            $question = $this->getQuizQuestionMapper()->findById($v);
394
            $question->setPosition($k);
395
            $this->getQuizQuestionMapper()->update($question);
396
        }
397
398
        return true;
399
    }
400
401
    /**
402
     * @return string
403
     */
404
    public function calculateMaxAnswersQuestion($question)
405
    {
406
        $question_max_points          = 0;
407
        $question_max_correct_answers = 0;
408
        // Closed question : Only one answer allowed
409
        if ($question->getType() == 0) {
410
            foreach ($question->getAnswers() as $answer) {
411
                if ($answer->getPoints() > $question_max_points) {
412
                    $question_max_points = $answer->getPoints();
413
                }
414
                if ($answer->getCorrect() && $question_max_correct_answers == 0) {
415
                    $question_max_correct_answers = 1;
416
                }
417
            }
418
            // if ($question_max_correct_answers == 0) {
419
            //     return false;
420
            // }
421
            // Closed question : Many answers allowed
422
        } elseif ($question->getType() == 1) {
423
            foreach ($question->getAnswers() as $answer) {
424
                $question_max_points += $answer->getPoints();
425
426
                if ($answer->getCorrect()) {
427
                    ++$question_max_correct_answers;
428
                }
429
            }
430
            // if ($question_max_correct_answers == 0) {
431
            //     return false;
432
            // }
433
            // Not a question : A textarea to fill in
434
        } elseif ($question->getType() == 2) {
435
            $question_max_correct_answers = 0;
436
        }
437
438
        $question->setMaxPoints($question_max_points);
439
        $question->setMaxCorrectAnswers($question_max_correct_answers);
440
441
        return $question;
442
    }
443
444
    public function calculateMaxAnswersQuiz($quiz)
445
    {
446
        $question_max_points          = 0;
447
        $question_max_correct_answers = 0;
448
        foreach ($quiz->getQuestions() as $question) {
449
            $question_max_points += $question->getMaxPoints();
450
            $question_max_correct_answers += $question->getMaxCorrectAnswers();
451
        }
452
        $quiz->setMaxPoints($question_max_points);
453
        $quiz->setMaxCorrectAnswers($question_max_correct_answers);
454
455
        return $quiz;
456
    }
457
458 View Code Duplication
    public function getNumberCorrectAnswersQuiz($user, $count = 'count')
0 ignored issues
show
Unused Code introduced by
The parameter $count 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...
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
459
    {
460
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
461
462
        $query = $em->createQuery(
463
            "SELECT COUNT(e.id) FROM PlaygroundGame\Entity\Entry e, PlaygroundGame\Entity\Game g
464
                WHERE e.user = :user
465
                AND g.classType = 'quiz'
466
                AND e.points > 0"
467
        );
468
        $query->setParameter('user', $user);
469
        $number = $query->getSingleScalarResult();
470
471
        return $number;
472
    }
473
474
    public function createQuizReply($data, $game, $user)
475
    {
476
        // Si mon nb de participation est < au nb autorisé, j'ajoute une entry + reponses au quiz et points
477
        $quizReplyMapper = $this->getQuizReplyMapper();
478
        $entryMapper     = $this->getEntryMapper();
479
        $entry           = $this->findLastActiveEntry($game, $user);
480
481
        if (!$entry) {
482
            return false;
483
        }
484
485
        $quizPoints         = 0;
486
        $quizCorrectAnswers = 0;
487
        $maxCorrectAnswers  = $game->getMaxCorrectAnswers();
488
        $totalQuestions     = 0;
489
490
        $quizReply = $this->getQuizReplyMapper()->getLastGameReply($entry);
491
        if (!$quizReply) {
492
            $quizReply = new QuizReply();
493
        } else {
494
            $quizReplyAnswered = [];
495
            foreach ($quizReply->getAnswers() as $answer) {
496
                $quizReplyAnswered[$answer->getQuestionId()] = $answer;
497
            }
498
        }
499
500
        foreach ($data as $group) {
501
            if(count($group) > 0) {
502
                foreach ($group as $q => $a) {
503
                    if (strlen($q) > 5 && strpos($q, '-data', strlen($q)-5) !== false) {
504
                        continue;// answer data is processed below
505
                    }
506
                    $question = $this->getQuizQuestionMapper()->findById((int) str_replace('q', '', $q));
507
                    ++$totalQuestions;
508
                    if (is_array($a)) {
509
                        foreach ($a as $k => $answer_id) {
510
                            $answer = $this->getQuizAnswerMapper()->findById($answer_id);
511 View Code Duplication
                            if ($answer) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
512
                                if (isset($quizReplyAnswered[$question->getId()])) {
513
                                    $this->getQuizReplyAnswerMapper()->remove($quizReplyAnswered[$question->getId()]);
514
                                }
515
516
                                $quizReplyAnswer = new QuizReplyAnswer();
517
                                $quizReplyAnswer->setAnswer($answer->getAnswer());
518
                                $quizReplyAnswer->setAnswerId($answer_id);
519
                                $quizReplyAnswer->setQuestion($question->getQuestion());
520
                                $quizReplyAnswer->setQuestionId($question->getId());
521
                                $quizReplyAnswer->setPoints($answer->getPoints());
522
                                $quizReplyAnswer->setCorrect($answer->getCorrect());
523
524
                                $quizReply->addAnswer($quizReplyAnswer);
525
526
                                $quizPoints += $answer->getPoints();
527
                                $quizCorrectAnswers += $answer->getCorrect();
528
529
                                if (isset($group[$q.'-'.$answer_id.'-data'])) {
530
                                    $quizReplyAnswer->setAnswerData($group[$q.'-'.$answer_id.'-data']);
531
                                }
532
                            }
533
                        }
534
                    } elseif ($question->getType() == 0 || $question->getType() == 1) {
535
                        ++$totalQuestions;
536
                        $answer = $this->getQuizAnswerMapper()->findById($a);
537 View Code Duplication
                        if ($answer) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
538
                            if (isset($quizReplyAnswered[$question->getId()])) {
539
                                $this->getQuizReplyAnswerMapper()->remove($quizReplyAnswered[$question->getId()]);
540
                            }
541
                            $quizReplyAnswer = new QuizReplyAnswer();
542
                            $quizReplyAnswer->setAnswer($answer->getAnswer());
543
                            $quizReplyAnswer->setAnswerId($a);
544
                            $quizReplyAnswer->setQuestion($question->getQuestion());
545
                            $quizReplyAnswer->setQuestionId($question->getId());
546
                            $quizReplyAnswer->setPoints($answer->getPoints());
547
                            $quizReplyAnswer->setCorrect($answer->getCorrect());
548
549
                            $quizReply->addAnswer($quizReplyAnswer);
550
551
                            $quizPoints += $answer->getPoints();
552
                            $quizCorrectAnswers += $answer->getCorrect();
553
                            if (isset($group[$q.'-'.$a.'-data'])) {
554
                                $quizReplyAnswer->setAnswerData($group[$q.'-'.$a.'-data']);
555
                            }
556
                        }
557
                    } elseif ($question->getType() == 2) {
558
                        ++$totalQuestions;
559
                        if (isset($quizReplyAnswered[$question->getId()])) {
560
                            $this->getQuizReplyAnswerMapper()->remove($quizReplyAnswered[$question->getId()]);
561
                        }
562
                        $quizReplyAnswer = new QuizReplyAnswer();
563
                        $quizReplyAnswer->setAnswer($a);
564
                        $quizReplyAnswer->setAnswerId(0);
0 ignored issues
show
Documentation introduced by
0 is of type integer, but the function expects a object<PlaygroundGame\Entity\unknown_type>.

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...
565
                        $quizReplyAnswer->setQuestion($question->getQuestion());
566
                        $quizReplyAnswer->setQuestionId($question->getId());
567
                        $quizReplyAnswer->setPoints(0);
0 ignored issues
show
Documentation introduced by
0 is of type integer, but the function expects a object<PlaygroundGame\Entity\field_type>.

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...
568
                        $quizReplyAnswer->setCorrect(0);
0 ignored issues
show
Documentation introduced by
0 is of type integer, but the function expects a object<PlaygroundGame\Entity\unknown_type>.

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...
569
570
                        $quizReply->addAnswer($quizReplyAnswer);
571
572
                        $quizPoints += 0;
573
                        $quizCorrectAnswers += 0;
574
                        $qAnswers = $question->getAnswers();
575
                        foreach ($qAnswers as $qAnswer) {
576
                            if (trim(strip_tags($a)) == trim(strip_tags($qAnswer->getAnswer()))) {
577
                                $quizReplyAnswer->setPoints($qAnswer->getPoints());
578
                                $quizPoints += $qAnswer->getPoints();
579
                                $quizReplyAnswer->setCorrect($qAnswer->getCorrect());
580
                                $quizCorrectAnswers += $qAnswer->getCorrect();
581
                                break;
582
                            }
583
                        }
584
585
                        if (isset($group[$q.'-'.$a.'-data'])) {
586
                            $quizReplyAnswer->setAnswerData($group[$q.'-'.$a.'-data']);
587
                        }
588
                    }
589
                }
590
            }
591
        }
592
        // TODO : In the case of usage of stopdate, the calculation of quizCorrectAnswers
593
        // and quizPoints is incorrect
594
        $winner = $this->isWinner($game, $quizCorrectAnswers);
595
596
        $entry->setWinner($winner);
0 ignored issues
show
Bug introduced by
The method setWinner cannot be called on $entry (of type boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
597
        // Every winning participation is eligible to draw
598
        // TODO : Make this modifiable in the admin (choose who can participate to draw)
599
        $entry->setDrawable($winner);
0 ignored issues
show
Bug introduced by
The method setDrawable cannot be called on $entry (of type boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
600
        $entry->setPoints($quizPoints);
0 ignored issues
show
Bug introduced by
The method setPoints cannot be called on $entry (of type boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
601
        $entry->setActive(false);
0 ignored issues
show
Bug introduced by
The method setActive cannot be called on $entry (of type boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
602
        $entry = $entryMapper->update($entry);
603
604
        $quizReply->setEntry($entry);
605
        $quizReply->setTotalCorrectAnswers($quizCorrectAnswers);
606
        $quizReply->setMaxCorrectAnswers($maxCorrectAnswers);
607
        $quizReply->setTotalQuestions($totalQuestions);
608
609
        $quizReplyMapper->insert($quizReply);
610
611
        $this->getEventManager()->trigger(
612
            __FUNCTION__ .'.post',
613
            $this,
614
            array('user' => $user, 'entry' => $entry, 'reply' => $quizReply, 'game' => $game)
615
        );
616
617
        return $entry;
618
    }
619
620
    public function isWinner($game, $quizCorrectAnswers = 0)
621
    {
622
        // Pour déterminer le gagnant, je regarde le nombre max de reponses correctes possibles
623
        // dans le jeu, puis je calcule le ratio de bonnes réponses et le compare aux conditions
624
        // de victoire
625
        $winner            = false;
626
        $maxCorrectAnswers = $game->getMaxCorrectAnswers();
627
        if ($maxCorrectAnswers > 0) {
628
            $ratioCorrectAnswers = ($quizCorrectAnswers/$maxCorrectAnswers)*100;
629
        } elseif ($game->getVictoryConditions() > 0) {
630
            // In the case I have a pronostic game for example
631
            $ratioCorrectAnswers = 0;
632
        } else {
633
            // In the case I want everybody to win
634
            $ratioCorrectAnswers = 100;
635
        }
636
637
        if ($game->getVictoryConditions() >= 0) {
638
            if ($ratioCorrectAnswers >= $game->getVictoryConditions()) {
639
                $winner = true;
640
            }
641
        }
642
        return $winner;
643
    }
644
645
    public function getEntriesHeader($game)
646
    {
647
        $header                        = parent::getEntriesHeader($game);
648
        $header['totalCorrectAnswers'] = 1;
649
650
        return $header;
651
    }
652
653 View Code Duplication
    public function getEntriesQuery($game)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
654
    {
655
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
656
657
        $qb = $em->createQueryBuilder();
658
        $qb->select('
659
            r.id,
660
            u.username,
661
            u.title,
662
            u.firstname,
663
            u.lastname,
664
            u.email,
665
            u.optin,
666
            u.optinPartner,
667
            u.address,
668
            u.address2,
669
            u.postalCode,
670
            u.city,
671
            u.telephone,
672
            u.mobile,
673
            u.created_at,
674
            u.dob,
675
            e.winner,
676
            e.socialShares,
677
            e.playerData,
678
            e.updated_at,
679
            r.totalCorrectAnswers
680
            ')
681
        ->from('PlaygroundGame\Entity\QuizReply', 'r')
682
        ->innerJoin('r.entry', 'e')
683
        ->leftJoin('e.user', 'u')
684
        ->where($qb->expr()->eq('e.game', ':game'));
685
686
        $qb->setParameter('game', $game);
687
688
        return $qb->getQuery();
689
    }
690
691
    public function getGameEntity()
692
    {
693
        return new \PlaygroundGame\Entity\Quiz;
694
    }
695
696
    /**
697
     * getQuizMapper
698
     *
699
     * @return QuizMapperInterface
700
     */
701
    public function getQuizMapper()
702
    {
703
        if (null === $this->quizMapper) {
704
            $this->quizMapper = $this->serviceLocator->get('playgroundgame_quiz_mapper');
705
        }
706
707
        return $this->quizMapper;
708
    }
709
710
    /**
711
     * setQuizMapper
712
     *
713
     * @param  QuizMapperInterface $quizMapper
714
     * @return Game
715
     */
716
    public function setQuizMapper(GameMapperInterface $quizMapper)
717
    {
718
        $this->quizMapper = $quizMapper;
0 ignored issues
show
Documentation Bug introduced by
It seems like $quizMapper of type object<PlaygroundGame\Mapper\GameInterface> is incompatible with the declared type object<PlaygroundGame\Se...ce\QuizMapperInterface> of property $quizMapper.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
719
720
        return $this;
721
    }
722
723
    /**
724
     * getQuizQuestionMapper
725
     *
726
     * @return QuizQuestionMapperInterface
727
     */
728
    public function getQuizQuestionMapper()
729
    {
730
        if (null === $this->quizQuestionMapper) {
731
            $this->quizQuestionMapper = $this->serviceLocator->get('playgroundgame_quizquestion_mapper');
732
        }
733
734
        return $this->quizQuestionMapper;
735
    }
736
737
    /**
738
     * setQuizQuestionMapper
739
     *
740
     * @param  QuizQuestionMapperInterface $quizquestionMapper
741
     * @return Quiz
742
     */
743
    public function setQuizQuestionMapper($quizquestionMapper)
744
    {
745
        $this->quizQuestionMapper = $quizquestionMapper;
746
747
        return $this;
748
    }
749
750
    /**
751
     * setQuizAnswerMapper
752
     *
753
     * @param  QuizAnswerMapperInterface $quizAnswerMapper
754
     * @return Quiz
755
     */
756
    public function setQuizAnswerMapper($quizAnswerMapper)
757
    {
758
        $this->quizAnswerMapper = $quizAnswerMapper;
759
760
        return $this;
761
    }
762
763
    /**
764
     * getQuizAnswerMapper
765
     *
766
     * @return QuizAnswerMapperInterface
767
     */
768
    public function getQuizAnswerMapper()
769
    {
770
        if (null === $this->quizAnswerMapper) {
771
            $this->quizAnswerMapper = $this->serviceLocator->get('playgroundgame_quizanswer_mapper');
772
        }
773
774
        return $this->quizAnswerMapper;
775
    }
776
777
    /**
778
     * getQuizReplyMapper
779
     *
780
     * @return QuizReplyMapperInterface
781
     */
782
    public function getQuizReplyMapper()
783
    {
784
        if (null === $this->quizReplyMapper) {
785
            $this->quizReplyMapper = $this->serviceLocator->get('playgroundgame_quizreply_mapper');
786
        }
787
788
        return $this->quizReplyMapper;
789
    }
790
791
    /**
792
     * setQuizReplyMapper
793
     *
794
     * @param  QuizReplyMapperInterface $quizreplyMapper
795
     * @return Quiz
796
     */
797
    public function setQuizReplyMapper($quizreplyMapper)
798
    {
799
        $this->quizReplyMapper = $quizreplyMapper;
800
801
        return $this;
802
    }
803
804
    /**
805
     * getQuizReplyAnswerMapper
806
     *
807
     * @return QuizReplyAnswerMapper
808
     */
809
    public function getQuizReplyAnswerMapper()
810
    {
811
        if (null === $this->quizReplyAnswerMapper) {
812
            $this->quizReplyAnswerMapper = $this->serviceLocator->get('playgroundgame_quizreplyanswer_mapper');
813
        }
814
815
        return $this->quizReplyAnswerMapper;
816
    }
817
818
    /**
819
     * setQuizReplyAnswerMapper
820
     *
821
     * @param  QuizReplyAnswerMapper $quizReplyAnswerMapper
822
     * @return Quiz
823
     */
824
    public function setQuizReplyAnswerMapper($quizReplyAnswerMapper)
825
    {
826
        $this->quizReplyAnswerMapper = $quizReplyAnswerMapper;
827
828
        return $this;
829
    }
830
}
831