Completed
Push — develop ( 8c855f...4c50ac )
by greg
03:25
created

QuizController::resultAction()   F

Complexity

Conditions 18
Paths 325

Size

Total Lines 136
Code Lines 97

Duplication

Lines 24
Ratio 17.65 %

Importance

Changes 6
Bugs 0 Features 0
Metric Value
c 6
b 0
f 0
dl 24
loc 136
rs 3.6714
cc 18
eloc 97
nc 325
nop 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
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
        // the quiz is done for the first time in this entry
20
        $firstTime = true;
21
        $redirectFb = $this->checkFbRegistration($this->user, $this->game);
22
        if ($redirectFb) {
23
            return $redirectFb;
24
        }
25
26
        $entry = $this->getGameService()->play($this->game, $this->user);
27 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...
28
            // the user has already taken part of this game and the participation limit has been reached
29
            $this->flashMessenger()->addMessage('Vous avez déjà participé!');
30
31
            return $this->redirect()->toUrl(
32
                $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...
33
                    $this->game->getClassType() . '/result',
34
                    array('id' => $this->game->getIdentifier())
35
                )
36
            );
37
        }
38
39
        $reply = $this->getGameService()->getQuizReplyMapper()->getLastGameReply($entry);
40
        $userAnswers = array();
41
        if ($reply) {
42
            $firstTime = false;
43
            foreach ($reply->getAnswers() as $answer) {
44
                $userAnswers[$answer->getQuestionId()][$answer->getAnswerId()] = true;
45
                $userAnswers[$answer->getQuestionId()]['answer'] = $answer->getAnswer();
46
            }
47
        }
48
49
        $questions = $this->game->getQuestions();
50
        $totalQuestions = count($questions);
51
52
        $form = new Form();
53
54
        $inputFilter = new \Zend\InputFilter\InputFilter();
55
        $factory = new InputFactory();
56
57
        $i = 0;
58
        $j = 0;
59
        $elementData = array();
60
        $explanations = array();
61
62
        foreach ($questions as $q) {
63
            if (($this->game->getQuestionGrouping() > 0 && $i % $this->game->getQuestionGrouping() === 0) ||
64
                ($i === 0 && $this->game->getQuestionGrouping() === 0)
65
            ) {
66
                $fieldsetName = 'questionGroup' . ++ $j;
67
                $fieldset = new Fieldset($fieldsetName);
68
            }
69
            $name = 'q' . $q->getId();
70
            $fieldsetFilter = new \Zend\InputFilter\InputFilter();
71
            if ($q->getType() === 0) {
72
                $element = new Element\Radio($name);
73
                $values = array();
74
                $valuesSortedByPosition = array();
75
                foreach ($q->getAnswers() as $a) {
76
                    $status = (
77
                        isset($userAnswers[$q->getId()]) &&
78
                        isset($userAnswers[$q->getId()][$a->getId()])
79
                    )? true:false;
80
                    $values[$a->getPosition()] = array(
81
                        'id' => $a->getId(),
82
                        'position' => $a->getPosition(),
83
                        'answer' => $a->getAnswer(),
84
                        'checked' => $status
85
                    );
86
                    $explanations[$a->getAnswer()] = $a->getExplanation();
87
                }
88
                ksort($values);
89
                foreach ($values as $key => $value) {
90
                    $valuesSortedByPosition[$value['id']] = $value['answer'];
91
                    if ($value['checked']) {
92
                        $element->setValue($value['id']);
93
                    }
94
                }
95
                $element->setValueOptions($valuesSortedByPosition);
96
                $element->setLabelOptions(array("disable_html_escape"=>true));
97
                $elementData[$q->getId()] = new Element\Hidden($name.'-data');
98
            } elseif ($q->getType() === 1) {
99
                $element = new Element\MultiCheckbox($name);
100
                $values = array();
101
                $valuesSortedByPosition = array();
102
                foreach ($q->getAnswers() as $a) {
103
                    $values[$a->getId()] = array(
104
                        'id' => $a->getId(),
105
                        'position' => $a->getPosition(),
106
                        'answer' => $a->getAnswer(),
107
                    );
108
                    $explanations[$a->getAnswer()] = $a->getExplanation();
109
                    $elementData[$a->getId()] = new Element\Hidden($name.'-'.$a->getId().'-data');
110
                }
111
112
                foreach ($values as $key => $value) {
113
                    $valuesSortedByPosition[$value['id']] = $value['answer'];
114
                }
115
116
                $element->setValueOptions($valuesSortedByPosition);
117
                $element->setLabelOptions(array("disable_html_escape"=>true));
118
            } elseif ($q->getType() == 2) {
119
                $element = new Element\Textarea($name);
120
                if (isset($userAnswers[$q->getId()])) {
121
                    $element->setValue($userAnswers[$q->getId()]['answer']);
122
                }
123
                $elementData[$q->getId()] = new Element\Hidden($name.'-data');
124
            }
125
126
            $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...
127
            $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...
128
            if (is_array($elementData)) {
129
                foreach ($elementData as $id => $e) {
130
                    $fieldset->add($e);
131
                }
132
            } else {
133
                $fieldset->add($elementData);
134
            }
135
136
            $fieldsetFilter->add($factory->createInput(array(
137
                'name'     => $name,
138
                'required' => true,
139
                'validators'=>array(
140
                    array(
141
                        'name'=>'NotEmpty',
142
                        'options'=>array(
143
                            'messages'=>array(
144
                                'isEmpty' => 'Merci de répondre à la question.',
145
                            ),
146
                        ),
147
                    ),
148
                )
149
            )));
150
151
            $i ++;
152
            if (($this->game->getQuestionGrouping() > 0 && $i % $this->game->getQuestionGrouping() == 0 && $i > 0) ||
153
                $i == $totalQuestions
154
            ) {
155
                $form->add($fieldset);
156
                $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...
157
            }
158
        }
