Completed
Push — master ( 467cb1...f6d530 )
by greg
57:09 queued 47:00
created

Quiz::getNumberCorrectAnswersQuiz()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 15

Duplication

Lines 15
Ratio 100 %

Importance

Changes 0
Metric Value
dl 15
loc 15
rs 9.7666
c 0
b 0
f 0
cc 1
nc 1
nop 2
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
    public function getAnswersDistribution($game) {
383
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
384
385
        /* @var $dbal \Doctrine\DBAL\Connection */
386
        $dbal = $em->getConnection();
387
        $sql    = "
388
        select q.id as question_id, q.question, qa.id as answer_id, qa.answer, count(a.id) as count from game as g
389
        inner join game_quiz_question as q on g.id = q.quiz_id
390
        inner join game_quiz_answer as qa on q.id = qa.question_id
391
        left join game_quiz_reply_answer as a on a.answer_id = qa.id
392
        where g.id = :quizId
393
        group by q.id, qa.id
394
        ";
395
396
        $stmt = $dbal->prepare($sql);
397
        $stmt->execute(
398
            array(
399
                'quizId' => $game->getId()
400
            )
401
        );
402
403
        $rows = $stmt->fetchAll();
404
        $result = [];
405
        foreach($rows as $row) {
406
            $result[$row['question_id']][] = $row;
407
        }
408
409
        $this->getEventManager()->trigger(
410
            __FUNCTION__ .'.post',
411
            $this,
412
            array('game' => $game)
413
        );
414
415
        return $result;
416
    }
417
418
    /**
419
     * This function update the sort order of the questions in a Quiz
420
     *
421
     * @param  string $data
422
     * @return boolean
423
     */
424
    public function sortQuestion($data)
425
    {
426
        $arr = explode(",", $data);
427
428
        foreach ($arr as $k => $v) {
429
            $question = $this->getQuizQuestionMapper()->findById($v);
430
            $question->setPosition($k);
431
            $this->getQuizQuestionMapper()->update($question);
432
        }
433
434
        return true;
435
    }
436
437
    /**
438
     * @return string
439
     */
440
    public function calculateMaxAnswersQuestion($question)
441
    {
442
        $question_max_points          = 0;
443
        $question_max_correct_answers = 0;
444
        // Closed question : Only one answer allowed
445
        if ($question->getType() == 0) {
446
            foreach ($question->getAnswers() as $answer) {
447
                if ($answer->getPoints() > $question_max_points) {
448
                    $question_max_points = $answer->getPoints();
449
                }
450
                if ($answer->getCorrect() && $question_max_correct_answers == 0) {
451
                    $question_max_correct_answers = 1;
452
                }
453
            }
454
            // if ($question_max_correct_answers == 0) {
455
            //     return false;
456
            // }
457
            // Closed question : Many answers allowed
458
        } elseif ($question->getType() == 1) {
459
            foreach ($question->getAnswers() as $answer) {
460
                $question_max_points += $answer->getPoints();
461
462
                if ($answer->getCorrect()) {
463
                    ++$question_max_correct_answers;
464
                }
465
            }
466
            // if ($question_max_correct_answers == 0) {
467
            //     return false;
468
            // }
469
            // Not a question : A textarea to fill in
470
        } elseif ($question->getType() == 2) {
471
            $question_max_correct_answers = 0;
472
        }
473
474
        $question->setMaxPoints($question_max_points);
475
        $question->setMaxCorrectAnswers($question_max_correct_answers);
476
477
        return $question;
478
    }
479
480
    public function calculateMaxAnswersQuiz($quiz)
481
    {
482
        $question_max_points          = 0;
483
        $question_max_correct_answers = 0;
484
        foreach ($quiz->getQuestions() as $question) {
485
            $question_max_points += $question->getMaxPoints();
486
            $question_max_correct_answers += $question->getMaxCorrectAnswers();
487
        }
488
        $quiz->setMaxPoints($question_max_points);
489
        $quiz->setMaxCorrectAnswers($question_max_correct_answers);
490
491
        return $quiz;
492
    }
493
494 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...
495
    {
496
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
497
498
        $query = $em->createQuery(
499
            "SELECT COUNT(e.id) FROM PlaygroundGame\Entity\Entry e, PlaygroundGame\Entity\Game g
500
                WHERE e.user = :user
501
                AND g.classType = 'quiz'
502
                AND e.points > 0"
503
        );
504
        $query->setParameter('user', $user);
505
        $number = $query->getSingleScalarResult();
506
507
        return $number;
508
    }
