Completed
Push — master ( 183459...341557 )
by greg
07:15 queued 04:28
created

Quiz   F

Complexity

Total Complexity 94

Size/Duplication

Total Lines 819
Duplicated Lines 13.92 %

Coupling/Cohesion

Components 1
Dependencies 9

Importance

Changes 0
Metric Value
wmc 94
lcom 1
cbo 9
dl 114
loc 819
rs 1.781
c 0
b 0
f 0

24 Methods

Rating   Name   Duplication   Size   Complexity  
A createQuestion() 10 50 3
C updateQuestion() 10 85 10
A findRepliesByGame() 0 15 1
B updatePrediction() 0 83 8
C updatePredictionOLD() 0 88 11
A sortQuestion() 0 12 2
B calculateMaxAnswersQuestion() 0 39 10
A calculateMaxAnswersQuiz() 0 13 2
A getNumberCorrectAnswersQuiz() 15 15 1
F createQuizReply() 42 142 23
A isWinner() 0 24 5
A getEntriesHeader() 0 7 1
A getEntriesQuery() 37 37 1
A getGameEntity() 0 4 1
A getQuizMapper() 0 8 2
A setQuizMapper() 0 6 1
A getQuizQuestionMapper() 0 8 2
A setQuizQuestionMapper() 0 6 1
A setQuizAnswerMapper() 0 6 1
A getQuizAnswerMapper() 0 8 2
A getQuizReplyMapper() 0 8 2
A setQuizReplyMapper() 0 6 1
A getQuizReplyAnswerMapper() 0 8 2
A setQuizReplyAnswerMapper() 0 6 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Quiz often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Quiz, and based on these observations, apply Extract Interface, too.

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
        // If question is a prediction, no need to calculate max good answers
62
        // if (!$question->getPrediction()) {
63
        //     // Max points and correct answers calculation for the question
64
        //     if (!$question = $this->calculateMaxAnswersQuestion($question)) {
65
        //
66
        //         return false;
67
        //     }
68
        // }
69
70
        // Max points and correct answers recalculation for the quiz
71
        $quiz = $this->calculateMaxAnswersQuiz($question->getQuiz());
72
73
        $this->getEventManager()->trigger(__FUNCTION__, $this, array('game' => $question, 'data' => $data));
74
        $this->getQuizQuestionMapper()->insert($question);
75
        $this->getEventManager()->trigger(__FUNCTION__ .'.post', $this, array('game' => $question, 'data' => $data));
76
77 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...
78
            ErrorHandler::start();
79
            $data['upload_image']['name'] = $this->fileNewname(
80
                $path,
81
                $question->getId()."-".$data['upload_image']['name']
82
            );
83
            move_uploaded_file($data['upload_image']['tmp_name'], $path.$data['upload_image']['name']);
84
            $question->setImage($media_url.$data['upload_image']['name']);
85
            ErrorHandler::stop(true);
86
        }
87
88
        $this->getQuizQuestionMapper()->update($question);
89
        $this->getQuizMapper()->update($quiz);
90
91
        return $question;
92
    }
93
94
    /**
95
     * @param  array $data
96
     * @return \PlaygroundGame\Entity\Game
97
     */
98
    public function updateQuestion(array $data, $question)
99
    {
100
        $path      = $this->getOptions()->getMediaPath().DIRECTORY_SEPARATOR;
101
        $media_url = $this->getOptions()->getMediaUrl().'/';
102
103
        $form = $this->serviceLocator->get('playgroundgame_quizquestion_form');
104
        $form->bind($question);
105
        $form->setData($data);
106
107
        if (!$form->isValid()) {
108
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by PlaygroundGame\Service\Quiz::updateQuestion of type PlaygroundGame\Entity\Game.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
109
        }
110
111
        // If question is a prediction, no need to calculate max good answers
112
        // if (!$question->getPrediction()) {
113
        //     // Max points and correct answers calculation for the question
114
        //     if (!$question = $this->calculateMaxAnswersQuestion($question)) {
115
        //         return false;
116
        //     }
117
        // }
118
119 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...
120
            ErrorHandler::start();
121
            $data['upload_image']['name'] = $this->fileNewname(
122
                $path,
123
                $question->getId()."-".$data['upload_image']['name']
124
            );
125
            move_uploaded_file($data['upload_image']['tmp_name'], $path.$data['upload_image']['name']);
126
            $question->setImage($media_url.$data['upload_image']['name']);
127
            ErrorHandler::stop(true);
128
        }
