Completed
Branch develop (ee4741)
by greg
03:30
created

PostVoteController   D

Complexity

Total Complexity 89

Size/Duplication

Total Lines 899
Duplicated Lines 5.78 %

Coupling/Cohesion

Components 1
Dependencies 11

Importance

Changes 22
Bugs 5 Features 1
Metric Value
wmc 89
c 22
b 5
f 1
lcom 1
cbo 11
dl 52
loc 899
rs 4

11 Methods

Rating   Name   Duplication   Size   Complexity  
D playAction() 16 167 19
B previewAction() 0 65 7
C postAction() 0 121 12
C resultAction() 14 91 11
B ajaxuploadAction() 0 51 5
B ajaxdeleteAction() 0 38 4
D listAction() 4 122 9
B ajaxVoteAction() 0 43 5
B captchaAction() 0 24 4
A getGameService() 0 8 2
C shareAction() 18 123 11

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like PostVoteController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use PostVoteController, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace PlaygroundGame\Controller\Frontend;
4
5
use Zend\Form\Form;
6
7
class PostVoteController extends GameController
8
{
9
    /**
10
     * @var gameService
11
     */
12
    protected $gameService;
13
14
    /**
15
     * --DONE-- 1. try to change the Game Id (on le redirige vers la home du jeu)
16
     * --DONE-- 2. try to modify questions (the form is recreated and verified in the controller)
17
     * --DONE-- 3. don't answer to questions (form is checked controller side)
18
     * 4. try to game the chrono
19
     * 5. try to play again
20
     * 6. try to change answers
21
     *  --DONE-- 7. essaie de répondre sans être inscrit (on le redirige vers la home du jeu)
22
     */
23
    public function playAction()
24
    {
25
        $sg         = $this->getGameService();
26
27
        $identifier = $this->getEvent()->getRouteMatch()->getParam('id');
28
        $channel = $this->getEvent()->getRouteMatch()->getParam('channel');
29
30
        $game = $sg->checkGame($identifier);
31
        if (! $game || $game->isClosed()) {
32
            return $this->notFoundAction();
33
        }
34
35
        $redirectFb = $this->checkFbRegistration($this->zfcUserAuthentication()->getIdentity(), $game, $channel);
0 ignored issues
show
Documentation Bug introduced by
The method zfcUserAuthentication does not exist on object<PlaygroundGame\Co...end\PostVoteController>? 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...
36
        if ($redirectFb) {
37
            return $redirectFb;
38
        }
39
40
        $user       = $this->zfcUserAuthentication()->getIdentity();
0 ignored issues
show
Documentation Bug introduced by
The method zfcUserAuthentication does not exist on object<PlaygroundGame\Co...end\PostVoteController>? 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...
41
42 View Code Duplication
        if (!$user && !$game->getAnonymousAllowed()) {
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...
43
            $redirect = urlencode(
44
                $this->frontendUrl()->fromRoute(
0 ignored issues
show
Documentation Bug introduced by
The method frontendUrl does not exist on object<PlaygroundGame\Co...end\PostVoteController>? 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...
45
                    $game->getClassType() . '/play',
46
                    array('id' => $game->getIdentifier(), 'channel' => $channel),
47
                    array('force_canonical' => true)
48
                )
49
            );
50
51
            return $this->redirect()->toUrl(
52
                $this->frontendUrl()->fromRoute(
0 ignored issues
show
Documentation Bug introduced by
The method frontendUrl does not exist on object<PlaygroundGame\Co...end\PostVoteController>? 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...
53
                    'zfcuser/register',
54
                    array('channel' => $channel)
55
                ) . '?redirect='.$redirect
56
            );
57
        }
58
59
        $entry = $sg->play($game, $user);
60
61
        if (!$entry) {
62
            $lastEntry = $sg->findLastInactiveEntry($game, $user);
63
            if ($lastEntry === null) {
64
                return $this->redirect()->toUrl(
65
                    $this->frontendUrl()->fromRoute(
0 ignored issues
show
Documentation Bug introduced by
The method frontendUrl does not exist on object<PlaygroundGame\Co...end\PostVoteController>? 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...
66
                        'postvote',
67
                        array(
68
                            'id' => $identifier,
69
                            'channel' => $this->getEvent()->getRouteMatch()->getParam('channel')
70
                        )
71
                    )
72
                );
73
            }
74
75
            $lastEntryId = $lastEntry->getId();
76
            $lastPost = $sg->getPostVotePostMapper()->findOneBy(array('entry' => $lastEntryId));
77
            $postId = $lastPost->getId();
78
            if ($lastPost->getStatus() == 2) {
79
                // the user has already taken part of this game and the participation limit has been reached
80
                $this->flashMessenger()->addMessage(
81
                    $this->getServiceLocator()->get('translator')->translate('You have already a Post')
82
                );
83
84
                return $this->redirect()->toUrl(
85
                    $this->frontendUrl()->fromRoute(
0 ignored issues
show
Documentation Bug introduced by
The method frontendUrl does not exist on object<PlaygroundGame\Co...end\PostVoteController>? 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...
86
                        'postvote/post',
87
                        array(
88
                            'id' => $identifier,
89
                            'post' => $postId,
90
                            'channel' => $this->getEvent()->getRouteMatch()->getParam('channel')
91
                        )
92
                    )
93
                );
94
            } else {
95
                $this->flashMessenger()->addMessage(
96
                    $this->getServiceLocator()->get('translator')->translate('Your Post is waiting for validation')
97
                );
98
99
                return $this->redirect()->toUrl(
100
                    $this->frontendUrl()->fromRoute(
0 ignored issues
show
Documentation Bug introduced by
The method frontendUrl does not exist on object<PlaygroundGame\Co...end\PostVoteController>? 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...
101
                        'postvote/post',
102
                        array(
103
                            'id' => $identifier,
104
                            'post' => $postId,
105
                            'channel' => $this->getEvent()->getRouteMatch()->getParam('channel')
106
                        )
107
                    )
108
                );
109
            }
110
        }
111
112
        if (! $game->getForm()) {
113
            return $this->redirect()->toUrl(
114
                $this->frontendUrl()->fromRoute(
0 ignored issues
show
Documentation Bug introduced by
The method frontendUrl does not exist on object<PlaygroundGame\Co...end\PostVoteController>? 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...
115
                    'postvote',
116
                    array(
117
                        'id' => $identifier,
118
                        'channel' => $this->getEvent()->getRouteMatch()->getParam('channel')
119
                    )
120
                )
121
            );
122
        }
123
124
        $form = $sg->createFormFromJson($game->getForm()->getForm(), 'postvoteForm');
125
126
        // Je recherche le post associé à entry + status == 0. Si non trouvé, je redirige vers home du jeu.
127
        $post = $sg->getPostVotePostMapper()->findOneBy(array('entry' => $entry, 'status' => 0));
128
        if ($post) {
129
            foreach ($post->getPostElements() as $element) {
130
                try {
131
                    $form->get($element->getName())->setValue($element->getValue());
132
133
                    $elementType = $form->get($element->getName())->getAttribute('type');
134
                    if ($elementType == 'file' && $element->getValue() != '') {
135
                        $filter = $form->getInputFilter();
136
                        $elementInput = $filter->get($element->getName());
137
                        $elementInput->setRequired(false);
138
                        $form->get($element->getName())->setAttribute('required', false);
139
                    }
140
                } catch (\Zend\Form\Exception\InvalidElementException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
141
                }
142
            }
143
        }
144
145
        $viewModel = $this->buildView($game);
146
147
        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...
148
            // POST Request: Process form
149
            $data = array_merge_recursive(
150
                $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...
151
                $this->getRequest()->getFiles()->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 getFiles() does only exist in the following implementations of said interface: Zend\Http\PhpEnvironment\Request, Zend\Http\Request.

Let’s take a look at an example:

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

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

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

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

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

Available Fixes

  1. Change the type-hint for the parameter:

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

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

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
152
            );
153
154
            $form->setData($data);
155
156
            if ($form->isValid()) {
157
                $data = $form->getData();
158
                $post = $this->getGameService()->createPost($data, $game, $user, $form);
159
160
                if ($post && !empty($game->nextStep('play'))) {
161
                    // determine the route where the user should go
162
                    $redirectUrl = $this->frontendUrl()->fromRoute(
0 ignored issues
show
Documentation Bug introduced by
The method frontendUrl does not exist on object<PlaygroundGame\Co...end\PostVoteController>? Since you implemented __call, maybe consider adding a @method annotation.

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

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

class ParentClass {
    private $data = array();

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

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

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
163
                        'postvote/'.$game->nextStep('play'),
164
                        array(
165
                            'id' => $game->getIdentifier(),
166
                            'channel' => $this->getEvent()->getRouteMatch()->getParam('channel')
167
                        )
168
                    );
169
170
                    return $this->redirect()->toUrl($redirectUrl);
171
                }
172
            } else {
173
                $messages = $form->getMessages();
174
                $viewModel = $this->buildView($game);
175
                $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...
176
                    'success' => false,
177
                    'message' => implode(',', $messages['title']),
178
                ));
179
            }
180
        }
