Completed
Push — master ( f7296b...16f165 )
by greg
10:20 queued 06:56
created

QuizController   F

Complexity

Total Complexity 63

Size/Duplication

Total Lines 402
Duplicated Lines 28.86 %

Coupling/Cohesion

Components 1
Dependencies 15

Importance

Changes 10
Bugs 0 Features 0
Metric Value
wmc 63
c 10
b 0
f 0
lcom 1
cbo 15
dl 116
loc 402
rs 3.6585

7 Methods

Rating   Name   Duplication   Size   Complexity  
A fbshareAction() 21 21 4
A fbrequestAction() 20 20 4
A tweetAction() 20 20 4
A googleAction() 20 20 4
A getGameService() 0 8 2
F playAction() 11 162 27
F resultAction() 24 136 18

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 QuizController 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 QuizController, and based on these observations, apply Extract Interface, too.

1
<?php
2
namespace PlaygroundGame\Controller\Frontend;
3
4
use Zend\Form\Element;
5
use Zend\Form\Fieldset;
6
use Zend\Form\Form;
7
use Zend\InputFilter\Factory as InputFactory;
8
9
class QuizController extends GameController
10
{
11
    /**
12
     *
13
     * @var gameService
14
     */
15
    protected $gameService;
16
17
    public function playAction()
18
    {
19
        $redirectFb = $this->checkFbRegistration($this->user, $this->game);
20
        if ($redirectFb) {
21
            return $redirectFb;
22
        }
23
24
        $entry = $this->getGameService()->play($this->game, $this->user);
25 View Code Duplication
        if (!$entry) {
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...
26
            // the user has already taken part of this game and the participation limit has been reached
27
            $this->flashMessenger()->addMessage('Vous avez déjà participé!');
28
29
            return $this->redirect()->toUrl(
30
                $this->frontendUrl()->fromRoute(
0 ignored issues
show
Documentation Bug introduced by
The method frontendUrl does not exist on object<PlaygroundGame\Co...rontend\QuizController>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
31
                    $this->game->getClassType() . '/result',
32
                    array('id' => $this->game->getIdentifier())
33
                )
34
            );
35
        }
36
37
        $reply = $this->getGameService()->getQuizReplyMapper()->getLastGameReply($entry);
38
        $userAnswers = array();
39
        if($reply){
40
            foreach ($reply->getAnswers() as $answer) {
41
                $userAnswers[$answer->getQuestionId()][$answer->getAnswerId()] = true;
42
                $userAnswers[$answer->getQuestionId()]['answer'] = $answer->getAnswer();
43
            }
44
        }
45
46
        $questions = $this->game->getQuestions();
47
        $totalQuestions = count($questions);
48
49
        $form = new Form();
50
51
        $inputFilter = new \Zend\InputFilter\InputFilter();
52
        $factory = new InputFactory();
53
54
        $i = 0;
55
        $j = 0;
56
        $elementData = array();
57
        $explanations = array();
58
59
        foreach ($questions as $q) {
60
            if (
61
                ($this->game->getQuestionGrouping() > 0 && $i % $this->game->getQuestionGrouping() === 0) ||
62
                ($i === 0 && $this->game->getQuestionGrouping() === 0)
63
            ) {
64
                $fieldsetName = 'questionGroup' . ++ $j;
65
                $fieldset = new Fieldset($fieldsetName);
66
            }
67
            $name = 'q' . $q->getId();
68
            $fieldsetFilter = new \Zend\InputFilter\InputFilter();
69
            if ($q->getType() === 0) {
70
                $element = new Element\Radio($name);
71
                $values = array();
72
                $valuesSortedByPosition = array();
73
                foreach ($q->getAnswers() as $a) {
74
                    $values[$a->getPosition()] = array(
75
                        'id' => $a->getId(),
76
                        'position' => $a->getPosition(),
77
                        'answer' => $a->getAnswer(),
78
                        );
79
                    $explanations[$a->getAnswer()] = $a->getExplanation();
80
                }
81
                ksort($values);
82
                foreach ($values as $key => $value) {
83
                    $valuesSortedByPosition[$value['id']] = $value['answer'];
84
                }
85
                $element->setValueOptions($valuesSortedByPosition);
86
                $element->setLabelOptions(array("disable_html_escape"=>true));
87
                $elementData[$q->getId()] = new Element\Hidden($name.'-data');
88
            } elseif ($q->getType() === 1) {
89
                $element = new Element\MultiCheckbox($name);
90
                $values = array();
91
                $valuesSortedByPosition = array();
92
                foreach ($q->getAnswers() as $a) {
93
                    $values[$a->getId()] = array(
94
                        'id' => $a->getId(),
95
                        'position' => $a->getPosition(),
96
                        'answer' => $a->getAnswer(),
97
                    );
98
                    $explanations[$a->getAnswer()] = $a->getExplanation();
99
                    $elementData[$a->getId()] = new Element\Hidden($name.'-'.$a->getId().'-data');
100
                }
101
102
                foreach ($values as $key => $value) {
103
                    $valuesSortedByPosition[$value['id']] = $value['answer'];
104
                }
105
106
                $element->setValueOptions($valuesSortedByPosition);
107
                $element->setLabelOptions(array("disable_html_escape"=>true));
108
            } elseif ($q->getType() == 2) {
109
                $element = new Element\Textarea($name);
110
                if(isset($userAnswers[$q->getId()])) $element->setValue($userAnswers[$q->getId()]['answer']);
111
                $elementData[$q->getId()] = new Element\Hidden($name.'-data');
112
            }
113
114
            $element->setLabel($q->getQuestion());
0 ignored issues
show
Bug introduced by
The variable $element 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...
115
            $fieldset->add($element);
0 ignored issues
show
Bug introduced by
The variable $fieldset 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...
116
            if (is_array($elementData)) {
117
                foreach ($elementData as $id => $e) {
118
                    $fieldset->add($e);
119
                }
120
            } else {
121
                $fieldset->add($elementData);
122
            }
123
124
            $fieldsetFilter->add($factory->createInput(array(
125
                'name'     => $name,
126
                'required' => true,
127
                'validators'=>array(
128
                    array(
129
                        'name'=>'NotEmpty',
130
                        'options'=>array(
131
                            'messages'=>array(
132
                                'isEmpty' => 'Merci de répondre à la question.',
133
                            ),
134
                        ),
135
                    ),
136
                )
137
            )));
138
139
            $i ++;
140
            if (
141
                ($this->game->getQuestionGrouping() > 0 && $i % $this->game->getQuestionGrouping() == 0 && $i > 0) ||
142
                $i == $totalQuestions
143
            ) {
144
                $form->add($fieldset);
145
                $inputFilter->add($fieldsetFilter, $fieldsetName);
0 ignored issues
show
Bug introduced by
The variable $fieldsetName 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...
146
            }
147
        }
148
149
        $form->setInputFilter($inputFilter);
150
151
        if ($this->getRequest()->isPost()) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Zend\Stdlib\RequestInterface as the method isPost() does only exist in the following implementations of said interface: Zend\Http\PhpEnvironment\Request, Zend\Http\Request.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
152
            $data = $this->getRequest()->getPost()->toArray();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Zend\Stdlib\RequestInterface as the method getPost() does only exist in the following implementations of said interface: Zend\Http\PhpEnvironment\Request, Zend\Http\Request.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
153
            $form->setData($data);
154
155
            // Improve it : I don't validate the form in a timer quiz as no answer is mandatory
156
            if ($this->game->getTimer() || $form->isValid()) {
157
                unset($data['submitForm']);
158
                $entry = $this->getGameService()->createQuizReply($data, $this->game, $this->user);
0 ignored issues
show
Unused Code introduced by
$entry 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...
159
            }
160
161
            return $this->redirect()->toUrl(
162
                $this->frontendUrl()->fromRoute(
0 ignored issues
show
Documentation Bug introduced by
The method frontendUrl does not exist on object<PlaygroundGame\Co...rontend\QuizController>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
163
                    $this->game->getClassType() . '/'. $this->game->nextStep($this->params('action')),
164
                    array('id' => $this->game->getIdentifier())
165
                )
166
            );
167
        }
168
169
        $viewModel = $this->buildView($this->game);
170
        $viewModel->setVariables(array(
0 ignored issues
show
Bug introduced by
The method setVariables does only exist in Zend\View\Model\ViewModel, but not in Zend\Http\PhpEnvironment\Response.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
171
            'questions' => $questions,
172
            'form'      => $form,
173
            'explanations' => $explanations,
174
            'flashMessages' => $this->flashMessenger()->getMessages(),
175
        ));
176
177
        return $viewModel;
178
    }