129
130
        if (isset($data['delete_image']) && !empty($data['delete_image']) && empty($data['upload_image']['tmp_name'])) {
131
            ErrorHandler::start();
132
            $image = $question->getImage();
133
            $image = str_replace($media_url, '', $image);
134
            if (file_exists($path.$image)) {
135
                unlink($path.$image);
136
            }
137
            $question->setImage(null);
138
            ErrorHandler::stop(true);
139
        }
140
141
        $i = 0;
142
        foreach ($question->getAnswers() as $answer) {
143
            if (!empty($data['answers'][$i]['upload_image']['tmp_name'])) {
144
                ErrorHandler::start();
145
                $data['answers'][$i]['upload_image']['name'] = $this->fileNewname(
146
                    $path,
147
                    $question->getId()."-".$data['answers'][$i]['upload_image']['name']
148
                );
149
                move_uploaded_file(
150
                    $data['answers'][$i]['upload_image']['tmp_name'],
151
                    $path.$data['answers'][$i]['upload_image']['name']
152
                );
153
                $answer->setImage($media_url.$data['answers'][$i]['upload_image']['name']);
154
                ErrorHandler::stop(true);
155
            }
156
            $i++;
157
        }
158
159
        // Max points and correct answers recalculation for the quiz
160
        $quiz = $this->calculateMaxAnswersQuiz($question->getQuiz());
161
162
        // If the question was a pronostic, I update entries with the results !
163
        if ($question->getPrediction()) {
164
            $this->updatePrediction($question);
165
        }
166
167
        $this->getEventManager()->trigger(
168
            __FUNCTION__,
169
            $this,
170
            array('question' => $question, 'data' => $data)
171
        );
172
        $this->getQuizQuestionMapper()->update($question);
173
        $this->getEventManager()->trigger(
174
            __FUNCTION__ .'.post',
175
            $this,
176
            array('question' => $question, 'data' => $data)
177
        );
178
179
        $this->getQuizMapper()->update($quiz);
180
181
        return $question;
182
    }
183
184
    public function findRepliesByGame($game)
185
    {
186
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
187
        $qb = $em->createQueryBuilder();
188
        $qb->select('r')
189
           ->from('PlaygroundGame\Entity\QuizReply', 'r')
190
           ->innerJoin('r.entry', 'e')
191
           ->where('e.game = :game')
192
           ->setParameter('game', $game);
193
        $query = $qb->getQuery();
194
195
        $replies = $query->getResult();
196
197
        return $replies;
198
    }
199
200
    public function updatePrediction($question)
201
    {
202
        set_time_limit(0);
203
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
204
205
        /* @var $dbal \Doctrine\DBAL\Connection */
206
        $dbal = $em->getConnection();
207
208
        $answers = $question->getAnswers($question->getQuiz());
209
210
        // I update all the answers with points and correctness
211
        // Very fast (native query inside)
212
        if ($question->getType() == 2) {
213
            foreach ($answers as $answer) {
214
                $correct = (is_int($answer->getCorrect()))?$answer->getCorrect():0;
215
                $value  = trim(strip_tags($answer->getAnswer()));
216
                $points = ($correct)?$answer->getPoints():0;
217
                $sql    = "
218
                UPDATE game_quiz_reply_answer AS ra
219
                SET ra.points=IF(ra.answer=:answer, :points, 0),
220
                    ra.correct = IF(ra.answer=:answer, :isCorrect, 0)
221
                WHERE ra.question_id = :questionId
222
                ";
223
                $stmt = $dbal->prepare($sql);
224
                $stmt->execute(
225
                    array(
226
                        'answer'     => $value,
227
                        'points'     => $points,
228
                        'isCorrect'  => $correct,
229
                        'questionId' => $question->getId()
230
                    )
231
                );
232
            }
233
        } else {
234
            foreach ($answers as $answer) {
235
                $correct = (is_int($answer->getCorrect()))?$answer->getCorrect():0;
236
                $points = ($correct)?$answer->getPoints():0;
237
                $sql    = "
238
                UPDATE game_quiz_reply_answer AS ra
239
                SET ra.points=:points,
240
                    ra.correct = :isCorrect
241
                WHERE ra.question_id = :questionId
242
                    AND ra.answer_id = :answerId
243
                ";
244
245
                $stmt = $dbal->prepare($sql);
246
                $stmt->execute(
247
                    array(
248
                        'points'     => $points,
249
                        'isCorrect'  => $correct,
250
                        'questionId' => $question->getId(),
251
                        'answerId'   => $answer->getId()
252
                    )
253
                );
254
            }
255
        }
256
257
        // Entry update with points. WINNER as to be calculated also !
258
        $sql = "
259
        UPDATE game_entry as e
260
        INNER JOIN
261
        (
262
            SELECT e.id, SUM(ra.points) as points, SUM(ra.correct) as correct
263
            FROM game_entry as e
264
            INNER JOIN game_quiz_reply AS r ON r.entry_id = e.id
265
            INNER JOIN game_quiz_reply_answer AS ra ON ra.reply_id = r.id AND ra.correct = 1
266
            GROUP BY e.id
267
        ) i ON e.id = i.id
268
        SET e.points = i.points
269
        WHERE e.game_id = :gameId
270
        ";
271
272
        $stmt = $dbal->prepare($sql);
273
        $stmt->execute(
274
            array('gameId' => $question->getQuiz()->getId())
275
        );
276
277
        $this->getEventManager()->trigger(
278
            __FUNCTION__ .'.post',
279
            $this,
280
            array('question' => $question)
281
        );
282
    }