181
182
        $viewModel->setVariables(array(
183
                'playerData' => $entry->getPlayerData(),
184
                'form' => $form,
185
                'post' => $post,
186
            ));
187
188
        return $viewModel;
189
    }
190
191
    public function previewAction()
192
    {
193
        $identifier = $this->getEvent()->getRouteMatch()->getParam('id');
194
        $user = $this->zfcUserAuthentication()->getIdentity();
0 ignored issues
show
Documentation Bug introduced by
The method zfcUserAuthentication does not exist on object<PlaygroundGame\Co...end\PostVoteController>? 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...
195
        $sg = $this->getGameService();
196
197
        $game = $sg->checkGame($identifier);
198
        if (! $game) {
199
            return $this->notFoundAction();
200
        }
201
202
        $entry = $sg->findLastActiveEntry($game, $user);
203
         
204
        if (!$entry) {
205
            // the user has already taken part of this game and the participation limit has been reached
206
            return $this->redirect()->toUrl(
207
                $this->frontendUrl()->fromRoute(
0 ignored issues
show
Documentation Bug introduced by
The method frontendUrl does not exist on object<PlaygroundGame\Co...end\PostVoteController>? 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...
208
                    'postvote/'.$game->nextStep('preview'),
209
                    array(
210
                        'id' => $identifier,
211
                        'channel' => $this->getEvent()->getRouteMatch()->getParam('channel')
212
                    )
213
                )
214
            );
215
        }
216
217
        // Je recherche le post associé à entry + status == 0. Si non trouvé, je redirige vers home du jeu.
218
        $post = $sg->getPostVotePostMapper()->findOneBy(array('entry' => $entry, 'status' => 0));
219
220
        if (! $post) {
221
            return $this->redirect()->toUrl(
222
                $this->frontendUrl()->fromRoute(
0 ignored issues
show
Documentation Bug introduced by
The method frontendUrl does not exist on object<PlaygroundGame\Co...end\PostVoteController>? 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...
223
                    'postvote',
224
                    array(
225
                        'id' => $identifier,
226
                        'channel' => $this->getEvent()->getRouteMatch()->getParam('channel')
227
                    )
228
                )
229
            );
230
        }
231
232
        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...
233
            $post = $this->getGameService()->confirmPost($game, $user);
234
235
            if ($post) {
236
                if (!($step = $game->nextStep('play'))) {
237
                    $step = 'result';
238
                }
239
                $redirectUrl = $this->frontendUrl()->fromRoute(
0 ignored issues
show
Documentation Bug introduced by
The method frontendUrl does not exist on object<PlaygroundGame\Co...end\PostVoteController>? 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...
240
                    'postvote/'.$step,
241
                    array(
242
                        'id' => $game->getIdentifier(),
243
                        'channel' => $this->getEvent()->getRouteMatch()->getParam('channel')
244
                    )
245
                );
246
247
                return $this->redirect()->toUrl($redirectUrl);
248
            }
249
        }
