Completed
Push — develop ( f46b16...00b32b )
by greg
09:54
created

Quiz::getEntriesHeader()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 7
rs 9.4285
cc 1
eloc 4
nc 1
nop 1
1
<?php
2
3
namespace PlaygroundGame\Service;
4
5
use PlaygroundGame\Entity\QuizReply;
6
use PlaygroundGame\Entity\QuizReplyAnswer;
7
use Zend\ServiceManager\ServiceManagerAwareInterface;
8
use PlaygroundGame\Mapper\GameInterface as GameMapperInterface;
9
use Zend\Stdlib\ErrorHandler;
10
11
class Quiz extends Game implements ServiceManagerAwareInterface
12
{
13
    /**
14
     * @var QuizMapperInterface
15
     */
16
    protected $quizMapper;
17
18
    /**
19
     * @var QuizAnswerMapperInterface
20
     */
21
    protected $quizAnswerMapper;
22
23
    /**
24
     * @var QuizQuestionMapperInterface
25
     */
26
    protected $quizQuestionMapper;
27
28
    /**
29
     * @var QuizReplyMapperInterface
30
     */
31
    protected $quizReplyMapper;
32
33
    /**
34
     * @var quizReplyAnswerMapper
35
     */
36
    protected $quizReplyAnswerMapper;
37
38
    /**
39
     *
40
     *
41
     * @param  array                  $data
42
     * @return \PlaygroundGame\Entity\Game
43
     */
44
    public function createQuestion(array $data)
45
    {
46
        $path = $this->getOptions()->getMediaPath() . DIRECTORY_SEPARATOR;
47
        $media_url = $this->getOptions()->getMediaUrl() . '/';
48
49
        $question  = new \PlaygroundGame\Entity\QuizQuestion();
50
        $form  = $this->getServiceManager()->get('playgroundgame_quizquestion_form');
51
        $form->bind($question);
52
        $form->setData($data);
53
54
        $quiz = $this->getGameMapper()->findById($data['quiz_id']);
55
        if (!$form->isValid()) {
56
            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::createQuestion 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...
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)) {
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->calculateMaxAnswersQuestion($question); of type string adds the type string to the return on line 90 which is incompatible with the return type documented by PlaygroundGame\Service\Quiz::createQuestion of type PlaygroundGame\Entity\Game.
Loading history...
65
                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::createQuestion 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...
66
            }
67
        }
68
69
        // Max points and correct answers recalculation for the quiz
70
        $quiz = $this->calculateMaxAnswersQuiz($question->getQuiz());
71
72
        $this->getEventManager()->trigger(__FUNCTION__, $this, array('game' => $question, 'data' => $data));
73
        $this->getQuizQuestionMapper()->insert($question);
74
        $this->getEventManager()->trigger(__FUNCTION__.'.post', $this, array('game' => $question, 'data' => $data));
75
76 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...
77
            ErrorHandler::start();
78
            $data['upload_image']['name'] = $this->fileNewname(
79
                $path,
80
                $question->getId() . "-" . $data['upload_image']['name']
81
            );
82
            move_uploaded_file($data['upload_image']['tmp_name'], $path . $data['upload_image']['name']);
83
            $question->setImage($media_url . $data['upload_image']['name']);
84
            ErrorHandler::stop(true);
85
        }
86
87
        $this->getQuizQuestionMapper()->update($question);
88
        $this->getQuizMapper()->update($quiz);
89
90
        return $question;
91
    }
92
93
    /**
94
     * @param  array $data
95
     * @return \PlaygroundGame\Entity\Game
96
     */
97
    public function updateQuestion(array $data, $question)
98
    {
99
        $path = $this->getOptions()->getMediaPath() . DIRECTORY_SEPARATOR;
100
        $media_url = $this->getOptions()->getMediaUrl() . '/';
101
102
        $form  = $this->getServiceManager()->get('playgroundgame_quizquestion_form');
103
        $form->bind($question);
104
        $form->setData($data);
105
106
        if (!$form->isValid()) {
107
            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...
108
        }
109
110
        // If question is a prediction, no need to calculate max good answers
111
        if (!$question->getPrediction()) {
112
            // Max points and correct answers calculation for the question
113
            if (!$question = $this->calculateMaxAnswersQuestion($question)) {
114
                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...
115
            }
116
        }
117
118 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...
119
            ErrorHandler::start();
120
            $data['upload_image']['name'] = $this->fileNewname(
121
                $path,
122
                $question->getId() . "-" . $data['upload_image']['name']
123
            );
124
            move_uploaded_file($data['upload_image']['tmp_name'], $path . $data['upload_image']['name']);
125
            $question->setImage($media_url . $data['upload_image']['name']);
126
            ErrorHandler::stop(true);
127
        }