179
180
    public function resultAction()
181
    {
182
        $statusMail = null;
183
        $prediction = false;
184
        $userTimer = array();
185
        $secretKey = strtoupper(substr(sha1(uniqid('pg_', true).'####'.time()), 0, 15));
186
        $socialLinkUrl = $this->frontendUrl()->fromRoute(
0 ignored issues
show
Documentation Bug introduced by
The method frontendUrl does not exist on object<PlaygroundGame\Co...rontend\QuizController>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
187
            'quiz',
188
            array('id' => $this->game->getIdentifier()),
189
            array('force_canonical' => true)
190
        ).'?key='.$secretKey;
191
192
        // With core shortener helper
193
        $socialLinkUrl = $this->shortenUrl()->shortenUrl($socialLinkUrl);
0 ignored issues
show
Documentation Bug introduced by
The method shortenUrl does not exist on object<PlaygroundGame\Co...rontend\QuizController>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
194
195
        $lastEntry = $this->getGameService()->findLastEntry($this->game, $this->user);
196 View Code Duplication
        if (!$lastEntry) {
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...
197
            return $this->redirect()->toUrl(
198
                $this->frontendUrl()->fromRoute(
0 ignored issues
show
Documentation Bug introduced by
The method frontendUrl does not exist on object<PlaygroundGame\Co...rontend\QuizController>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
199
                    'quiz',
200
                    array('id' => $this->game->getIdentifier()),
201
                    array('force_canonical' => true)
202
                )
203
            );
204
        }
205
206
        // je compte les bonnes réponses et le ratio
207
        $maxCorrectAnswers = $this->game->getMaxCorrectAnswers();
208
        $winner = $lastEntry->getWinner();
209
        $reply = $this->getGameService()->getQuizReplyMapper()->getLastGameReply($lastEntry);
210
        $userCorrectAnswers = 0;
211
        $correctAnswers = array();
212
        $userAnswers = array();
213
        
214
        foreach ($reply->getAnswers() as $answer) {
215
            if ($answer->getCorrect()) {
216
                $correctAnswers[$answer->getQuestionId()][$answer->getAnswerId()] = true;
217
                ++$userCorrectAnswers;
218
            }
219
            $userAnswers[$answer->getQuestionId()][$answer->getAnswerId()] = true;
220
            $userAnswers[$answer->getQuestionId()]['answer'] = $answer->getAnswer();
221
        }
222
223
        $ratioCorrectAnswers = 0;
0 ignored issues
show
Unused Code introduced by
$ratioCorrectAnswers 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...
224
        if ($maxCorrectAnswers > 0) {
225
            $ratioCorrectAnswers = ($userCorrectAnswers / $maxCorrectAnswers) * 100;
226
        } else {
227
            $ratioCorrectAnswers = 100;
228
        }
229
230
        if ($this->game->getTimer()) {
231
            $timer = $this->getGameService()->getEntryMapper()->findOneBy(
232
                array('game' => $this->game, 'user'=> $this->user)
233
            );
234
            $start = $timer->getCreatedAt()->format('U');
235
            $end = $timer->getUpdatedAt()->format('U');
236
            $userTimer = array(
237
               'ratio'  => $ratioCorrectAnswers,
238
               'timer'  => $end - $start,
239
            );
240
        }
241
242
        // Je prépare le tableau des bonnes réponses trouvées et non trouvées
243
        $ga = array();
244
        $questions = $this->game->getQuestions();
245
        foreach ($questions as $q) {
246
            foreach ($q->getAnswers() as $a) {
247
                if ($a->getCorrect()) {
248
                    $ga[$q->getId()]['question'] = $q;
249
                    $ga[$q->getId()]['answers'][$a->getId()]['answer'] = $a->getAnswer();
250
                    $ga[$q->getId()]['answers'][$a->getId()]['explanation'] = $a->getExplanation();
251
                    $ga[$q->getId()]['answers'][$a->getId()]['userAnswer'] = isset($userAnswers[$q->getId()]) ?
252
                        $userAnswers[$q->getId()]['answer'] :
253
                        false;
254
255 View Code Duplication
                    if (isset($correctAnswers[$q->getId()]) && isset($correctAnswers[$q->getId()][$a->getId()])) {
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...
256
                        $ga[$q->getId()]['answers'][$a->getId()]['found'] = true;
257
                    } else {
258
                        $ga[$q->getId()]['answers'][$a->getId()]['found'] = false;
259
                    }
260
                    
261 View Code Duplication
                    if (isset($userAnswers[$q->getId()]) && isset($userAnswers[$q->getId()][$a->getId()])) {
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...
262
                        $ga[$q->getId()]['answers'][$a->getId()]['yourChoice'] = true;
263
                    } else {
264
                        $ga[$q->getId()]['answers'][$a->getId()]['yourChoice'] = false;
265
                    }
266
267
                    $ga[$q->getId()]['answers'][$a->getId()]['correctAnswers'] = true;
268
                } else {
269
                    $ga[$q->getId()]['question'] = $q;
270
                    $ga[$q->getId()]['answers'][$a->getId()]['answer'] = $a->getAnswer();
271
                    $ga[$q->getId()]['answers'][$a->getId()]['explanation'] = $a->getExplanation();
272
                    $ga[$q->getId()]['answers'][$a->getId()]['correctAnswers'] = false;
273
                    $ga[$q->getId()]['answers'][$a->getId()]['userAnswer'] = isset($userAnswers[$q->getId()]) ?
274
                        $userAnswers[$q->getId()]['answer'] :
275
                        false;
276
                    
277 View Code Duplication
                    if (isset($userAnswers[$q->getId()]) && isset($userAnswers[$q->getId()][$a->getId()])) {
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...
278
                        $ga[$q->getId()]['answers'][$a->getId()]['yourChoice'] = true;
279
                    } else {
280
                        $ga[$q->getId()]['answers'][$a->getId()]['yourChoice'] = false;
281
                    }
282
                }
283
            }
284
            // if only one question is a prediction, we can't determine if it's a winner or looser
285
            if ($q->getPrediction()) {
286
                $prediction = true;
287
            }
288
        }
289
290
        $form = $this->getServiceLocator()->get('playgroundgame_sharemail_form');
291
        $form->setAttribute('method', 'post');
292
293
        $viewModel = $this->buildView($this->game);
294
        
295
        $this->getGameService()->sendMail($this->game, $this->user, $lastEntry);
296
297
        $viewModel->setVariables(array(
0 ignored issues
show
Bug introduced by
The method setVariables does only exist in Zend\View\Model\ViewModel, but not in Zend\Http\PhpEnvironment\Response.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
298
            'entry'               => $lastEntry,
299
            'statusMail'          => $statusMail,
300
            'form'                => $form,
301
            'winner'              => $winner,
302
            'prediction'          => $prediction,
303
            'userCorrectAnswers'  => $userCorrectAnswers,
304
            'maxCorrectAnswers'   => $maxCorrectAnswers,
305
            'ratioCorrectAnswers' => $ratioCorrectAnswers,
306
            'gameCorrectAnswers'  => $ga,
307
            'socialLinkUrl'       => $socialLinkUrl,
308
            'secretKey'           => $secretKey,
309
            'userTimer'           => $userTimer,
310
            'userAnswers'         => $userAnswers,
311
            'flashMessages'       => $this->flashMessenger()->getMessages(),
312
        ));
313
314
        return $viewModel;
315
    }