250
251
        $viewModel = $this->buildView($game);
252
        $viewModel->setVariables(array('post' => $post));
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...
253
254
        return $viewModel;
255
    }
256
257
    /**
258
     * View the Post page
259
     * @return multitype:|\Zend\Http\Response|\Zend\View\Model\ViewModel
0 ignored issues
show
Documentation introduced by
The doc-type multitype:|\Zend\Http\Re...nd\View\Model\ViewModel could not be parsed: Unknown type name "multitype:" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
260
     */
261
    public function postAction()
262
    {
263
        $identifier = $this->getEvent()->getRouteMatch()->getParam('id');
264
        $postId = $this->getEvent()->getRouteMatch()->getParam('post');
265
        $user = $this->zfcUserAuthentication()->getIdentity();
0 ignored issues
show
Documentation Bug introduced by
The method zfcUserAuthentication does not exist on object<PlaygroundGame\Co...end\PostVoteController>? 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...
266
        $sg = $this->getGameService();
267
        $voted = false;
268
269
        $statusMail = false;
270
        $mailService = $this->getServiceLocator()->get('playgroundgame_message');
271
        $to = '';
272
        $skinUrl = $sg->getServiceManager()->get('ViewRenderer')->url(
273
            'frontend',
274
            array(
275
                'channel' => $this->getEvent()->getRouteMatch()->getParam('channel')
276
            ),
277
            array('force_canonical' => true)
278
        );
279
        $config = $this->getGameService()->getServiceManager()->get('config');
280
        if (isset($config['moderation']['email'])) {
281
            $to = $config['moderation']['email'];
282
        }
283
284
        $game = $sg->checkGame($identifier, false);
285
286
        if (! $postId) {
287
            return $this->notFoundAction();
288
        }
289
290
        // Je recherche le post associé à entry + status == 0. Si non trouvé, je redirige vers home du jeu.
291
        $post = $sg->getPostVotePostMapper()->findById($postId);
292
293
        if (! $post || $post->getStatus() === 9) {
294
            return $this->redirect()->toUrl(
295
                $this->frontendUrl()->fromRoute(
0 ignored issues
show
Documentation Bug introduced by
The method frontendUrl does not exist on object<PlaygroundGame\Co...end\PostVoteController>? 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...
296
                    'postvote',
297
                    array(
298
                        'id' => $identifier,
299
                        'channel' => $this->getEvent()->getRouteMatch()->getParam('channel')
300
                    )
301
                )
302
            );
303
        }
304
305
        $formModeration = new Form();
306
        $formModeration->setAttribute('method', 'post');
307
308
        $formModeration->add(array(
309
            'name' => 'moderation',
310
            'attributes' => array(
311
                'type' => 'hidden',
312
                'value' => '1'
313
            ),
314
        ));
315
316
        $form = new \PlaygroundGame\Form\Frontend\PostVoteVote(
317
            $this->frontendUrl()->fromRoute(
0 ignored issues
show
Documentation Bug introduced by
The method frontendUrl does not exist on object<PlaygroundGame\Co...end\PostVoteController>? 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...
318
                'postvote/post/captcha',
319
                array(
320
                    'id' => $identifier,
321
                    'post' => $postId,
322
                    'channel' => $this->getEvent()->getRouteMatch()->getParam('channel')
323
                )
324
            )
325
        );
326
327
        if ($user) {
328
            $form->remove('captcha');
329
        }
330
331
        $alreadyVoted = '';
332
        $reportId = '';
333
334
        $request = $this->getRequest();
335
        if ($request->isPost()) {
336
            $data = $request->getPost()->toArray();
337
            if (isset($data['moderation'])) {
338
                $formModeration->setData($data);
339
                if ($formModeration->isValid()) {
340
                    $from = $to;
341
                    $subject= 'Moderation Post and Vote';
342
                    $result = $mailService->createHtmlMessage(
343
                        $from,
344
                        $to,
345
                        $subject,
346
                        'playground-game/email/moderation',
347
                        array('data' => $data, 'skinUrl' => $skinUrl)
348
                    );
349
                    $mailService->send($result);
350
                    if ($result) {
351
                        $statusMail = true;
352
                        $reportId = $data['reportid'];
353
                    }
354
                }
355
            } else {
356
                $form->setData($request->getPost());
357
                if ($form->isValid()) {
358
                    if ($sg->addVote($user, $this->getRequest()->getServer('REMOTE_ADDR'), $post)) {
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 getServer() does only exist in the following implementations of said interface: Zend\Http\PhpEnvironment\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...
359
                        $voted = true;
360
                    } else {
361
                        $alreadyVoted = 'Vous avez déjà voté!';
362
                    }
363
                }
364
            }
365
        }
366
367
        $viewModel = $this->buildView($game);
368
        $viewModel->setVariables(
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...
369
            array(
370
                'post'  => $post,
371
                'voted' => $voted,
372
                'form'  => $form,
373
                'formModeration' => $formModeration,
374
                'statusMail' => $statusMail,
375
                'alreadyVoted' => $alreadyVoted,
376
                'reportId' => $reportId,
377
            )
378
        );
379
380
        return $viewModel;
381
    }