159
160
        $form->setInputFilter($inputFilter);
161
162
        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...
163
            $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...
164
            $form->setData($data);
165
166
            // Improve it : I don't validate the form in a timer quiz as no answer is mandatory
167
            if ($this->game->getTimer() || $form->isValid()) {
168
                unset($data['submitForm']);
169
                $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...
170
            }
171
172
            return $this->redirect()->toUrl(
173
                $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...
174
                    $this->game->getClassType() . '/'. $this->game->nextStep($this->params('action')),
175
                    array('id' => $this->game->getIdentifier())
176
                )
177
            );
178
        }
179
180
        $viewModel = $this->buildView($this->game);
181
        $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...
182
            'firstTime' => $firstTime,
183
            'questions' => $questions,
184
            'form'      => $form,
185
            'explanations' => $explanations,
186
            'flashMessages' => $this->flashMessenger()->getMessages(),
187
        ));
188
189
        return $viewModel;
190
    }
191
192
    public function resultAction()
193
    {
194
        $statusMail = null;
195
        $prediction = false;
196
        $userTimer = array();
197
        $secretKey = strtoupper(substr(sha1(uniqid('pg_', true).'####'.time()), 0, 15));
198
        $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...
199
            'quiz',
200
            array('id' => $this->game->getIdentifier()),
201
            array('force_canonical' => true)
202
        ).'?key='.$secretKey;
203
204
        // With core shortener helper
205
        $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...
206
207
        $lastEntry = $this->getGameService()->findLastEntry($this->game, $this->user);
208 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...
209
            return $this->redirect()->toUrl(
210
                $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...
211
                    'quiz',
212
                    array('id' => $this->game->getIdentifier()),
213
                    array('force_canonical' => true)
214
                )
215
            );
216
        }
217
218
        // je compte les bonnes réponses et le ratio
219
        $maxCorrectAnswers = $this->game->getMaxCorrectAnswers();
220
        $winner = $lastEntry->getWinner();
221
        $reply = $this->getGameService()->getQuizReplyMapper()->getLastGameReply($lastEntry);
