Completed
Push — master ( fe2a3e...0bf495 )
by greg
07:03 queued 03:32
created

PostVoteController::postAction()   D

Complexity

Conditions 13
Paths 46

Size

Total Lines 114
Code Lines 78

Duplication

Lines 8
Ratio 7.02 %

Importance

Changes 10
Bugs 2 Features 0
Metric Value
c 10
b 2
f 0
dl 8
loc 114
rs 4.9922
cc 13
eloc 78
nc 46
nop 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
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
        $redirectFb = $this->checkFbRegistration($this->user, $this->game);
26
        if ($redirectFb) {
27
            return $redirectFb;
28
        }
29
30
        $entry = $this->getGameService()->play($this->game, $this->user);
31
32
        if (!$entry) {
33
            $lastEntry = $this->getGameService()->findLastInactiveEntry($this->game, $this->user);
34
            if ($lastEntry === null) {
35
                return $this->redirect()->toUrl(
36
                    $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...
37
                        'postvote',
38
                        array('id' => $this->game->getIdentifier())
39
                    )
40
                );
41
            }
42
43
            $lastEntryId = $lastEntry->getId();
44
            $lastPost = $this->getGameService()->getPostVotePostMapper()->findOneBy(array('entry' => $lastEntryId));
45
            $postId = $lastPost->getId();
46
            if ($lastPost->getStatus() == 2) {
47
                // the user has already taken part to this game and the participation limit has been reached
48
                $this->flashMessenger()->addMessage(
49
                    $this->getServiceLocator()->get('translator')->translate('You have already a Post')
50
                );
51
52
                return $this->redirect()->toUrl(
53
                    $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...
54
                        'postvote/post',
55
                        array(
56
                            'id' => $this->game->getIdentifier(),
57
                            'post' => $postId,
58
                        )
59
                    )
60
                );
61
            } else {
62
                $this->flashMessenger()->addMessage(
63
                    $this->getServiceLocator()->get('translator')->translate('Your Post is waiting for validation')
64
                );
65
66
                return $this->redirect()->toUrl(
67
                    $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...
68
                        'postvote/post',
69
                        array(
70
                            'id' => $this->game->getIdentifier(),
71
                            'post' => $postId,
72
                            
73
                        )
74
                    )
75
                );
76
            }
77
        }
78
79
        if (! $this->game->getForm()) {
80
            return $this->redirect()->toUrl(
81
                $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...
82
                    'postvote',
83
                    array('id' => $this->game->getIdentifier())
84
                )
85
            );
86
        }
87
88
        $form = $this->getGameService()->createFormFromJson($this->game->getForm()->getForm(), 'postvoteForm');
89
90
        // Je recherche le post associé à entry + status == 0. Si non trouvé, je redirige vers home du jeu.
91
        $post = $this->getGameService()->getPostVotePostMapper()->findOneBy(array('entry' => $entry, 'status' => 0));
92
        if ($post) {
93
            foreach ($post->getPostElements() as $element) {
94
                try {
95
                    $form->get($element->getName())->setValue($element->getValue());
96
97
                    $elementType = $form->get($element->getName())->getAttribute('type');
98
                    if ($elementType == 'file' && $element->getValue() != '') {
99
                        $filter = $form->getInputFilter();
100
                        $elementInput = $filter->get($element->getName());
101
                        $elementInput->setRequired(false);
102
                        $form->get($element->getName())->setAttribute('required', false);
103
                    }
104
                } 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...
105
                }
106
            }
107
        }
108
109
        $viewModel = $this->buildView($this->game);
110
111
        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...
112
            // POST Request: Process form
113
            $data = array_merge_recursive(
114
                $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...
115
                $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...
116
            );
117
118
            $form->setData($data);