509
510
    public function createQuizReply($data, $game, $user)
511
    {
512
        // Si mon nb de participation est < au nb autorisé, j'ajoute une entry + reponses au quiz et points
513
        $quizReplyMapper = $this->getQuizReplyMapper();
514
        $entryMapper     = $this->getEntryMapper();
515
        $entry           = $this->findLastActiveEntry($game, $user);
516
517
        if (!$entry) {
518
            return false;
519
        }
520
521
        $quizPoints         = 0;
522
        $quizCorrectAnswers = 0;
523
        $maxCorrectAnswers  = $game->getMaxCorrectAnswers();
524
        $totalQuestions     = 0;
525
526
        $quizReply = $this->getQuizReplyMapper()->getLastGameReply($entry);
527
        if (!$quizReply) {
528
            $quizReply = new QuizReply();
529
        } else {
530
            $quizReplyAnswered = [];
531
            foreach ($quizReply->getAnswers() as $answer) {
532
                $quizReplyAnswered[$answer->getQuestionId()] = $answer;
533
            }
534
        }
535
536
        foreach ($data as $group) {
537
            if(count($group) > 0) {
538
                foreach ($group as $q => $a) {
539
                    if (strlen($q) > 5 && strpos($q, '-data', strlen($q)-5) !== false) {
540
                        continue;// answer data is processed below
541
                    }
542
                    $question = $this->getQuizQuestionMapper()->findById((int) str_replace('q', '', $q));
543
                    ++$totalQuestions;
544
                    if (is_array($a)) {
545
                        foreach ($a as $k => $answer_id) {
546
                            $answer = $this->getQuizAnswerMapper()->findById($answer_id);
547 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...
548
                                if (isset($quizReplyAnswered[$question->getId()])) {
549
                                    $this->getQuizReplyAnswerMapper()->remove($quizReplyAnswered[$question->getId()]);
550
                                }
551
552
                                $quizReplyAnswer = new QuizReplyAnswer();
553
                                $quizReplyAnswer->setAnswer($answer->getAnswer());
554
                                $quizReplyAnswer->setAnswerId($answer_id);
555
                                $quizReplyAnswer->setQuestion($question->getQuestion());
556
                                $quizReplyAnswer->setQuestionId($question->getId());
557
                                $quizReplyAnswer->setPoints($answer->getPoints());
558
                                $quizReplyAnswer->setCorrect($answer->getCorrect());
559
560
                                $quizReply->addAnswer($quizReplyAnswer);
561
562
                                $quizPoints += $answer->getPoints();
563
                                $quizCorrectAnswers += $answer->getCorrect();
564
565
                                if (isset($group[$q.'-'.$answer_id.'-data'])) {
566
                                    $quizReplyAnswer->setAnswerData($group[$q.'-'.$answer_id.'-data']);
567
                                }
568
                            }
569
                        }
570
                    } elseif ($question->getType() == 0 || $question->getType() == 1) {
571
                        ++$totalQuestions;
572
                        $answer = $this->getQuizAnswerMapper()->findById($a);
573 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...
574
                            if (isset($quizReplyAnswered[$question->getId()])) {
575
                                $this->getQuizReplyAnswerMapper()->remove($quizReplyAnswered[$question->getId()]);
576
                            }
577
                            $quizReplyAnswer = new QuizReplyAnswer();
578
                            $quizReplyAnswer->setAnswer($answer->getAnswer());
579
                            $quizReplyAnswer->setAnswerId($a);
580
                            $quizReplyAnswer->setQuestion($question->getQuestion());
581
                            $quizReplyAnswer->setQuestionId($question->getId());
582
                            $quizReplyAnswer->setPoints($answer->getPoints());
583
                            $quizReplyAnswer->setCorrect($answer->getCorrect());
584
585
                            $quizReply->addAnswer($quizReplyAnswer);
586
587
                            $quizPoints += $answer->getPoints();
588
                            $quizCorrectAnswers += $answer->getCorrect();
589
                            if (isset($group[$q.'-'.$a.'-data'])) {
590
                                $quizReplyAnswer->setAnswerData($group[$q.'-'.$a.'-data']);
591
                            }
592
                        }
593
                    } elseif ($question->getType() == 2) {
594
                        ++$totalQuestions;
595
                        if (isset($quizReplyAnswered[$question->getId()])) {
596
                            $this->getQuizReplyAnswerMapper()->remove($quizReplyAnswered[$question->getId()]);
597
                        }
598
                        $quizReplyAnswer = new QuizReplyAnswer();
599
                        $quizReplyAnswer->setAnswer($a);
600
                        $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...
601
                        $quizReplyAnswer->setQuestion($question->getQuestion());
602
                        $quizReplyAnswer->setQuestionId($question->getId());
603
                        $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...
604
                        $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...
605
606
                        $quizReply->addAnswer($quizReplyAnswer);
607
608
                        $quizPoints += 0;
609
                        $quizCorrectAnswers += 0;
610
                        $qAnswers = $question->getAnswers();
611
                        foreach ($qAnswers as $qAnswer) {
612
                            if (trim(strip_tags($a)) == trim(strip_tags($qAnswer->getAnswer()))) {
613
                                $quizReplyAnswer->setPoints($qAnswer->getPoints());
614
                                $quizPoints += $qAnswer->getPoints();
615
                                $quizReplyAnswer->setCorrect($qAnswer->getCorrect());
616
                                $quizCorrectAnswers += $qAnswer->getCorrect();
617
                                break;
618
                            }
619
                        }
620
621
                        if (isset($group[$q.'-'.$a.'-data'])) {
622
                            $quizReplyAnswer->setAnswerData($group[$q.'-'.$a.'-data']);
623
                        }
624
                    }
625
                }
626
            }