128
129 View Code Duplication
        if (isset($data['delete_image']) && 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...
130
            ErrorHandler::start();
131
            $image = $question->getImage();
132
            $image = str_replace($media_url, '', $image);
133
            if (file_exists($path .$image)) {
134
                unlink($path .$image);
135
            }
136
            $question->setImage(null);
137
            ErrorHandler::stop(true);
138
        }
139
        
140
        $i = 0;
141
        foreach ($question->getAnswers() as $answer) {
142
            if (!empty($data['answers'][$i]['upload_image']['tmp_name'])) {
143
                ErrorHandler::start();
144
                $data['answers'][$i]['upload_image']['name'] = $this->fileNewname(
145
                    $path,
146
                    $question->getId() . "-" . $data['answers'][$i]['upload_image']['name']
147
                );
148
                move_uploaded_file(
149
                    $data['answers'][$i]['upload_image']['tmp_name'],
150
                    $path . $data['answers'][$i]['upload_image']['name']
151
                );
152
                $answer->setImage($media_url . $data['answers'][$i]['upload_image']['name']);
153
                ErrorHandler::stop(true);
154
            }
155
            $i++;
156
        }
157
158
        // Max points and correct answers recalculation for the quiz
159
        $quiz = $this->calculateMaxAnswersQuiz($question->getQuiz());
160
161
        // If the question was a pronostic, I update entries with the results !
162
        if ($question->getPrediction()) {
163
            $this->updatePrediction($question);
164
        }
165
166
        $this->getEventManager()->trigger(
167
            __FUNCTION__,
168
            $this,
169
            array('question' => $question, 'data' => $data)
170
        );
171
        $this->getQuizQuestionMapper()->update($question);
172
        $this->getEventManager()->trigger(
173
            __FUNCTION__.'.post',
174
            $this,
175
            array('question' => $question, 'data' => $data)
176
        );
177
178
        $this->getQuizMapper()->update($quiz);
179
180
        return $question;
181
    }
182
183
    public function findRepliesByGame($game)
184
    {
185
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
186
        $qb = $em->createQueryBuilder();
187
        $qb->select('r')
188
            ->from('PlaygroundGame\Entity\QuizReply', 'r')
189
            ->innerJoin('r.entry', 'e')
190
            ->where('e.game = :game')
191
            ->setParameter('game', $game);
192
        $query = $qb->getQuery();
193
        
194
        $replies = $query->getResult();
195
196
        return $replies;
197
    }
198
199
    /**
200
     * This function update the sort order of the questions in a Quiz
201
     * BEWARE : This function is time consuming (1s for 11 updates)
202
     * If you have many replies, switch to a  batch
203
     * 
204
     * To improve performance, usage of DQL update
205
     * http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html
206
     *
207
     * @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...
208
     * @return boolean
209
     */
210
    public function updatePrediction($question)