119
120
            if ($form->isValid()) {
121
                $data = $form->getData();
122
                $post = $this->getGameService()->createPost($data, $this->game, $this->user, $form);
123
124 View Code Duplication
                if ($post && !empty($this->game->nextStep('play'))) {
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...
125
                    // determine the route where the user should go
126
                    $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...
127
                        'postvote/'.$this->game->nextStep('play'),
128
                        array('id' => $this->game->getIdentifier())
129
                    );
130
131
                    return $this->redirect()->toUrl($redirectUrl);
132
                }
133
            } else {
134
                $messages = $form->getMessages();
135
                $viewModel = $this->buildView($this->game);
136
                $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...
137
                    'success' => false,
138
                    'message' => implode(',', $messages['title']),
139
                ));
140
            }
141
        }
142
143
        $viewModel->setVariables(array(
144
            'playerData' => $entry->getPlayerData(),
145
            'form' => $form,
146
            'post' => $post,
147
        ));
148
149
        return $viewModel;
150
    }
151
152
    public function previewAction()
153
    {
154
        $entry = $this->getGameService()->findLastActiveEntry($this->game, $this->user);
155
         
156 View Code Duplication
        if (!$entry) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
157
            // the user has already taken part of this game and the participation limit has been reached
158
            return $this->redirect()->toUrl(
159
                $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...
160
                    'postvote/'.$this->game->nextStep('preview'),
161
                    array('id' => $this->game->getIdentifier())
162
                )
163
            );
164
        }
165
166
        // Je recherche le post associé à entry + status == 0. Si non trouvé, je redirige vers home du jeu.
167
        $post = $this->getGameService()->getPostVotePostMapper()->findOneBy(array('entry' => $entry, 'status' => 0));
168
169
        if (! $post) {
170
            return $this->redirect()->toUrl(
171
                $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...
172
                    'postvote',
173
                    array('id' => $this->game->getIdentifier())
174
                )
175
            );
176
        }
177
178
        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...
179
            $post = $this->getGameService()->confirmPost($this->game, $this->user);
180
181
            if ($post) {
182
                if (!($step = $this->game->nextStep('play'))) {
183
                    $step = 'result';
184
                }
185
                $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...
186
                    'postvote/'.$step,
187
                    array('id' => $this->game->getIdentifier())
188
                );
189
190
                return $this->redirect()->toUrl($redirectUrl);
191
            }
192
        }
193
194
        $viewModel = $this->buildView($this->game);
195
        $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...
196
197
        return $viewModel;
198
    }
199
200
    /**
201
     * View the Post page
202
     * @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...
203
     */
204
    public function postAction()
205
    {
206
        $postId = $this->getEvent()->getRouteMatch()->getParam('post');
207
        $voted = false;
208
        $statusMail = false;
209
        $mailService = $this->getServiceLocator()->get('playgroundgame_message');
210
        $to = '';
211
        $skinUrl = $this->getGameService()->getServiceManager()->get('ViewRenderer')->url(
212
            'frontend',
213
            array(),
214
            array('force_canonical' => true)
215
        );
216
        $config = $this->getGameService()->getServiceManager()->get('config');
217
        if (isset($config['moderation']['email'])) {
218
            $to = $config['moderation']['email'];
219
        }
220
221
        if (! $postId) {
222
            return $this->notFoundAction();
223
        }
224
225
        // Je recherche le post associé à entry + status == 0. Si non trouvé, je redirige vers home du jeu.
226
        $post = $this->getGameService()->getPostVotePostMapper()->findById($postId);
227
228 View Code Duplication
        if (! $post || $post->getStatus() === 9) {
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...
229
            return $this->redirect()->toUrl(
230
                $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...
231
                    'postvote',
232
                    array('id' => $this->game->getIdentifier())
233
                )
234
            );
235
        }
236
237
        $formModeration = new Form();
238
        $formModeration->setAttribute('method', 'post');
239
240
        $formModeration->add(array(
241
            'name' => 'moderation',
242
            'attributes' => array(
243
                'type' => 'hidden',
244
                'value' => '1'
245
            ),
246
        ));
247
248
        $form = new \PlaygroundGame\Form\Frontend\PostVoteVote(
249
            $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...
250
                'postvote/post/captcha',
251
                array(
252
                    'id' => $this->game->getIdentifier(),
253
                    'post' => $postId,
254
                )
255
            )