316
317 View Code Duplication
    public function fbshareAction()
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...
318
    {
319
        $result = parent::fbshareAction();
320
        $bonusEntry = false;
321
322
        if ($result->getVariable('success')) {
323
            // Improve this thing
324
            $lastEntry = $this->getGameService()->findLastInactiveEntry($this->game, $this->user);
325
            if ($lastEntry && $lastEntry->getWinner()) {
326
                $bonusEntry = $this->getGameService()->addAnotherChance($this->game, $this->user, 1);
327
            }
328
        }
329
330
        $response = $this->getResponse();
331
        $response->setContent(\Zend\Json\Json::encode(array(
332
                'success' => $result,
333
                'playBonus' => $bonusEntry
334
        )));
335
336
        return $response;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $response; (Zend\Stdlib\ResponseInterface) is incompatible with the return type of the parent method PlaygroundGame\Controlle...ntroller::fbshareAction of type Zend\View\Model\JsonModel.

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...
337
    }
338
339 View Code Duplication
    public function fbrequestAction()
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...
340
    {
341
        $result = parent::fbrequestAction();
342
        $bonusEntry = false;
343
344
        if ($result->getVariable('success')) {
345
            $lastEntry = $this->getGameService()->findLastInactiveEntry($this->game, $this->user);
346
            if ($lastEntry && $lastEntry->getWinner()) {
347
                $bonusEntry = $this->getGameService()->addAnotherChance($this->game, $this->user, 1);
348
            }
349
        }
350
351
        $response = $this->getResponse();
352
        $response->setContent(\Zend\Json\Json::encode(array(
353
            'success' => $result,
354
            'playBonus' => $bonusEntry
355
        )));
356
357
        return $response;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $response; (Zend\Stdlib\ResponseInterface) is incompatible with the return type of the parent method PlaygroundGame\Controlle...roller::fbrequestAction of type Zend\View\Model\JsonModel.

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...
358
    }