211
    {
212
        set_time_limit(0);
213
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
214
215
        $replies = $this->findRepliesByGame($question->getQuiz());
216
217
        $answers = $question->getAnswers($question->getQuiz());
218
219
        $answersarray = array();
220
        foreach ($answers as $answer) {
221
            $answersarray[$answer->getId()] = $answer;
222
        }
223
224
        foreach ($replies as $reply) {
225
            $quizPoints = 0;
226
            $quizCorrectAnswers = 0;
227
228
            foreach ($reply->getAnswers() as $quizReplyAnswer) {
229
                if (2 != $question->getType() && $quizReplyAnswer->getQuestionId() === $question->getId()) {
230
                    if ($answersarray[$quizReplyAnswer->getAnswerId()]) {
231
                        $updatedAnswer = $answersarray[$quizReplyAnswer->getAnswerId()];
232
                        $quizReplyAnswer->setPoints($updatedAnswer->getPoints());
233
                        $quizReplyAnswer->setCorrect($updatedAnswer->getCorrect());
234
                        $q = $em->createQuery(
235
                            'update PlaygroundGame\Entity\QuizReplyAnswer a SET a.points = ' . 
236
                            $updatedAnswer->getPoints() . ',a.correct=' . $updatedAnswer->getCorrect() . 
237
                            ' WHERE a.id=' .$quizReplyAnswer->getId()
238
                        );
239
                        $q->execute();
240
                    }
241
                } else if($quizReplyAnswer->getQuestionId() === $question->getId()){
242
                    // question is a textarea
243
                    // search for a matching answer
244
                    foreach ($answers as $answer) {
245
                        if (trim(strip_tags($answer->getAnswer())) == trim(
246
                            strip_tags($quizReplyAnswer->getAnswer())
247
                        )
248
                        ) {
249
                            $quizReplyAnswer->setPoints($answer->getPoints());
250
                            $quizReplyAnswer->setCorrect($answer->getCorrect());
251
                            $q = $em->createQuery(
252
                                'update PlaygroundGame\Entity\QuizReplyAnswer a SET a.points = ' . 
253
                                $answer->getPoints() . ', a.correct='.$answer->getCorrect() 
254
                                . ' WHERE a.id=' .$quizReplyAnswer->getId()
255
                            );
256
                            $q->execute();
257
                        } else {
258
                            $quizReplyAnswer->setPoints(0);
259
                            $quizReplyAnswer->setCorrect(false);
260
                            $q = $em->createQuery(
261
                                'update PlaygroundGame\Entity\QuizReplyAnswer a SET a.points = 0, a.correct = false WHERE a.id=' .
262
                                $quizReplyAnswer->getId()
263
                            );
264
                            $q->execute();
265
                        }
266
                    }
267
                }
268
269
                // The reply has been updated with correct answers and points for this question.
270
                // I count the whole set of points for this reply and update the entry
271
                if ($quizReplyAnswer->getCorrect()) {
272
                    $quizPoints += $quizReplyAnswer->getPoints();
273
                    $quizCorrectAnswers += $quizReplyAnswer->getCorrect();
274
                }
275
            }
276
            
277
            $winner = $this->isWinner($question->getQuiz(), $quizCorrectAnswers);
278
            $reply->getEntry()->setWinner($winner);
279
            $reply->getEntry()->setPoints($quizPoints);
280
            // The entry should be inactive : entry->setActive(false);
281
            $this->getEntryMapper()->update($reply->getEntry());
282
        }
283
284
        $this->getEventManager()->trigger(
285
            __FUNCTION__.'.post',
286
            $this,
287
            array('question' => $question)
288
        );
289
    }
290
291
    /**
292
     * This function update the sort order of the questions in a Quiz
293
     *
294
     * @param  string $data
295
     * @return boolean
296
     */
297
    public function sortQuestion($data)
298
    {
299
        $arr = explode(",", $data);
300
301
        foreach ($arr as $k => $v) {
302
            $question = $this->getQuizQuestionMapper()->findById($v);
303
            $question->setPosition($k);
304
            $this->getQuizQuestionMapper()->update($question);
305
        }
306
307
        return true;
308
    }
309
310
    /**
311
     * @return string
312
     */
313
    public function calculateMaxAnswersQuestion($question)
314
    {
315
        $question_max_points = 0;
316
        $question_max_correct_answers = 0;
317
        // Closed question : Only one answer allowed
318
        if ($question->getType() == 0) {
319
            foreach ($question->getAnswers() as $answer) {
320
                if ($answer->getPoints() > $question_max_points) {
321
                    $question_max_points = $answer->getPoints();
322
                }
323
                if ($answer->getCorrect() && $question_max_correct_answers==0) {
324
                    $question_max_correct_answers=1;
325
                }
326
            }
327
            if ($question_max_correct_answers == 0) {
328
                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\Q...ulateMaxAnswersQuestion of type string.

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...
329
            }
330
        // Closed question : Many answers allowed
331
        } elseif ($question->getType() == 1) {
332
            foreach ($question->getAnswers() as $answer) {
333
                $question_max_points += $answer->getPoints();
334
335
                if ($answer->getCorrect()) {
336
                    ++$question_max_correct_answers;
337
                }
338
            }
339
            if ($question_max_correct_answers == 0) {
340
                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\Q...ulateMaxAnswersQuestion of type string.

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...
341
            }
342
        // Not a question : A textarea to fill in
343
        } elseif ($question->getType() == 2) {
344
            $question_max_correct_answers = 0;
345
        }
346
347
        $question->setMaxPoints($question_max_points);
348
        $question->setMaxCorrectAnswers($question_max_correct_answers);
349
350
        return $question;
351
    }