256
        );
257
258
        if ($this->user) {
259
            $form->remove('captcha');
260
            if(count($this->getGameService()->getPostvoteVoteMapper()->findBy(array('userId' => $this->user->getId(), 'post' =>$post))) > 0) $voted = true;
261
        }
262
263
        $alreadyVoted = '';
264
        $reportId = '';
265
266
        $request = $this->getRequest();
267
        if ($request->isPost()) {
268
            $data = $request->getPost()->toArray();
269
            if (isset($data['moderation'])) {
270
                $formModeration->setData($data);
271
                if ($formModeration->isValid()) {
272
                    $from = $to;
273
                    $subject= 'Moderation Post and Vote';
274
                    $result = $mailService->createHtmlMessage(
275
                        $from,
276
                        $to,
277
                        $subject,
278
                        'playground-game/email/moderation',
279
                        array('data' => $data, 'skinUrl' => $skinUrl)
280
                    );
281
                    $mailService->send($result);
282
                    if ($result) {
283
                        $statusMail = true;
284
                        $reportId = $data['reportid'];
285
                    }
286
                }
287
            } else {
288
                $form->setData($request->getPost());
289
                if ($form->isValid()) {
290
                    if ($this->getGameService()->addVote(
291
                        $this->user,
292
                        $this->getRequest()->getServer('REMOTE_ADDR'),
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...
293
                        $post
294
                    )) {
295
                        $voted = true;
296
                    } else {
297
                        $alreadyVoted = 'Vous avez déjà voté!';
298
                    }
299
                }
300
            }
301
        }
302
303
        $viewModel = $this->buildView($this->game);
304
        $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...
305
            array(
306
                'post'  => $post,
307
                'voted' => $voted,
308
                'form'  => $form,
309
                'formModeration' => $formModeration,
310
                'statusMail' => $statusMail,
311
                'alreadyVoted' => $alreadyVoted,
312
                'reportId' => $reportId,
313
            )
314
        );
315
316
        return $viewModel;
317
    }
318
319
    /**
320
     *
321
     */
322
    public function resultAction()
323
    {
324
        $lastEntry = $this->getGameService()->findLastInactiveEntry($this->game, $this->user);
325
        if ($lastEntry == null) {
326
            return $this->redirect()->toUrl($this->frontendUrl()->fromRoute('postvote', array('id' => $identifier)));
0 ignored issues
show
Bug introduced by
The variable $identifier 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...
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...
327
        }
328
        // Je recherche le post associé à entry + status == 0. Si non trouvé, je redirige vers home du jeu.
329
        $post = $this->getGameService()->getPostVotePostMapper()->findOneBy(array('entry' => $lastEntry));
330
331 View Code Duplication
        if (! $post) {
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...
332
            die('bad');
333
            return $this->redirect()->toUrl(
0 ignored issues
show
Unused Code introduced by
return $this->redirect()...me->getIdentifier()))); does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
334
                $this->frontendUrl()->fromRoute(
335
                    'postvote',
336
                    array('id' => $this->game->getIdentifier())
337
                )
338
            );
339
        }
340
341
        $view = $this->forward()->dispatch(
342
            'playgroundgame_'.$this->game->getClassType(),
343
            array(
344
                'controller' => 'playgroundgame_'.$this->game->getClassType(),
345
                'action' => 'share',
346
                'id' => $this->game->getIdentifier()
347
            )
348
        );
349
350
        if ($view && $view instanceof \Zend\View\Model\ViewModel) {
351
            $view->setVariables(array('post' => $post));
352
353
            return $view;
354
        } elseif ($view && $view instanceof \Zend\Http\PhpEnvironment\Response) {
355
            return $view;
356
        } else {
357
            $form = $this->getServiceLocator()->get('playgroundgame_sharemail_form');
358
            $form->setAttribute('method', 'post');
359
360
            $viewModel = $this->buildView($this->game);
361
362
            $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...
363
                    'statusMail' => null,
364
                    'post' => $post,
365
                    'form' => $form,
366
                ));