283
    /**
284
     * This function update the sort order of the questions in a Quiz
285
     * BEWARE : This function is time consuming (1s for 11 updates)
286
     * If you have many replies, switch to a  batch
287
     *
288
     * To improve performance, usage of DQL update
289
     * http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html
290
     *
291
     * @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...
292
     * @return boolean
293
     */
294
    public function updatePredictionOLD($question)
295
    {
296
        set_time_limit(0);
297
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
298
299
        $replies = $this->findRepliesByGame($question->getQuiz());
300
301
        $answers = $question->getAnswers($question->getQuiz());
302
303
        $answersarray = array();
304
        foreach ($answers as $answer) {
305
            $answersarray[$answer->getId()] = $answer;
306
        }
307
308
        foreach ($replies as $reply) {
309
            $quizPoints         = 0;
310
            $quizCorrectAnswers = 0;
311
312
            foreach ($reply->getAnswers() as $quizReplyAnswer) {
313
                if (2 != $question->getType() && $quizReplyAnswer->getQuestionId() === $question->getId()) {
314
                    if ($answersarray[$quizReplyAnswer->getAnswerId()]) {
315
                        $updatedAnswer = $answersarray[$quizReplyAnswer->getAnswerId()];
316
                        $quizReplyAnswer->setPoints($updatedAnswer->getPoints());
317
                        $quizReplyAnswer->setCorrect($updatedAnswer->getCorrect());
318
                        $q = $em->createQuery('
319
							UPDATE PlaygroundGame\Entity\QuizReplyAnswer a
320
              SET a.points = :points, a.correct=:isCorrect
321
              WHERE a.id=:answerId
322
						');
323
                        $q->setParameter('points', $updatedAnswer->getPoints());
324
                        $q->setParameter('isCorrect', $updatedAnswer->getCorrect());
325
                        $q->setParameter('answerId', $quizReplyAnswer->getId());
326
                        $q->execute();
327
                    }
328
                } elseif ($quizReplyAnswer->getQuestionId() === $question->getId()) {
329
                    // question is a textarea
330
                    // search for a matching answer
331
                    foreach ($answers as $answer) {
332
                        if (trim(strip_tags($answer->getAnswer())) == trim(
333
                            strip_tags($quizReplyAnswer->getAnswer())
334
                        )
335
                        ) {
336
                            $quizReplyAnswer->setPoints($answer->getPoints());
337
                            $quizReplyAnswer->setCorrect($answer->getCorrect());
338
                            $q = $em->createQuery('
339
                              UPDATE PlaygroundGame\Entity\QuizReplyAnswer a
340
                              SET a.points = :points, a.correct=:isCorrect
341
                              WHERE a.id=:answerId
342
                            ');
343
                            $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...
344
                            $q->setParameter('isCorrect', $updatedAnswer->getCorrect());
345
                            $q->setParameter('answerId', $quizReplyAnswer->getId());
346
                            $q->execute();
347
                        } else {
348
                            $quizReplyAnswer->setPoints(0);
349
                            $quizReplyAnswer->setCorrect(false);
350
                            $q = $em->createQuery('
351
                              UPDATE PlaygroundGame\Entity\QuizReplyAnswer a
352
                              SET a.points = 0, a.correct = false
353
                              WHERE a.id=:answerId
354
                            ');
355
                            $q->setParameter('answerId', $quizReplyAnswer->getId());
356
                            $q->execute();
357
                        }
358
                    }
359
                }
360
361
                // The reply has been updated with correct answers and points for this question.
362
                // I count the whole set of points for this reply and update the entry
363
                if ($quizReplyAnswer->getCorrect()) {
364
                    $quizPoints += $quizReplyAnswer->getPoints();
365
                    $quizCorrectAnswers += $quizReplyAnswer->getCorrect();
366
                }
367
            }
368
369
            $winner = $this->isWinner($question->getQuiz(), $quizCorrectAnswers);
370
            $reply->getEntry()->setWinner($winner);
371
            $reply->getEntry()->setPoints($quizPoints);
372
            // The entry should be inactive : entry->setActive(false);
373
            $this->getEntryMapper()->update($reply->getEntry());
374
        }
375
376
        $this->getEventManager()->trigger(
377
            __FUNCTION__ .'.post',
378
            $this,
379
            array('question' => $question)
380
        );
381
    }
382
383
    /**
384
     * This function update the sort order of the questions in a Quiz
385
     *
386
     * @param  string $data
387
     * @return boolean
388
     */
389
    public function sortQuestion($data)
390
    {
391
        $arr = explode(",", $data);
392
393
        foreach ($arr as $k => $v) {
394
            $question = $this->getQuizQuestionMapper()->findById($v);
395
            $question->setPosition($k);
396
            $this->getQuizQuestionMapper()->update($question);
397
        }
398
399
        return true;
400
    }
401
402
    /**
403
     * @return string
404
     */
405
    public function calculateMaxAnswersQuestion($question)
406
    {
407
        $question_max_points          = 0;
408
        $question_max_correct_answers = 0;
409
        // Closed question : Only one answer allowed
410
        if ($question->getType() == 0) {
411
            foreach ($question->getAnswers() as $answer) {
412
                if ($answer->getPoints() > $question_max_points) {
413
                    $question_max_points = $answer->getPoints();
414
                }
415
                if ($answer->getCorrect() && $question_max_correct_answers == 0) {
416
                    $question_max_correct_answers = 1;
417
                }
418
            }
419
            // if ($question_max_correct_answers == 0) {
420
            //     return false;
421
            // }
422
            // Closed question : Many answers allowed
423
        } elseif ($question->getType() == 1) {
424
            foreach ($question->getAnswers() as $answer) {
425
                $question_max_points += $answer->getPoints();
426
427
                if ($answer->getCorrect()) {
428
                    ++$question_max_correct_answers;
429
                }
430
            }
431
            // if ($question_max_correct_answers == 0) {
432
            //     return false;
433
            // }
434
            // Not a question : A textarea to fill in
435
        } elseif ($question->getType() == 2) {
436
            $question_max_correct_answers = 0;
437
        }
438
439
        $question->setMaxPoints($question_max_points);
440
        $question->setMaxCorrectAnswers($question_max_correct_answers);
441
442
        return $question;
443
    }
444
445
    public function calculateMaxAnswersQuiz($quiz)
446
    {
447
        $question_max_points          = 0;
448
        $question_max_correct_answers = 0;
449
        foreach ($quiz->getQuestions() as $question) {
450
            $question_max_points += $question->getMaxPoints();
451
            $question_max_correct_answers += $question->getMaxCorrectAnswers();
452
        }
453
        $quiz->setMaxPoints($question_max_points);
454
        $quiz->setMaxCorrectAnswers($question_max_correct_answers);
455
456
        return $quiz;
457
    }
458
459 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...
460
    {
461
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
462
463
        $query = $em->createQuery(
464
            "SELECT COUNT(e.id) FROM PlaygroundGame\Entity\Entry e, PlaygroundGame\Entity\Game g
465
                WHERE e.user = :user
466
                AND g.classType = 'quiz'
467
                AND e.points > 0"
468
        );
469
        $query->setParameter('user', $user);
470
        $number = $query->getSingleScalarResult();
471
472
        return $number;
473
    }
474
475
    public function createQuizReply($data, $game, $user)
476
    {
477
        // Si mon nb de participation est < au nb autorisé, j'ajoute une entry + reponses au quiz et points
478
        $quizReplyMapper = $this->getQuizReplyMapper();
479
        $entryMapper     = $this->getEntryMapper();
480
        $entry           = $this->findLastActiveEntry($game, $user);
481
482
        if (!$entry) {
483
            return false;
484
        }
485
486
        $quizPoints         = 0;
487
        $quizCorrectAnswers = 0;
488
        $maxCorrectAnswers  = $game->getMaxCorrectAnswers();
489
        $totalQuestions     = 0;
490
491
        $quizReply = $this->getQuizReplyMapper()->getLastGameReply($entry);
492
        if (!$quizReply) {
493
            $quizReply = new QuizReply();
494
        } else {
495
            $quizReplyAnswered = [];
496
            foreach ($quizReply->getAnswers() as $answer) {
497
                $quizReplyAnswered[$answer->getQuestionId()] = $answer;
498
            }
499
        }
500
501
        foreach ($data as $group) {
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
        $winner = $this->isWinner($game, $quizCorrectAnswers);
593
594
        $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...
595
        // Every winning participation is eligible to draw
596
        // Make this modifiable in the admin (choose who can participate to draw)
597
        $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...
598
        $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...
599
        $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...
600
        $entry = $entryMapper->update($entry);
601
602
        $quizReply->setEntry($entry);
603
        $quizReply->setTotalCorrectAnswers($quizCorrectAnswers);
604
        $quizReply->setMaxCorrectAnswers($maxCorrectAnswers);
605
        $quizReply->setTotalQuestions($totalQuestions);
606
607
        $quizReplyMapper->insert($quizReply);
608
609
        $this->getEventManager()->trigger(
610
            __FUNCTION__ .'.post',
611
            $this,
612
            array('user' => $user, 'entry' => $entry, 'reply' => $quizReply, 'game' => $game)
613
        );
614
615
        return $entry;
616
    }
617
618
    public function isWinner($game, $quizCorrectAnswers = 0)
619
    {
620
        // Pour déterminer le gagnant, je regarde le nombre max de reponses correctes possibles
621
        // dans le jeu, puis je calcule le ratio de bonnes réponses et le compare aux conditions
622
        // de victoire
623
        $winner            = false;
624
        $maxCorrectAnswers = $game->getMaxCorrectAnswers();
625
        if ($maxCorrectAnswers > 0) {
626
            $ratioCorrectAnswers = ($quizCorrectAnswers/$maxCorrectAnswers)*100;
627
        } elseif ($game->getVictoryConditions() > 0) {
628
            // In the case I have a pronostic game for example
629
            $ratioCorrectAnswers = 0;
630
        } else {
631
            // In the case I want everybody to win
632
            $ratioCorrectAnswers = 100;
633
        }
634
635
        if ($game->getVictoryConditions() >= 0) {
636
            if ($ratioCorrectAnswers >= $game->getVictoryConditions()) {
637
                $winner = true;
638
            }
639
        }
640
        return $winner;
641
    }
642
643
    public function getEntriesHeader($game)
644
    {
645
        $header                        = parent::getEntriesHeader($game);
646
        $header['totalCorrectAnswers'] = 1;
647
648
        return $header;
649
    }
650
651 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...
652
    {
653
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
654
655
        $qb = $em->createQueryBuilder();
656
        $qb->select('
657
            r.id,
658
            u.username,
659
            u.title,
660
            u.firstname,
661
            u.lastname,
662
            u.email,
663
            u.optin,
664
            u.optinPartner,
665
            u.address,
666
            u.address2,
667
            u.postalCode,
668
            u.city,
669
            u.telephone,
670
            u.mobile,
671
            u.created_at,
672
            u.dob,
673
            e.winner,
674
            e.socialShares,
675
            e.playerData,
676
            e.updated_at,
677
            r.totalCorrectAnswers
678
            ')
679
        ->from('PlaygroundGame\Entity\QuizReply', 'r')
680
        ->innerJoin('r.entry', 'e')
681
        ->leftJoin('e.user', 'u')
682
        ->where($qb->expr()->eq('e.game', ':game'));
683
684
        $qb->setParameter('game', $game);
685
686
        return $qb->getQuery();
687
    }
688
689
    public function getGameEntity()
690
    {
691
        return new \PlaygroundGame\Entity\Quiz;
692
    }
693
694
    /**
695
     * getQuizMapper
696
     *
697
     * @return QuizMapperInterface
698
     */
699
    public function getQuizMapper()
700
    {
701
        if (null === $this->quizMapper) {
702
            $this->quizMapper = $this->serviceLocator->get('playgroundgame_quiz_mapper');
703
        }
704
705
        return $this->quizMapper;
706
    }
707
708
    /**
709
     * setQuizMapper
710
     *
711
     * @param  QuizMapperInterface $quizMapper
712
     * @return Game
713
     */
714
    public function setQuizMapper(GameMapperInterface $quizMapper)
715
    {
716
        $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...
717
718
        return $this;
719
    }
720
721
    /**
722
     * getQuizQuestionMapper
723
     *
724
     * @return QuizQuestionMapperInterface
725
     */
726
    public function getQuizQuestionMapper()
727
    {
728
        if (null === $this->quizQuestionMapper) {
729
            $this->quizQuestionMapper = $this->serviceLocator->get('playgroundgame_quizquestion_mapper');
730
        }
731
732
        return $this->quizQuestionMapper;
733
    }
734
735
    /**
736
     * setQuizQuestionMapper
737
     *
738
     * @param  QuizQuestionMapperInterface $quizquestionMapper
739
     * @return Quiz
740
     */
741
    public function setQuizQuestionMapper($quizquestionMapper)
742
    {
743
        $this->quizQuestionMapper = $quizquestionMapper;
744
745
        return $this;
746
    }
747
748
    /**
749
     * setQuizAnswerMapper
750
     *
751
     * @param  QuizAnswerMapperInterface $quizAnswerMapper
752
     * @return Quiz
753
     */
754
    public function setQuizAnswerMapper($quizAnswerMapper)
755
    {
756
        $this->quizAnswerMapper = $quizAnswerMapper;
757
758
        return $this;
759
    }
760
761
    /**
762
     * getQuizAnswerMapper
763
     *
764
     * @return QuizAnswerMapperInterface
765
     */
766
    public function getQuizAnswerMapper()
767
    {
768
        if (null === $this->quizAnswerMapper) {
769
            $this->quizAnswerMapper = $this->serviceLocator->get('playgroundgame_quizanswer_mapper');
770
        }
771
772
        return $this->quizAnswerMapper;
773
    }
774
775
    /**
776
     * getQuizReplyMapper
777
     *
778
     * @return QuizReplyMapperInterface
779
     */
780
    public function getQuizReplyMapper()
781
    {
782
        if (null === $this->quizReplyMapper) {
783
            $this->quizReplyMapper = $this->serviceLocator->get('playgroundgame_quizreply_mapper');
784
        }
785
786
        return $this->quizReplyMapper;
787
    }
788
789
    /**
790
     * setQuizReplyMapper
791
     *
792
     * @param  QuizReplyMapperInterface $quizreplyMapper
793
     * @return Quiz
794
     */
795
    public function setQuizReplyMapper($quizreplyMapper)
796
    {
797
        $this->quizReplyMapper = $quizreplyMapper;
798
799
        return $this;
800
    }
801
802
    /**
803
     * getQuizReplyAnswerMapper
804
     *
805
     * @return QuizReplyAnswerMapper
806
     */
807
    public function getQuizReplyAnswerMapper()
808
    {
809
        if (null === $this->quizReplyAnswerMapper) {
810
            $this->quizReplyAnswerMapper = $this->serviceLocator->get('playgroundgame_quizreplyanswer_mapper');
811
        }
812
813
        return $this->quizReplyAnswerMapper;
814
    }
815
816
    /**
817
     * setQuizReplyAnswerMapper
818
     *
819
     * @param  QuizReplyAnswerMapper $quizReplyAnswerMapper
820
     * @return Quiz
821
     */
822
    public function setQuizReplyAnswerMapper($quizReplyAnswerMapper)
823
    {
824
        $this->quizReplyAnswerMapper = $quizReplyAnswerMapper;
825
826
        return $this;
827
    }
828
}
829