352
353
    public function calculateMaxAnswersQuiz($quiz)
354
    {
355
        $question_max_points = 0;
356
        $question_max_correct_answers = 0;
357
        foreach ($quiz->getQuestions() as $question) {
358
            $question_max_points += $question->getMaxPoints();
359
            $question_max_correct_answers += $question->getMaxCorrectAnswers();
360
        }
361
        $quiz->setMaxPoints($question_max_points);
362
        $quiz->setMaxCorrectAnswers($question_max_correct_answers);
363
364
        return $quiz;
365
    }
366
367 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...
368
    {
369
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
370
371
        $query = $em->createQuery(
372
            "SELECT COUNT(e.id) FROM PlaygroundGame\Entity\Entry e, PlaygroundGame\Entity\Game g
373
                WHERE e.user = :user
374
                AND g.classType = 'quiz'
375
                AND e.points > 0"
376
        );
377
        $query->setParameter('user', $user);
378
        $number = $query->getSingleScalarResult();
379
380
        return $number;
381
    }
382
383
    public function createQuizReply($data, $game, $user)
384
    {
385
        // Si mon nb de participation est < au nb autorisé, j'ajoute une entry + reponses au quiz et points
386
        $quizReplyMapper = $this->getQuizReplyMapper();
387
        $entryMapper = $this->getEntryMapper();
388
        $entry = $this->findLastActiveEntry($game, $user);
389
390
        if (!$entry) {
391
            return false;
392
        }
393
394
        $quizPoints          = 0;
395
        $quizCorrectAnswers  = 0;
396
        $maxCorrectAnswers = $game->getMaxCorrectAnswers();
397
        $totalQuestions = 0;
398
399
        $quizReply = $this->getQuizReplyMapper()->getLastGameReply($entry);
400
        if (!$quizReply) {
401
            $quizReply = new QuizReply();
402
        } else {
403
            foreach ($quizReply->getAnswers() as $answer) {
404
                $this->getQuizReplyAnswerMapper()->remove($answer);
405
            }
406
        }
407
        
408
        foreach ($data as $group) {
409
            foreach ($group as $q => $a) {
410
                if (strlen($q) > 5 && strpos($q, '-data', strlen($q) - 5) !== false) {
411
                    continue; // answer data is processed below
412
                }
413
                $question = $this->getQuizQuestionMapper()->findById((int) str_replace('q', '', $q));
414
                ++$totalQuestions;
415
                if (is_array($a)) {
416
                    foreach ($a as $k => $answer_id) {
417
                        $answer = $this->getQuizAnswerMapper()->findById($answer_id);
418 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...
419
                            $quizReplyAnswer = new QuizReplyAnswer();
420
                            $quizReplyAnswer->setAnswer($answer->getAnswer());
421
                            $quizReplyAnswer->setAnswerId($answer_id);
422
                            $quizReplyAnswer->setQuestion($question->getQuestion());
423
                            $quizReplyAnswer->setQuestionId($question->getId());
424
                            $quizReplyAnswer->setPoints($answer->getPoints());
425
                            $quizReplyAnswer->setCorrect($answer->getCorrect());
426
427
                            $quizReply->addAnswer($quizReplyAnswer);
428
                            $quizPoints += $answer->getPoints();
429
                            $quizCorrectAnswers += $answer->getCorrect();
430
431
                            if (isset($group[$q.'-'.$answer_id.'-data'])) {
432
                                $quizReplyAnswer->setAnswerData($group[$q.'-'.$answer_id.'-data']);
433
                            }
434
                        }
435
                    }
436
                } elseif ($question->getType() == 0 || $question->getType() == 1) {
437
                    ++$totalQuestions;
438
                    $answer = $this->getQuizAnswerMapper()->findById($a);
439 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...
440
                        $quizReplyAnswer = new QuizReplyAnswer();
441
                        $quizReplyAnswer->setAnswer($answer->getAnswer());
442
                        $quizReplyAnswer->setAnswerId($a);
443
                        $quizReplyAnswer->setQuestion($question->getQuestion());
444
                        $quizReplyAnswer->setQuestionId($question->getId());
445
                        $quizReplyAnswer->setPoints($answer->getPoints());
446
                        $quizReplyAnswer->setCorrect($answer->getCorrect());
447
448
                        $quizReply->addAnswer($quizReplyAnswer);
449
                        $quizPoints += $answer->getPoints();
450
                        $quizCorrectAnswers += $answer->getCorrect();
451
                        if (isset($group[$q.'-'.$a.'-data'])) {
452
                            $quizReplyAnswer->setAnswerData($group[$q.'-'.$a.'-data']);
453
                        }
454
                    }
455
                } elseif ($question->getType() == 2) {
456
                    ++$totalQuestions;
457
                    $quizReplyAnswer = new QuizReplyAnswer();
458
                    
459
                    $quizReplyAnswer->setAnswer($a);
460
                    $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...
461
                    $quizReplyAnswer->setQuestion($question->getQuestion());
462
                    $quizReplyAnswer->setQuestionId($question->getId());
463
                    $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...
464
                    $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...
465
466
                    $quizReply->addAnswer($quizReplyAnswer);
467
                    $quizPoints += 0;
468
                    $quizCorrectAnswers += 0;
469
                    $qAnswers = $question->getAnswers();
470
                    foreach ($qAnswers as $qAnswer) {
471
                        if (trim(strip_tags($a)) == trim(strip_tags($qAnswer->getAnswer()))) {
472
                            $quizReplyAnswer->setPoints($qAnswer->getPoints());
473
                            $quizPoints += $qAnswer->getPoints();
474
                            $quizReplyAnswer->setCorrect($qAnswer->getCorrect());
475
                            $quizCorrectAnswers += $qAnswer->getCorrect();
476
                            break;
477
                        }
478
                    }
479
480
                    if (isset($group[$q.'-'.$a.'-data'])) {
481
                        $quizReplyAnswer->setAnswerData($group[$q.'-'.$a.'-data']);
482
                    }
483
                }
484
            }