367
368
            return $viewModel;
369
        }
370
    }
371
372
    /**
373
     * Example of AJAX File Upload with Session Progress and partial validation.
374
     * It's now possible to send a base64 image in this case the call is the form :
375
     * this._ajax(
376
     * {
377
     *   url: url.dataset.url,
378
     *    method: 'post',
379
     *    body: 'photo=' + image
380
     * },
381
     *
382
     * @return \Zend\Stdlib\ResponseInterface
383
     */
384
    public function ajaxuploadAction()
385
    {
386
        // Call this for the session lock to be released (other ajax calls can then be made)
387
        session_write_close();
388
389
        if (! $this->game) {
390
            $this->getResponse()->setContent(\Zend\Json\Json::encode(array(
391
                'success' => 0
392
            )));
393
394
            return $this->getResponse();
395
        }
396
397
        $entry = $this->getGameService()->findLastActiveEntry(
398
            $this->game,
399
            $this->user
400
        );
401
        if (!$entry) {
402
            // the user has already taken part of this game and the participation limit has been reached
403
            $this->getResponse()->setContent(\Zend\Json\Json::encode(array(
404
                'success' => 0
405
            )));
406
407
            return $this->getResponse();
408
        }
409
410
        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...
411
            $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...
412
413
            if (empty($data)) {
414
                $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...
415
                $key = key($data);
416
                $uploadImage = array('name' => $key.'.png', 'error' => 0, 'base64' => $data[$key]);
417
                $data = array($key => $uploadImage);
418
            }
419
            $uploadFile = $this->getGameService()->uploadFileToPost(
420
                $data,
421
                $this->game,
422
                $this->user
423
            );
424
        }
425
426
        $this->getResponse()->setContent(\Zend\Json\Json::encode(array(
427
            'success' => true,
428
            '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...
429
        )));
430
431
        return $this->getResponse();
432
    }
433
434
    public function ajaxdeleteAction()
435
    {
436
        $response = $this->getResponse();
437
438
        if (! $this->game) {
439
            $response->setContent(\Zend\Json\Json::encode(array(
440
                'success' => 0
441
            )));
442
443
            return $response;
444
        }
445
446
        $entry = $this->getGameService()->findLastActiveEntry($this->game, $this->user);
447
        if (!$entry) {
448
            // the user has already taken part of this game and the participation limit has been reached
449
            $response->setContent(\Zend\Json\Json::encode(array(
450
                'success' => 0
451
            )));
452
453
            return $response;
454
        }
455
        if ($request->isPost()) {
456
            $data = $request->getPost()->toArray();
0 ignored issues
show
Bug introduced by
The variable $request 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...
457
            $this->getGameService()->deleteFilePosted($data, $this->game, $this->user);
458
        }
459
460
        $response->setContent(\Zend\Json\Json::encode(array(
461
            'success' => true,
462
        )));
463
464
        return $response;
465
    }
466
467
    public function listAction()