382
383
    /**
384
     *
385
     */
386
    public function resultAction()
387
    {
388
        $identifier = $this->getEvent()->getRouteMatch()->getParam('id');
389
        $user = $this->zfcUserAuthentication()->getIdentity();
0 ignored issues
show
Documentation Bug introduced by
The method zfcUserAuthentication does not exist on object<PlaygroundGame\Co...end\PostVoteController>? 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...
390
        $channel = $this->getEvent()->getRouteMatch()->getParam('channel');
391
392
        $statusMail = null;
393
394
        if (!$identifier) {
395
            return $this->notFoundAction();
396
        }
397
398
        $postVoteMapper = $this->getGameService()->getPostVoteMapper();
399
        $game = $postVoteMapper->findByIdentifier($identifier);
400
401
        if (!$game || $game->isClosed()) {
402
            return $this->notFoundAction();
403
        }
404
405
        // Has the user finished the game ?
406
        $lastEntry = $this->getGameService()->findLastInactiveEntry($game, $user);
407
408
        if ($lastEntry === null) {
409
            return $this->redirect()->toUrl(
410
                $this->frontendUrl()->fromRoute(
0 ignored issues
show
Documentation Bug introduced by
The method frontendUrl does not exist on object<PlaygroundGame\Co...end\PostVoteController>? 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...
411
                    'postvote',
412
                    array(
413
                        'id' => $identifier,
414
                        'channel' => $this->getEvent()->getRouteMatch()->getParam('channel')
415
                    )
416
                )
417
            );
418
        }
419
420 View Code Duplication
        if (!$user && !$game->getAnonymousAllowed()) {
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...
421
            $redirect = urlencode(
422
                $this->frontendUrl()->fromRoute(
0 ignored issues
show
Documentation Bug introduced by
The method frontendUrl does not exist on object<PlaygroundGame\Co...end\PostVoteController>? 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...
423
                    'postvote/result',
424
                    array(
425
                        'id' => $game->getIdentifier(),
426
                        'channel' => $channel
427
                    )
428
                )
429
            );
430
            return $this->redirect()->toUrl(
431
                $this->frontendUrl()->fromRoute(
0 ignored issues
show
Documentation Bug introduced by
The method frontendUrl does not exist on object<PlaygroundGame\Co...end\PostVoteController>? 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...
432
                    'zfcuser/register',
433
                    array('channel' => $channel)
434
                ) . '?redirect='.$redirect
435
            );
436
        }
437
438
        $form = $this->getServiceLocator()->get('playgroundgame_sharemail_form');
439
        $form->setAttribute('method', 'post');
440
441 View Code Duplication
        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...
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...
442
            $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...
443
            $form->setData($data);
444
            if ($form->isValid()) {
445
                $result = $this->getGameService()->sendShareMail($data, $game, $user, $lastEntry);
446
                if ($result) {
447
                    $statusMail = true;
448
                }
449
            }
450
        }