485
        }
486
487
        $winner = $this->isWinner($game, $quizCorrectAnswers);
488
489
        $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...
490
        // Every winning participation is eligible to draw
491
        // Make this modifiable in the admin (choose who can participate to draw)
492
        $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...
493
        $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...
494
        $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...
495
        $entry = $entryMapper->update($entry);
496
497
        $quizReply->setEntry($entry);
498
        $quizReply->setTotalCorrectAnswers($quizCorrectAnswers);
499
        $quizReply->setMaxCorrectAnswers($maxCorrectAnswers);
500
        $quizReply->setTotalQuestions($totalQuestions);
501
502
        $quizReplyMapper->insert($quizReply);
503
504
        $this->getEventManager()->trigger(
505
            __FUNCTION__.'.post',
506
            $this,
507
            array('user' => $user, 'entry' => $entry, 'reply' => $quizReply, 'game' => $game)
508
        );
509
510
        return $entry;
511
    }
512
513
    public function isWinner($game, $quizCorrectAnswers = 0)
514
    {
515
        // Pour déterminer le gagnant, je regarde le nombre max de reponses correctes possibles
516
        // dans le jeu, puis je calcule le ratio de bonnes réponses et le compare aux conditions
517
        // de victoire
518
        $winner = false;
0 ignored issues
show
Unused Code introduced by
$winner is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
519
        $maxCorrectAnswers = $game->getMaxCorrectAnswers();
520
        if ($maxCorrectAnswers > 0) {
521
            $ratioCorrectAnswers = ($quizCorrectAnswers / $maxCorrectAnswers) * 100;
522
        } elseif ($game->getVictoryConditions() > 0) {
523
            // In the case I have a pronostic game for example
524
            $ratioCorrectAnswers = 0;
525
        } else {
526
            // In the case I want everybody to win
527
            $ratioCorrectAnswers = 100;
528
        }
529
530
        $winner = false;
531
        if ($game->getVictoryConditions() >= 0) {
532
            if ($ratioCorrectAnswers >= $game->getVictoryConditions()) {
533
                $winner = true;
534
            }
535
        }
536
        return $winner;
537
    }