468
    {
469
        $filter = $this->getEvent()->getRouteMatch()->getParam('filter');
470
        $search = $this->params()->fromQuery('name');
471
        $postId = $this->params()->fromQuery('id');
472
        $statusMail = false;
473
        $mailService = $this->getServiceLocator()->get('playgroundgame_message');
474
        $to = '';
475
        $skinUrl = $this->getGameService()->getServiceManager()->get('ViewRenderer')->url(
476
            'frontend',
477
            array(),
478
            array('force_canonical' => true)
479
        );
480
        $config = $this->getGameService()->getServiceManager()->get('config');
481
        if (isset($config['moderation']['email'])) {
482
            $to = $config['moderation']['email'];
483
        }
484
485
        $request = $this->getRequest();
486
487
        // Je recherche les posts validés associés à ce jeu
488
        $posts = $this->getGameService()->findArrayOfValidatedPosts($this->game, $this->user, $filter, $search);
489
490
        if (is_array($posts)) {
491
            $paginator = new \Zend\Paginator\Paginator(new \Zend\Paginator\Adapter\ArrayAdapter($posts));
492
            $paginator->setItemCountPerPage($this->game->getPostDisplayNumber());
493
            $paginator->setCurrentPageNumber($this->getEvent()->getRouteMatch()->getParam('p'));
494
        } else {
495
            $paginator = $posts;
496
        }
497
498
        $form = new Form();
499
        $form->setAttribute('method', 'post');
500
501
        $form->add(array(
502
            'name' => 'moderation',
503
            'attributes' => array(
504
                'type' => 'hidden',
505
                'value' => '1'
506
            ),
507
        ));
508
509
        $reportId ='';
510
511
        if ($request->isPost()) {
512
            $data = $request->getPost()->toArray();
513
514
            if (isset($data['moderation'])) {
515
                $from = $to;
516
                $subject= 'Moderation Post and Vote';
517
                $result = $mailService->createHtmlMessage(
518
                    $from,
519
                    $to,
520
                    $subject,
521
                    'playground-game/email/moderation',
522
                    array('data' => $data, 'skinUrl' => $skinUrl)
523
                );
524
                $mailService->send($result);
525
                if ($result) {
526
                    $statusMail = true;
527
                    $reportId = $data['reportid'];
528
                }
529
            }
530
        }
531
532
        $viewModel = $this->buildView($this->game);
533
        
534
        if ($postId) {
535
            $postTarget = $this->getGameService()->getPostVotePostMapper()->findById($postId);
536
            if ($postTarget) {
537 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...
538
                    $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...
539
                        '',
540
                        array(),
541
                        array('force_canonical' => true),
542
                        false
543
                    ) . $element->getValue();
544
                    break;
545
                }
546
                
547
                $secretKey = strtoupper(substr(sha1(uniqid('pg_', true).'####'.time()), 0, 15));
548
                
549
                // Without bit.ly shortener
550
                $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...
551
                    'postvote/list',
552
                    array(
553
                        'id' => $this->game->getIdentifier(),
554
                        'filter' => 'date'),
555
                    array('force_canonical' => true)
556
                ).'?id='.$postTarget->getId().'&key='.$secretKey;
557
                // With core shortener helper
558
                $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...
559
                
560
                $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...
561
                $this->getViewHelper('HeadMeta')->setProperty('twitter:card', "photo");
562
                $this->getViewHelper('HeadMeta')->setProperty('twitter:site', "@alfie_selfie");
563
                $this->getViewHelper('HeadMeta')->setProperty('twitter:title', $this->game->getTwShareMessage());
564
                $this->getViewHelper('HeadMeta')->setProperty('twitter:description', "");
565
                $this->getViewHelper('HeadMeta')->setProperty('twitter:image', $fbShareImage);
566
                $this->getViewHelper('HeadMeta')->setProperty('twitter:url', $socialLinkUrl);
567
            }
568
        }
569
        
570
        $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...
571
                'posts' => $paginator,
572
                'form' => $form,
573
                'statusMail' => $statusMail,
574
                'reportId' => $reportId,
575
                'filter' => $filter,
576
                'search' => $search,
577
            ));
578
579
        return $viewModel;
580
    }
581
582
    public function ajaxVoteAction()
583
    {
584
        // Call this for the session lock to be released (other ajax calls can then be made)
585
        session_write_close();
586
        $postId = $this->getEvent()->getRouteMatch()->getParam('post');
587
        $request = $this->getRequest();
588
        $response = $this->getResponse();
589
590
        if (! $this->game) {
591
            $response->setContent(\Zend\Json\Json::encode(array(
592
                'success' => 0
593
            )));
594
595
            return $response;
596
        }
597
598 View Code Duplication
        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...
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...
599
            $response->setContent(\Zend\Json\Json::encode(array(
600
                'success' => 0
601
            )));
602
        } else {
603
            if ($request->isPost()) {
604
                $post = $this->getGameService()->getPostvotePostMapper()->findById($postId);
605
                if ($this->getGameService()->addVote(
606
                    $this->user,
607
                    $this->getRequest()->getServer('REMOTE_ADDR'),
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...
608
                    $post
609
                )) {
610
                    $response->setContent(\Zend\Json\Json::encode(array(
611
                        'success' => 1
612
                    )));
613
                } else {
614
                    $response->setContent(\Zend\Json\Json::encode(array(
615
                        'success' => 0
616
                    )));
617
                }
618
            }
619
        }
