Completed
Push — develop ( 8cc9e7...453ab4 )
by greg
29:32
created

QuizController::fbrequestAction()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 20
Code Lines 12

Duplication

Lines 20
Ratio 100 %

Importance

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