451
452
        // Je recherche le post associé à entry + status == 0. Si non trouvé, je redirige vers home du jeu.
453
        $post = $this->getGameService()->getPostVotePostMapper()->findOneBy(array('entry' => $lastEntry));
454
455
        if (! $post) {
456
            return $this->redirect()->toUrl(
457
                $this->frontendUrl()->fromRoute(
0 ignored issues
show
Documentation Bug introduced by
The method frontendUrl does not exist on object<PlaygroundGame\Co...end\PostVoteController>? 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...
458
                    'postvote',
459
                    array(
460
                        'id' => $identifier,
461
                        'channel' => $this->getEvent()->getRouteMatch()->getParam('channel')
462
                    )
463
                )
464
            );
465
        }
466
467
        $viewModel = $this->buildView($game);
468
469
        $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...
470
                'statusMail' => $statusMail,
471
                'post' => $post,
472
                'form' => $form,
473
            ));
474
475
        return $viewModel;
476
    }
477
478
    /**
479
     * Example of AJAX File Upload with Session Progress and partial validation.
480
     * It's now possible to send a base64 image in this case the call is the form :
481
     * this._ajax(
482
     * {
483
     *   url: url.dataset.url,
484
     *    method: 'post',
485
     *    body: 'photo=' + image
486
     * },
487
     *
488
     * @return \Zend\Stdlib\ResponseInterface
489
     */
490
    public function ajaxuploadAction()
491
    {
492
        // Call this for the session lock to be released (other ajax calls can then be made)
493
        session_write_close();
494
495
        $identifier = $this->getEvent()->getRouteMatch()->getParam('id');
496
        $user = $this->zfcUserAuthentication()->getIdentity();
0 ignored issues
show
Documentation Bug introduced by
The method zfcUserAuthentication does not exist on object<PlaygroundGame\Co...end\PostVoteController>? 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...
497
        $sg = $this->getGameService();
498
        $request = $this->getRequest();
499
        $response = $this->getResponse();
500
501
        $game = $sg->checkGame($identifier);
502
        if (! $game) {
503
            $response->setContent(\Zend\Json\Json::encode(array(
504
                'success' => 0
505
            )));
506
507
            return $response;
508
        }
509
510
        $entry = $sg->findLastActiveEntry($game, $user);
511
        if (!$entry) {
512
            // the user has already taken part of this game and the participation limit has been reached
513
            $response->setContent(\Zend\Json\Json::encode(array(
514
                'success' => 0
515
            )));
516
517
            return $response;
518
        }
519
520
        if ($request->isPost()) {
521
            $data = $this->getRequest()->getFiles()->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 getFiles() 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...
522
523
            if (empty($data)) {
524
                $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...
525
526
                $key = key($data);
527
528
                $uploadImage = array('name' => $key.'.png', 'error' => 0, 'base64' => $data[$key]);
529
                $data = array($key => $uploadImage);
530
            }
531
            $uploadFile = $sg->uploadFileToPost($data, $game, $user);
532
        }
533
534
        $response->setContent(\Zend\Json\Json::encode(array(
535
                'success' => true,
536
                'fileUrl' => $uploadFile
0 ignored issues
show
Bug introduced by
The variable $uploadFile 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...
537
            )));
538
539
        return $response;
540
    }
541
542
    public function ajaxdeleteAction()
543
    {
544
        $identifier = $this->getEvent()->getRouteMatch()->getParam('id');
545
        $user = $this->zfcUserAuthentication()->getIdentity();
0 ignored issues
show
Documentation Bug introduced by
The method zfcUserAuthentication does not exist on object<PlaygroundGame\Co...end\PostVoteController>? 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...
546
        $sg = $this->getGameService();
547
        $request = $this->getRequest();
548
        $response = $this->getResponse();
549
550
        $game = $sg->checkGame($identifier);
551
        if (! $game) {
552
            $response->setContent(\Zend\Json\Json::encode(array(
553
                'success' => 0
554
            )));
555
556
            return $response;
557
        }
558
559
        $entry = $sg->findLastActiveEntry($game, $user);
560
        if (!$entry) {
561
            // the user has already taken part of this game and the participation limit has been reached
562
            $response->setContent(\Zend\Json\Json::encode(array(
563
                'success' => 0
564
            )));
565
566
            return $response;
567
        }
568
569
        if ($request->isPost()) {
570
            $data = $request->getPost()->toArray();
571
            $sg->deleteFilePosted($data, $game, $user);
572
        }
573
574
        $response->setContent(\Zend\Json\Json::encode(array(
575
                'success' => true,
576
            )));
577
578
        return $response;
579
    }
580
581
    public function listAction()