620
621
        return $response;
622
    }
623
624
    public function commentsAction()
625
    {
626
627
        $postId = $this->getEvent()->getRouteMatch()->getParam('post');
628
        if($postId){
629
            $post = $this->getGameService()->getPostvotePostMapper()->findById($postId);
0 ignored issues
show
Unused Code introduced by
$post 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...
630
            $comments = $this->getGameService()->getCommentsForPostvote($postId);
631
        } else {
632
            $comments = $this->getGameService()->getCommentsForPostvote($this->game);
633
        }
634
635
        if (is_array($comments)) {
636
            $paginator = new \Zend\Paginator\Paginator(new \Zend\Paginator\Adapter\ArrayAdapter($comments));
637
            $paginator->setItemCountPerPage(500);
638
            $paginator->setCurrentPageNumber($this->getEvent()->getRouteMatch()->getParam('p'));
639
        } else {
640
            $paginator = $comments;
641
        }
642
643
        $viewModel = $this->buildView($this->game);
644
        $viewModel->setVariables(array('comments' => $paginator));
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...
645
646
        return $viewModel;
647
    }
648
649
    public function commentAction()
650
    {
651
        if ($this->getRequest()->isXmlHttpRequest()) {
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 isXmlHttpRequest() 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...
652
            // Call this for the session lock to be released (other ajax calls can then be made)
653
            session_write_close();
654
        }
655
        $postId = $this->getEvent()->getRouteMatch()->getParam('post');
656
        $request = $this->getRequest();
657
        $response = $this->getResponse();
658
        $post = $this->getGameService()->getPostvotePostMapper()->findById($postId);
659
660 View Code Duplication
        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...
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...
661
            $response->setContent(\Zend\Json\Json::encode(array(
662
                'success' => 0
663
            )));
664
        } else {
665
            if ($request->isPost()) {
666
                if ($this->getGameService()->addComment(
667
                    $this->user,
668
                    $this->getRequest()->getServer('REMOTE_ADDR'),
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...
669
                    $post,
670
                    $this->params()->fromPost('comment')
671
                )) {
672
                    $response->setContent(\Zend\Json\Json::encode(array(
673
                        'success' => 1
674
                    )));
675
                } else {
676
                    $response->setContent(\Zend\Json\Json::encode(array(
677
                        'success' => 0
678
                    )));
679
                }
680
            }
681
        }
682
683
        //ajax call ?
684
        if ($this->getRequest()->isXmlHttpRequest()) {
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 isXmlHttpRequest() 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...
685
686
            return $response;
687
        }
688
689
        return $this->redirect()->toUrl(
690
            $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...
691
                'les-idees/idee',
692
                array('post' => $post->getId())
693
            )
694
        );
695
    }
696
697
    public function ajaxRemoveCommentAction()
698
    {
699
        // Call this for the session lock to be released (other ajax calls can then be made)
700
        session_write_close();
701
        $commentId = $this->getEvent()->getRouteMatch()->getParam('comment');
702
        $request = $this->getRequest();
703
        $response = $this->getResponse();
704
705
        if (! $this->game) {
706
            $response->setContent(\Zend\Json\Json::encode(array(
707
                'success' => 0
708
            )));
709
710
            return $response;
711
        }
712
713 View Code Duplication
        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...
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...
714
            $response->setContent(\Zend\Json\Json::encode(array(
715
                'success' => 0
716
            )));
717
        } else {
718
            if ($request->isPost()) {
719
                if ($this->getGameService()->removeComment(
720
                    $this->user,
721
                    $this->getRequest()->getServer('REMOTE_ADDR'),
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...
722
                    $commentId
723
                )) {
724
                    $response->setContent(\Zend\Json\Json::encode(array(
725
                        'success' => 1
726
                    )));
727
                } else {
728
                    $response->setContent(\Zend\Json\Json::encode(array(
729
                        'success' => 0
730
                    )));
731
                }
732
            }
733
        }