359
360 View Code Duplication
    public function tweetAction()
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...
361
    {
362
        $result = parent::tweetAction();
363
        $bonusEntry = false;
364
365
        if ($result->getVariable('success')) {
366
            $lastEntry = $this->getGameService()->findLastInactiveEntry($this->game, $this->user);
367
            if ($lastEntry && $lastEntry->getWinner()) {
368
                $bonusEntry = $this->getGameService()->addAnotherChance($this->game, $this->user, 1);
369
            }
370
        }
371
372
        $response = $this->getResponse();
373
        $response->setContent(\Zend\Json\Json::encode(array(
374
            'success' => $result,
375
            'playBonus' => $bonusEntry
376
        )));
377
378
        return $response;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $response; (Zend\Stdlib\ResponseInterface) is incompatible with the return type of the parent method PlaygroundGame\Controlle...Controller::tweetAction of type Zend\View\Model\JsonModel.

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...
379
    }
380
381 View Code Duplication
    public function googleAction()
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...
382
    {
383
        $result = parent::googleAction();
384
        $bonusEntry = false;
385
386
        if ($result->getVariable('success')) {
387
            $lastEntry = $this->getGameService()->findLastInactiveEntry($this->game, $this->user);
388
            if ($lastEntry && $lastEntry->getWinner()) {
389
                $bonusEntry = $this->getGameService()->addAnotherChance($this->game, $this->user, 1);
390
            }
391
        }
392
393
        $response = $this->getResponse();
394
        $response->setContent(\Zend\Json\Json::encode(array(
395
            'success' => $result,
396
            'playBonus' => $bonusEntry
397
        )));
398
399
        return $response;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $response; (Zend\Stdlib\ResponseInterface) is incompatible with the return type of the parent method PlaygroundGame\Controlle...ontroller::googleAction of type Zend\View\Model\JsonModel.

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...
400
    }
401
402
    public function getGameService()
403
    {
404
        if (! $this->gameService) {
405
            $this->gameService = $this->getServiceLocator()->get('playgroundgame_quiz_service');
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->getServiceLocator...oundgame_quiz_service') can also be of type array. However, the property $gameService is declared as type object<PlaygroundGame\Co...r\Frontend\gameService>. 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...
406
        }
407
408
        return $this->gameService;
409
    }
410
}
411