Completed
Pull Request — master (#341)
by greg
02:39
created

QuizController::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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