222
        $userCorrectAnswers = 0;
223
        $correctAnswers = array();
224
        $userAnswers = array();
225
        
226
        foreach ($reply->getAnswers() as $answer) {
227
            if ($answer->getCorrect()) {
228
                $correctAnswers[$answer->getQuestionId()][$answer->getAnswerId()] = true;
229
                ++$userCorrectAnswers;
230
            }
231
            $userAnswers[$answer->getQuestionId()][$answer->getAnswerId()] = true;
232
            $userAnswers[$answer->getQuestionId()]['answer'] = $answer->getAnswer();
233
        }
234
235
        $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...
236
        if ($maxCorrectAnswers > 0) {
237
            $ratioCorrectAnswers = ($userCorrectAnswers / $maxCorrectAnswers) * 100;
238
        } else {
239
            $ratioCorrectAnswers = 100;
240
        }
241
242
        if ($this->game->getTimer()) {
243
            $timer = $this->getGameService()->getEntryMapper()->findOneBy(
244
                array('game' => $this->game, 'user'=> $this->user)
245
            );
246
            $start = $timer->getCreatedAt()->format('U');
247
            $end = $timer->getUpdatedAt()->format('U');
248
            $userTimer = array(
249
               'ratio'  => $ratioCorrectAnswers,
250
               'timer'  => $end - $start,
251
            );
252
        }
253
254
        // Je prépare le tableau des bonnes réponses trouvées et non trouvées
255
        $ga = array();
256
        $questions = $this->game->getQuestions();
257
        foreach ($questions as $q) {
258
            foreach ($q->getAnswers() as $a) {
259
                if ($a->getCorrect()) {
260
                    $ga[$q->getId()]['question'] = $q;
261
                    $ga[$q->getId()]['answers'][$a->getId()]['answer'] = $a->getAnswer();
262
                    $ga[$q->getId()]['answers'][$a->getId()]['explanation'] = $a->getExplanation();
263
                    $ga[$q->getId()]['answers'][$a->getId()]['userAnswer'] = isset($userAnswers[$q->getId()]) ?
264
                        $userAnswers[$q->getId()]['answer'] :
265
                        false;
266
267 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...
268
                        $ga[$q->getId()]['answers'][$a->getId()]['found'] = true;
269
                    } else {
270
                        $ga[$q->getId()]['answers'][$a->getId()]['found'] = false;
271
                    }
272
                    
273 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...
274
                        $ga[$q->getId()]['answers'][$a->getId()]['yourChoice'] = true;
275
                    } else {
276
                        $ga[$q->getId()]['answers'][$a->getId()]['yourChoice'] = false;
277
                    }
278
279
                    $ga[$q->getId()]['answers'][$a->getId()]['correctAnswers'] = true;
280
                } else {
281
                    $ga[$q->getId()]['question'] = $q;
282
                    $ga[$q->getId()]['answers'][$a->getId()]['answer'] = $a->getAnswer();
283
                    $ga[$q->getId()]['answers'][$a->getId()]['explanation'] = $a->getExplanation();
284
                    $ga[$q->getId()]['answers'][$a->getId()]['correctAnswers'] = false;
285
                    $ga[$q->getId()]['answers'][$a->getId()]['userAnswer'] = isset($userAnswers[$q->getId()]) ?
286
                        $userAnswers[$q->getId()]['answer'] :
287
                        false;
288
                    
289 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...
290
                        $ga[$q->getId()]['answers'][$a->getId()]['yourChoice'] = true;
291
                    } else {
292
                        $ga[$q->getId()]['answers'][$a->getId()]['yourChoice'] = false;
293
                    }
294
                }
295
            }
296
            // if only one question is a prediction, we can't determine if it's a winner or looser
297
            if ($q->getPrediction()) {
298
                $prediction = true;
299
            }
300
        }
301
302
        $form = $this->getServiceLocator()->get('playgroundgame_sharemail_form');
303
        $form->setAttribute('method', 'post');