582
    {
583
        $identifier = $this->getEvent()->getRouteMatch()->getParam('id');
584
        $filter        = $this->getEvent()->getRouteMatch()->getParam('filter');
585
        $search    = $this->params()->fromQuery('name');
586
        $sg        = $this->getGameService();
587
        $postId     = $this->params()->fromQuery('id');
588
589
        $statusMail = false;
590
        $mailService = $this->getServiceLocator()->get('playgroundgame_message');
591
        $to = '';
592
        $skinUrl = $sg->getServiceManager()->get('ViewRenderer')->url(
593
            'frontend',
594
            array('channel' => $this->getEvent()->getRouteMatch()->getParam('channel')),
595
            array('force_canonical' => true)
596
        );
597
        $config = $this->getGameService()->getServiceManager()->get('config');
598
        if (isset($config['moderation']['email'])) {
599
            $to = $config['moderation']['email'];
600
        }
601
602
        $request = $this->getRequest();
603
604
        $game = $sg->checkGame($identifier, false);
605
606
        // Je recherche les posts validés associés à ce jeu
607
        $posts = $sg->findArrayOfValidatedPosts($game, $filter, $search);
608
609
        if (is_array($posts)) {
610
            $paginator = new \Zend\Paginator\Paginator(new \Zend\Paginator\Adapter\ArrayAdapter($posts));
611
            $paginator->setItemCountPerPage($game->getPostDisplayNumber());
612
            $paginator->setCurrentPageNumber($this->getEvent()->getRouteMatch()->getParam('p'));
613
        } else {
614
            $paginator = $posts;
615
        }
616
617
        $form = new Form();
618
        $form->setAttribute('method', 'post');
619
620
        $form->add(array(
621
            'name' => 'moderation',
622
            'attributes' => array(
623
                'type' => 'hidden',
624
                'value' => '1'
625
            ),
626
        ));
627
628
        $reportId ='';
629
630
        if ($request->isPost()) {
631
            $data = $request->getPost()->toArray();
632
633
            if (isset($data['moderation'])) {
634
                $from = $to;
635
                $subject= 'Moderation Post and Vote';
636
                $result = $mailService->createHtmlMessage(
637
                    $from,
638
                    $to,
639
                    $subject,
640
                    'playground-game/email/moderation',
641
                    array('data' => $data, 'skinUrl' => $skinUrl)
642
                );
643
                $mailService->send($result);
644
                if ($result) {
645
                    $statusMail = true;
646
                    $reportId = $data['reportid'];
647
                }
648
            }
649
        }
650
651
        $viewModel = $this->buildView($game);
652
        
653
        if ($postId) {
654
            $postTarget = $sg->getPostVotePostMapper()->findById($postId);
655
            if ($postTarget) {
656 View Code Duplication
                foreach ($postTarget->getPostElements() as $element) {
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...
657
                    $fbShareImage = $this->frontendUrl()->fromRoute(
0 ignored issues
show
Documentation Bug introduced by
The method frontendUrl does not exist on object<PlaygroundGame\Co...end\PostVoteController>? 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...
658
                        '',
659
                        array('channel' => ''),
660
                        array('force_canonical' => true),
661
                        false
662
                    ) . $element->getValue();
663
                    break;
664
                }
665
                
666
                $secretKey = strtoupper(substr(sha1(uniqid('pg_', true).'####'.time()), 0, 15));
667
                
668
                // Without bit.ly shortener
669
                $socialLinkUrl = $this->frontendUrl()->fromRoute(
0 ignored issues
show
Documentation Bug introduced by
The method frontendUrl does not exist on object<PlaygroundGame\Co...end\PostVoteController>? 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...
670
                    'postvote/list',
671
                    array(
672
                        'id' => $game->getIdentifier(),
673
                        'filter' => 'date',
674
                        'channel' => $this->getEvent()->getRouteMatch()->getParam('channel')
675
                    ),
676
                    array('force_canonical' => true)
677
                ).'?id='.$postTarget->getId().'&key='.$secretKey;
678
                // With core shortener helper
679
                $socialLinkUrl = $this->shortenUrl()->shortenUrl($socialLinkUrl);
0 ignored issues
show
Documentation Bug introduced by
The method shortenUrl does not exist on object<PlaygroundGame\Co...end\PostVoteController>? 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...
680
                
681
                $this->getViewHelper('HeadMeta')->setProperty('og:image', $fbShareImage);
0 ignored issues
show
Bug introduced by
The variable $fbShareImage 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...
682
                
683
                $this->getViewHelper('HeadMeta')->setProperty('twitter:card', "photo");
684
                $this->getViewHelper('HeadMeta')->setProperty('twitter:site', "@alfie_selfie");
685
                $this->getViewHelper('HeadMeta')->setProperty('twitter:title', $game->getTwShareMessage());
686
                $this->getViewHelper('HeadMeta')->setProperty('twitter:description', "");
687
                $this->getViewHelper('HeadMeta')->setProperty('twitter:image', $fbShareImage);
688
                $this->getViewHelper('HeadMeta')->setProperty('twitter:url', $socialLinkUrl);
689
            }
690
        }
691
        
692
        $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...
693
                'posts' => $paginator,
694
                'form' => $form,
695
                'statusMail' => $statusMail,
696
                'reportId' => $reportId,
697
                'filter' => $filter,
698
                'search' => $search,
699
            ));