627
        }
628
        // TODO : In the case of usage of stopdate, the calculation of quizCorrectAnswers
629
        // and quizPoints is incorrect
630
        $winner = $this->isWinner($game, $quizCorrectAnswers);
631
632
        $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...
633
        // Every winning participation is eligible to draw
634
        // TODO : Make this modifiable in the admin (choose who can participate to draw)
635
        $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...
636
        $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...
637
        $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...
638
        $entry = $entryMapper->update($entry);
639
640
        $quizReply->setEntry($entry);
641
        $quizReply->setTotalCorrectAnswers($quizCorrectAnswers);
642
        $quizReply->setMaxCorrectAnswers($maxCorrectAnswers);
643
        $quizReply->setTotalQuestions($totalQuestions);
644
645
        $quizReplyMapper->insert($quizReply);
646
647
        $this->getEventManager()->trigger(
648
            __FUNCTION__ .'.post',
649
            $this,
650
            array('user' => $user, 'entry' => $entry, 'reply' => $quizReply, 'game' => $game)
651
        );
652
653
        return $entry;
654
    }
655
656
    public function isWinner($game, $quizCorrectAnswers = 0)
657
    {
658
        // Pour déterminer le gagnant, je regarde le nombre max de reponses correctes possibles
659
        // dans le jeu, puis je calcule le ratio de bonnes réponses et le compare aux conditions
660
        // de victoire
661
        $winner            = false;
662
        $maxCorrectAnswers = $game->getMaxCorrectAnswers();
663
        if ($maxCorrectAnswers > 0) {
664
            $ratioCorrectAnswers = ($quizCorrectAnswers/$maxCorrectAnswers)*100;
665
        } elseif ($game->getVictoryConditions() > 0) {
666
            // In the case I have a pronostic game for example
667
            $ratioCorrectAnswers = 0;
668
        } else {
669
            // In the case I want everybody to win
670
            $ratioCorrectAnswers = 100;
671
        }
672
673
        if ($game->getVictoryConditions() >= 0) {
674
            if ($ratioCorrectAnswers >= $game->getVictoryConditions()) {
675
                $winner = true;
676
            }
677
        }
678
        return $winner;
679
    }
680
681
    public function getEntriesHeader($game)
682
    {
683
        $header                        = parent::getEntriesHeader($game);
684
        $header['totalCorrectAnswers'] = 1;
685
686
        return $header;
687
    }