538
539
    public function getEntriesHeader($game)
540
    {
541
        $header = parent::getEntriesHeader($game);
542
        $header['totalCorrectAnswers'] = 1;
543
544
        return $header;
545
    }
546
547 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...
548
    {
549
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
550
551
        $qb = $em->createQueryBuilder();
552
        $qb->select('
553
            r.id,
554
            u.username,
555
            u.title,
556
            u.firstname,
557
            u.lastname,
558
            u.email,
559
            u.optin,
560
            u.optinPartner,
561
            u.address,
562
            u.address2,
563
            u.postalCode,
564
            u.city,
565
            u.telephone,
566
            u.mobile,
567
            u.created_at,
568
            u.dob,
569
            e.winner,
570
            e.socialShares,
571
            e.playerData,
572
            e.updated_at,
573
            r.totalCorrectAnswers
574
            ')
575
            ->from('PlaygroundGame\Entity\QuizReply', 'r')
576
            ->innerJoin('r.entry', 'e')
577
            ->leftJoin('e.user', 'u')
578
            ->where($qb->expr()->eq('e.game', ':game'));
579
        
580
        $qb->setParameter('game', $game);
581
582
        return $qb->getQuery();
583
    }
584
585
    public function getGameEntity()
586
    {
587
        return new \PlaygroundGame\Entity\Quiz;
588
    }
589
590
    /**
591
     * getQuizMapper
592
     *
593
     * @return QuizMapperInterface
594
     */
595
    public function getQuizMapper()
596
    {
597
        if (null === $this->quizMapper) {
598
            $this->quizMapper = $this->getServiceManager()->get('playgroundgame_quiz_mapper');
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->getServiceManager...roundgame_quiz_mapper') can also be of type array. However, the property $quizMapper is declared as type object<PlaygroundGame\Se...ce\QuizMapperInterface>. Maybe add an additional type check?

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

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

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

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
599
        }
600
601
        return $this->quizMapper;
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->quizMapper; of type object|array adds the type array to the return on line 601 which is incompatible with the return type documented by PlaygroundGame\Service\Quiz::getQuizMapper of type PlaygroundGame\Service\QuizMapperInterface.
Loading history...
602
    }
603
604
    /**
605
     * setQuizMapper
606
     *
607
     * @param  QuizMapperInterface $quizMapper
608
     * @return Game
609
     */
610
    public function setQuizMapper(GameMapperInterface $quizMapper)
611
    {
612
        $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...
613
614
        return $this;
615
    }
616
617
    /**
618
     * getQuizQuestionMapper
619
     *
620
     * @return QuizQuestionMapperInterface
621
     */
622
    public function getQuizQuestionMapper()
623
    {
624
        if (null === $this->quizQuestionMapper) {
625
            $this->quizQuestionMapper = $this->getServiceManager()->get('playgroundgame_quizquestion_mapper');
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->getServiceManager...e_quizquestion_mapper') can also be of type array. However, the property $quizQuestionMapper is declared as type object<PlaygroundGame\Se...uestionMapperInterface>. Maybe add an additional type check?

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

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

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

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
626
        }
627
628
        return $this->quizQuestionMapper;
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->quizQuestionMapper; of type object|array adds the type array to the return on line 628 which is incompatible with the return type documented by PlaygroundGame\Service\Quiz::getQuizQuestionMapper of type PlaygroundGame\Service\QuizQuestionMapperInterface.
Loading history...
629
    }
630
631
    /**
632
     * setQuizQuestionMapper
633
     *
634
     * @param  QuizQuestionMapperInterface $quizquestionMapper
635
     * @return Quiz
636
     */
637
    public function setQuizQuestionMapper($quizquestionMapper)
638
    {
639
        $this->quizQuestionMapper = $quizquestionMapper;
640
641
        return $this;
642
    }
643
644
    /**
645
     * setQuizAnswerMapper
646
     *
647
     * @param  QuizAnswerMapperInterface $quizAnswerMapper
648
     * @return Quiz
649
     */
650
    public function setQuizAnswerMapper($quizAnswerMapper)
651
    {
652
        $this->quizAnswerMapper = $quizAnswerMapper;
653
654
        return $this;
655
    }
656
657
    /**
658
     * getQuizAnswerMapper
659
     *
660
     * @return QuizAnswerMapperInterface
661
     */
662
    public function getQuizAnswerMapper()
663
    {
664
        if (null === $this->quizAnswerMapper) {
665
            $this->quizAnswerMapper = $this->getServiceManager()->get('playgroundgame_quizanswer_mapper');
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->getServiceManager...ame_quizanswer_mapper') can also be of type array. However, the property $quizAnswerMapper is declared as type object<PlaygroundGame\Se...zAnswerMapperInterface>. Maybe add an additional type check?

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

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

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

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
666
        }
667
668
        return $this->quizAnswerMapper;
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->quizAnswerMapper; of type object|array adds the type array to the return on line 668 which is incompatible with the return type documented by PlaygroundGame\Service\Quiz::getQuizAnswerMapper of type PlaygroundGame\Service\QuizAnswerMapperInterface.
Loading history...
669
    }
670
671
    /**
672
     * getQuizReplyMapper
673
     *
674
     * @return QuizReplyMapperInterface
675
     */
676
    public function getQuizReplyMapper()
677
    {
678
        if (null === $this->quizReplyMapper) {
679
            $this->quizReplyMapper = $this->getServiceManager()->get('playgroundgame_quizreply_mapper');
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->getServiceManager...game_quizreply_mapper') can also be of type array. However, the property $quizReplyMapper is declared as type object<PlaygroundGame\Se...izReplyMapperInterface>. Maybe add an additional type check?

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

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

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

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
680
        }
681
682
        return $this->quizReplyMapper;
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->quizReplyMapper; of type object|array adds the type array to the return on line 682 which is incompatible with the return type documented by PlaygroundGame\Service\Quiz::getQuizReplyMapper of type PlaygroundGame\Service\QuizReplyMapperInterface.
Loading history...
683
    }
684
685
    /**
686
     * setQuizReplyMapper
687
     *
688
     * @param  QuizReplyMapperInterface $quizreplyMapper
689
     * @return Quiz
690
     */
691
    public function setQuizReplyMapper($quizreplyMapper)
692
    {
693
        $this->quizReplyMapper = $quizreplyMapper;
694
695
        return $this;
696
    }
697
698
    /**
699
     * getQuizReplyAnswerMapper
700
     *
701
     * @return QuizReplyAnswerMapper
702
     */
703
    public function getQuizReplyAnswerMapper()
704
    {
705
        if (null === $this->quizReplyAnswerMapper) {
706
            $this->quizReplyAnswerMapper = $this->getServiceManager()->get('playgroundgame_quizreplyanswer_mapper');
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->getServiceManager...uizreplyanswer_mapper') can also be of type array. However, the property $quizReplyAnswerMapper is declared as type object<PlaygroundGame\Se...\QuizReplyAnswerMapper>. Maybe add an additional type check?

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

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

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

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
707
        }
708
709
        return $this->quizReplyAnswerMapper;
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->quizReplyAnswerMapper; of type object|array adds the type array to the return on line 709 which is incompatible with the return type documented by PlaygroundGame\Service\Q...etQuizReplyAnswerMapper of type PlaygroundGame\Service\QuizReplyAnswerMapper.
Loading history...
710
    }
711
712
     /**
713
     * setQuizReplyAnswerMapper
714
     *
715
     * @param  QuizReplyAnswerMapper $quizReplyAnswerMapper
716
     * @return Quiz
717
     */
718
    public function setQuizReplyAnswerMapper($quizReplyAnswerMapper)
719
    {
720
        $this->quizReplyAnswerMapper = $quizReplyAnswerMapper;
721
722
        return $this;
723
    }
724
}
725