700
701
        return $viewModel;
702
    }
703
704
    public function ajaxVoteAction()
705
    {
706
        // Call this for the session lock to be released (other ajax calls can then be made)
707
        session_write_close();
708
709
        $identifier = $this->getEvent()->getRouteMatch()->getParam('id');
710
        $postId     = $this->getEvent()->getRouteMatch()->getParam('post');
711
        $user        = $this->zfcUserAuthentication()->getIdentity();
0 ignored issues
show
Documentation Bug introduced by
The method zfcUserAuthentication does not exist on object<PlaygroundGame\Co...end\PostVoteController>? 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...
712
        $sg = $this->getGameService();
713
714
        $game = $sg->checkGame($identifier);
715
        if (! $game) {
716
            $response->setContent(\Zend\Json\Json::encode(array(
0 ignored issues
show
Bug introduced by
The variable $response seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
717
                'success' => 0
718
            )));
719
720
            return $response;
0 ignored issues
show
Bug introduced by
The variable $response seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
721
        }
722
723
        $request = $this->getRequest();
724
        $response = $this->getResponse();
725
726
        if (!$this->zfcUserAuthentication()->hasIdentity()) {
0 ignored issues
show
Documentation Bug introduced by
The method zfcUserAuthentication does not exist on object<PlaygroundGame\Co...end\PostVoteController>? 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...
727
            $response->setContent(\Zend\Json\Json::encode(array(
728
                    'success' => 0
729
            )));
730
        } else {
731
            if ($request->isPost()) {
732
                $post = $sg->getPostvotePostMapper()->findById($postId);
733
                if ($sg->addVote($user, $this->getRequest()->getServer('REMOTE_ADDR'), $post)) {
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 getServer() does only exist in the following implementations of said interface: Zend\Http\PhpEnvironment\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...
734
                    $response->setContent(\Zend\Json\Json::encode(array(
735
                        'success' => 1
736
                    )));
737
                } else {
738
                    $response->setContent(\Zend\Json\Json::encode(array(
739
                        'success' => 0
740
                    )));
741
                }
742
            }
743
        }
744
745
        return $response;
746
    }
747
748
    public function captchaAction()
749
    {
750
        $response = $this->getResponse();
751
        $response->getHeaders()->addHeaderLine('Content-Type', "image/png");
752
753
        $id = $this->params('id', false);
754
755
        if ($id) {
756
            $image = './data/captcha/' . $id;
757
758
            if (file_exists($image) !== false) {
759
                $imagegetcontent = file_get_contents($image);
760
761
                $response->setStatusCode(200);
762
                $response->setContent($imagegetcontent);
763
764
                if (file_exists($image) === true) {
765
                    unlink($image);
766
                }
767
            }
768
        }
769
770
        return $response;
771
    }
772
    
773
    public function shareAction()