688
689 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...
690
    {
691
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
692
693
        $qb = $em->createQueryBuilder();
694
        $qb->select('
695
            r.id,
696
            u.username,
697
            u.title,
698
            u.firstname,
699
            u.lastname,
700
            u.email,
701
            u.optin,
702
            u.optinPartner,
703
            u.address,
704
            u.address2,
705
            u.postalCode,
706
            u.city,
707
            u.telephone,
708
            u.mobile,
709
            u.created_at,
710
            u.dob,
711
            e.winner,
712
            e.socialShares,
713
            e.playerData,
714
            e.updated_at,
715
            r.totalCorrectAnswers
716
            ')
717
        ->from('PlaygroundGame\Entity\QuizReply', 'r')
718
        ->innerJoin('r.entry', 'e')
719
        ->leftJoin('e.user', 'u')
720
        ->where($qb->expr()->eq('e.game', ':game'));
721
722
        $qb->setParameter('game', $game);
723
724
        return $qb->getQuery();
725
    }
726
727
    public function getGameEntity()
728
    {
729
        return new \PlaygroundGame\Entity\Quiz;
730
    }
731
732
    /**
733
     * getQuizMapper
734
     *
735
     * @return QuizMapperInterface
736
     */
737
    public function getQuizMapper()
738
    {
739
        if (null === $this->quizMapper) {
740
            $this->quizMapper = $this->serviceLocator->get('playgroundgame_quiz_mapper');
741
        }
742
743
        return $this->quizMapper;
744
    }
745
746
    /**
747
     * setQuizMapper
748
     *
749
     * @param  QuizMapperInterface $quizMapper
750
     * @return Game
751
     */
752
    public function setQuizMapper(GameMapperInterface $quizMapper)
753
    {
754
        $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...
755
756
        return $this;
757
    }
758
759
    /**
760
     * getQuizQuestionMapper
761
     *
762
     * @return QuizQuestionMapperInterface
763
     */
764
    public function getQuizQuestionMapper()
765
    {
766
        if (null === $this->quizQuestionMapper) {
767
            $this->quizQuestionMapper = $this->serviceLocator->get('playgroundgame_quizquestion_mapper');
768
        }
769
770
        return $this->quizQuestionMapper;
771
    }
772
773
    /**
774
     * setQuizQuestionMapper
775
     *
776
     * @param  QuizQuestionMapperInterface $quizquestionMapper
777
     * @return Quiz
778
     */
779
    public function setQuizQuestionMapper($quizquestionMapper)
780
    {
781
        $this->quizQuestionMapper = $quizquestionMapper;
782
783
        return $this;
784
    }
785
786
    /**
787
     * setQuizAnswerMapper
788
     *
789
     * @param  QuizAnswerMapperInterface $quizAnswerMapper
790
     * @return Quiz
791
     */
792
    public function setQuizAnswerMapper($quizAnswerMapper)
793
    {
794
        $this->quizAnswerMapper = $quizAnswerMapper;
795
796
        return $this;
797
    }
798
799
    /**
800
     * getQuizAnswerMapper
801
     *
802
     * @return QuizAnswerMapperInterface
803
     */
804
    public function getQuizAnswerMapper()
805
    {
806
        if (null === $this->quizAnswerMapper) {
807
            $this->quizAnswerMapper = $this->serviceLocator->get('playgroundgame_quizanswer_mapper');
808
        }
809
810
        return $this->quizAnswerMapper;
811
    }
812
813
    /**
814
     * getQuizReplyMapper
815
     *
816
     * @return QuizReplyMapperInterface
817
     */
818
    public function getQuizReplyMapper()
819
    {
820
        if (null === $this->quizReplyMapper) {
821
            $this->quizReplyMapper = $this->serviceLocator->get('playgroundgame_quizreply_mapper');
822
        }
823
824
        return $this->quizReplyMapper;
825
    }
826
827
    /**
828
     * setQuizReplyMapper
829
     *
830
     * @param  QuizReplyMapperInterface $quizreplyMapper
831
     * @return Quiz
832
     */
833
    public function setQuizReplyMapper($quizreplyMapper)
834
    {
835
        $this->quizReplyMapper = $quizreplyMapper;
836
837
        return $this;
838
    }
839
840
    /**
841
     * getQuizReplyAnswerMapper
842
     *
843
     * @return QuizReplyAnswerMapper
844
     */
845
    public function getQuizReplyAnswerMapper()
846
    {
847
        if (null === $this->quizReplyAnswerMapper) {
848
            $this->quizReplyAnswerMapper = $this->serviceLocator->get('playgroundgame_quizreplyanswer_mapper');
849
        }
850
851
        return $this->quizReplyAnswerMapper;
852
    }
853
854
    /**
855
     * setQuizReplyAnswerMapper
856
     *
857
     * @param  QuizReplyAnswerMapper $quizReplyAnswerMapper
858
     * @return Quiz
859
     */
860
    public function setQuizReplyAnswerMapper($quizReplyAnswerMapper)
861
    {
862
        $this->quizReplyAnswerMapper = $quizReplyAnswerMapper;
863
864
        return $this;
865
    }
866
}
867