304
305
        $viewModel = $this->buildView($this->game);
306
        
307
        $this->getGameService()->sendMail($this->game, $this->user, $lastEntry);
308
309
        $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...
310
            'entry'               => $lastEntry,
311
            'statusMail'          => $statusMail,
312
            'form'                => $form,
313
            'winner'              => $winner,
314
            'prediction'          => $prediction,
315
            'userCorrectAnswers'  => $userCorrectAnswers,
316
            'maxCorrectAnswers'   => $maxCorrectAnswers,
317
            'ratioCorrectAnswers' => $ratioCorrectAnswers,
318
            'gameCorrectAnswers'  => $ga,
319
            'socialLinkUrl'       => $socialLinkUrl,
320
            'secretKey'           => $secretKey,
321
            'userTimer'           => $userTimer,
322
            'userAnswers'         => $userAnswers,
323
            'flashMessages'       => $this->flashMessenger()->getMessages(),
324
        ));
325
326
        return $viewModel;
327
    }
328
329 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...
330
    {
331
        $result = parent::fbshareAction();
332
        $bonusEntry = false;
333
334
        if ($result->getVariable('success')) {
335
            // Improve this thing
336
            $lastEntry = $this->getGameService()->findLastInactiveEntry($this->game, $this->user);
337
            if ($lastEntry && $lastEntry->getWinner()) {
338
                $bonusEntry = $this->getGameService()->addAnotherChance($this->game, $this->user, 1);
339
            }
340
        }
341
342
        $response = $this->getResponse();
343
        $response->setContent(\Zend\Json\Json::encode(array(
344
                'success' => $result,
345
                'playBonus' => $bonusEntry
346
        )));
347
348
        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...
349
    }
350
351 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...
352
    {
353
        $result = parent::fbrequestAction();
354
        $bonusEntry = false;
355
356
        if ($result->getVariable('success')) {
357
            $lastEntry = $this->getGameService()->findLastInactiveEntry($this->game, $this->user);
358
            if ($lastEntry && $lastEntry->getWinner()) {
359
                $bonusEntry = $this->getGameService()->addAnotherChance($this->game, $this->user, 1);
360
            }
361
        }
362
363
        $response = $this->getResponse();
364
        $response->setContent(\Zend\Json\Json::encode(array(
365
            'success' => $result,
366
            'playBonus' => $bonusEntry
367
        )));
368
369
        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...
370
    }
371
372 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...
373
    {
374
        $result = parent::tweetAction();
375
        $bonusEntry = false;
376
377
        if ($result->getVariable('success')) {
378
            $lastEntry = $this->getGameService()->findLastInactiveEntry($this->game, $this->user);
379
            if ($lastEntry && $lastEntry->getWinner()) {
380
                $bonusEntry = $this->getGameService()->addAnotherChance($this->game, $this->user, 1);
381
            }
382
        }
383
384
        $response = $this->getResponse();
385
        $response->setContent(\Zend\Json\Json::encode(array(
386
            'success' => $result,
387
            'playBonus' => $bonusEntry
388
        )));
389
390
        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...
391
    }
392
393 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...
394
    {
395
        $result = parent::googleAction();
396
        $bonusEntry = false;
397
398
        if ($result->getVariable('success')) {
399
            $lastEntry = $this->getGameService()->findLastInactiveEntry($this->game, $this->user);
400
            if ($lastEntry && $lastEntry->getWinner()) {
401
                $bonusEntry = $this->getGameService()->addAnotherChance($this->game, $this->user, 1);
402
            }
403
        }
404
405
        $response = $this->getResponse();
406
        $response->setContent(\Zend\Json\Json::encode(array(
407
            'success' => $result,
408
            'playBonus' => $bonusEntry
409
        )));
410
411
        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...
412
    }
413
414
    public function getGameService()
415
    {
416
        if (! $this->gameService) {
417
            $this->gameService = $this->getServiceLocator()->get('playgroundgame_quiz_service');
418
        }
419
420
        return $this->gameService;
421
    }
422
}
423