774
    {
775
        $identifier = $this->getEvent()->getRouteMatch()->getParam('id');
776
        $user = $this->zfcUserAuthentication()->getIdentity();
0 ignored issues
show
Documentation Bug introduced by
The method zfcUserAuthentication does not exist on object<PlaygroundGame\Co...end\PostVoteController>? 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...
777
        $sg = $this->getGameService();
778
    
779
        $statusMail = null;
780
    
781
        if (!$identifier) {
782
            return $this->notFoundAction();
783
        }
784
    
785
        $gameMapper = $this->getGameService()->getGameMapper();
786
        $game = $gameMapper->findByIdentifier($identifier);
787
    
788
        if (!$game || $game->isClosed()) {
789
            return $this->notFoundAction();
790
        }
791
    
792
        // Has the user finished the game ?
793
        $lastEntry = $this->getGameService()->findLastInactiveEntry($game, $user);
794
    
795
        if ($lastEntry === null) {
796
            return $this->redirect()->toUrl(
797
                $this->frontendUrl()->fromRoute(
0 ignored issues
show
Documentation Bug introduced by
The method frontendUrl does not exist on object<PlaygroundGame\Co...end\PostVoteController>? 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...
798
                    'postvote',
799
                    array(
800
                        'id' => $identifier,
801
                        'channel' => $this->getEvent()->getRouteMatch()->getParam('channel')
802
                    )
803
                )
804
            );
805
        }
806
    
807
        $post = $sg->getPostVotePostMapper()->findOneBy(array('entry' => $lastEntry));
808
    
809
        $secretKey = strtoupper(substr(sha1(uniqid('pg_', true).'####'.time()), 0, 15));
810
        $socialLinkUrl = $this->frontendUrl()->fromRoute(
0 ignored issues
show
Documentation Bug introduced by
The method frontendUrl does not exist on object<PlaygroundGame\Co...end\PostVoteController>? 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...
811
            'postvote/post',
812
            array(
813
                'id' => $identifier,
814
                'post' => $post->getId(),
815
                'channel' => $this->getEvent()->getRouteMatch()->getParam('channel')
816
            ),
817
            array('force_canonical' => true)
818
        ).'?key='.$secretKey;
819
        // With core shortener helper
820
        $socialLinkUrl = $this->shortenUrl()->shortenUrl($socialLinkUrl);
0 ignored issues
show
Unused Code introduced by
$socialLinkUrl 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...
Documentation Bug introduced by
The method shortenUrl does not exist on object<PlaygroundGame\Co...end\PostVoteController>? 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...
821
    
822 View Code Duplication
        if (!$user && !$game->getAnonymousAllowed()) {
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...
823
            $redirect = urlencode(
824
                $this->frontendUrl()->fromRoute(
0 ignored issues
show
Documentation Bug introduced by
The method frontendUrl does not exist on object<PlaygroundGame\Co...end\PostVoteController>? 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...
825
                    'postvote/result',
826
                    array('id' => $game->getIdentifier(), 'channel' => $channel)
0 ignored issues
show
Bug introduced by
The variable $channel does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
827
                )
828
            );
829
            return $this->redirect()->toUrl(
830
                $this->frontendUrl()->fromRoute(
0 ignored issues
show
Documentation Bug introduced by
The method frontendUrl does not exist on object<PlaygroundGame\Co...end\PostVoteController>? 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...
831
                    'zfcuser/register',
832
                    array('channel' => $channel)
833
                ) . '?redirect='.$redirect
834
            );
835
        }
836
    
837
        $form = $this->getServiceLocator()->get('playgroundgame_sharemail_form');
838
        $form->setAttribute('method', 'post');
839
    
840 View Code Duplication
        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...
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...
841
            $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...
842
            $form->setData($data);
843
            if ($form->isValid()) {
844
                $result = $this->getGameService()->sendShareMail($data, $game, $user, $lastEntry);
845
                if ($result) {
846
                    $statusMail = true;
847
                }
848
            }
849
        }
850
851
        $viewModel = $this->buildView($game);
852
    
853 View Code Duplication
        foreach ($post->getPostElements() as $element) {
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...
854
            $fbShareImage = $this->frontendUrl()->fromRoute(
0 ignored issues
show
Documentation Bug introduced by
The method frontendUrl does not exist on object<PlaygroundGame\Co...end\PostVoteController>? 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...
855
                '',
856
                array('channel' => ''),
857
                array('force_canonical' => true),
858
                false
859
            ) . $element->getValue();
860
            break;
861
        }
862
    
863
        $secretKey = strtoupper(substr(sha1(uniqid('pg_', true).'####'.time()), 0, 15));
864
865
        // Without bit.ly shortener
866
        $socialLinkUrl = $this->frontendUrl()->fromRoute(
0 ignored issues
show
Documentation Bug introduced by
The method frontendUrl does not exist on object<PlaygroundGame\Co...end\PostVoteController>? 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...
867
            'postvote/list',
868
            array(
869
                'id' => $game->getIdentifier(),
870
                'filter' => 'date',
871
                'channel' => $this->getEvent()->getRouteMatch()->getParam('channel')
872
            ),
873
            array('force_canonical' => true)
874
        ).'?id='.$post->getId().'&key='.$secretKey;
875
        // With core shortener helper
876
        $socialLinkUrl = $this->shortenUrl()->shortenUrl($socialLinkUrl);
0 ignored issues
show
Documentation Bug introduced by
The method shortenUrl does not exist on object<PlaygroundGame\Co...end\PostVoteController>? 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...
877
878
        $this->getViewHelper('HeadMeta')->setProperty('og:image', $fbShareImage);
0 ignored issues
show
Bug introduced by
The variable $fbShareImage 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...
879
880
        $this->getViewHelper('HeadMeta')->setProperty('twitter:card', "photo");
881
        $this->getViewHelper('HeadMeta')->setProperty('twitter:site', "@playground");
882
        $this->getViewHelper('HeadMeta')->setProperty('twitter:title', $game->getTwShareMessage());
883
        $this->getViewHelper('HeadMeta')->setProperty('twitter:description', "");
884
        $this->getViewHelper('HeadMeta')->setProperty('twitter:image', $fbShareImage);
885
        $this->getViewHelper('HeadMeta')->setProperty('twitter:url', $socialLinkUrl);
886
            
887
        $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...
888
            'statusMail'       => $statusMail,
889
            'form'             => $form,
890
            'socialLinkUrl'    => $socialLinkUrl,
891
            'post'             => $post
892
        ));
893
    
894
        return $viewModel;
895
    }
896
897
    public function getGameService()
898
    {
899
        if (!$this->gameService) {
900
            $this->gameService = $this->getServiceLocator()->get('playgroundgame_postvote_service');
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->getServiceLocator...game_postvote_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...
901
        }
902
903
        return $this->gameService;
904
    }
905
}
906