734
735
        return $response;
736
    }
737
738
    public function captchaAction()
739
    {
740
        $response = $this->getResponse();
741
        $response->getHeaders()->addHeaderLine('Content-Type', "image/png");
742
743
        $id = $this->params('id', false);
744
745
        if ($id) {
746
            $image = './data/captcha/' . $id;
747
748
            if (file_exists($image) !== false) {
749
                $imagegetcontent = file_get_contents($image);
750
751
                $response->setStatusCode(200);
752
                $response->setContent($imagegetcontent);
753
754
                if (file_exists($image) === true) {
755
                    unlink($image);
756
                }
757
            }
758
        }
759
760
        return $response;
761
    }
762
    
763
    public function shareAction()
764
    {
765
        $statusMail = null;
766
    
767
        // Has the user finished the game ?
768
        $lastEntry = $this->getGameService()->findLastInactiveEntry($this->game, $this->user);
769
    
770
        if ($lastEntry === null) {
771
            return $this->redirect()->toUrl(
772
                $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...
773
                    'postvote',
774
                    array('id' => $this->game->getIdentifier())
775
                )
776
            );
777
        }
778
    
779
        $post = $this->getGameService()->getPostVotePostMapper()->findOneBy(array('entry' => $lastEntry));
780
    
781
        $secretKey = strtoupper(substr(sha1(uniqid('pg_', true).'####'.time()), 0, 15));
782
        $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...
783
            'postvote/post',
784
            array(
785
                'id' => $this->game->getIdentifier(),
786
                'post' => $post->getId(),
787
            ),
788
            array('force_canonical' => true)
789
        ).'?key='.$secretKey;
790
        // With core shortener helper
791
        $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...
792
    
793
        $form = $this->getServiceLocator()->get('playgroundgame_sharemail_form');
794
        $form->setAttribute('method', 'post');
795
    
796
        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...
797
            $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...
798
            $form->setData($data);
799 View Code Duplication
            if ($form->isValid()) {
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...
800
                $result = $this->getGameService()->sendShareMail($data, $this->game, $this->user, $lastEntry);
801
                if ($result) {
802
                    $statusMail = true;
803
                }
804
            }
805
        }
806
807
        $viewModel = $this->buildView($this->game);
808
    
809 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...
810
            $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...
811
                '',
812
                array(),
813
                array('force_canonical' => true),
814
                false
815
            ) . $element->getValue();
816
            break;
817
        }
818
819
        $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...
820
        $this->getViewHelper('HeadMeta')->setProperty('twitter:card', "photo");
821
        $this->getViewHelper('HeadMeta')->setProperty('twitter:site', "@playground");
822
        $this->getViewHelper('HeadMeta')->setProperty('twitter:title', $this->game->getTwShareMessage());
823
        $this->getViewHelper('HeadMeta')->setProperty('twitter:description', "");
824
        $this->getViewHelper('HeadMeta')->setProperty('twitter:image', $fbShareImage);
825
        $this->getViewHelper('HeadMeta')->setProperty('twitter:url', $socialLinkUrl);
826
            
827
        $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...
828
            'statusMail'       => $statusMail,
829
            'form'             => $form,
830
            'socialLinkUrl'    => $socialLinkUrl,
831
            'post'             => $post
832
        ));
833
    
834
        return $viewModel;
835
    }
836
837
    public function getGameService()
838
    {
839
        if (!$this->gameService) {
840
            $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...
841
        }
842
843
        return $this->gameService;
844
    }
845
}
846