Completed
Push — master ( 8a3179...d462e2 )
by greg
24:52 queued 21:12
created

GameController::editGame()   F

Complexity

Conditions 33
Paths 2088

Size

Total Lines 216

Duplication

Lines 14
Ratio 6.48 %

Importance

Changes 0
Metric Value
dl 14
loc 216
rs 0
c 0
b 0
f 0
cc 33
nc 2088
nop 2

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\Admin;
4
5
use PlaygroundGame\Service\Game as AdminGameService;
6
use Zend\Mvc\Controller\AbstractActionController;
7
use Zend\View\Model\ViewModel;
8
use PlaygroundGame\Options\ModuleOptions;
9
use Zend\Paginator\Paginator;
10
use DoctrineORMModule\Paginator\Adapter\DoctrinePaginator as DoctrineAdapter;
11
use PlaygroundCore\ORM\Pagination\LargeTablePaginator;
12
use Doctrine\ORM\Tools\Pagination\Paginator as ORMPaginator;
13
use Zend\Stdlib\ErrorHandler;
14
use Zend\ServiceManager\ServiceLocatorInterface;
15
use Zend\Session\Container;
16
17
class GameController extends AbstractActionController
18
{
19
    protected $options;
20
21
    /**
22
     * @var \PlaygroundGame\Service\Game
23
     */
24
    protected $adminGameService;
25
26
    protected $game;
27
28
    /**
29
     *
30
     * @var ServiceManager
31
     */
32
    protected $serviceLocator;
33
34
    public function __construct(ServiceLocatorInterface $locator)
35
    {
36
        $this->serviceLocator = $locator;
0 ignored issues
show
Documentation Bug introduced by
It seems like $locator of type object<Zend\ServiceManag...erviceLocatorInterface> is incompatible with the declared type object<PlaygroundGame\Co...r\Admin\ServiceManager> of property $serviceLocator.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
37
    }
38
39
    public function getServiceLocator()
40
    {
41
        return $this->serviceLocator;
42
    }
43
44
    public function checkGame()
45
    {
46
        $gameId = $this->getEvent()->getRouteMatch()->getParam('gameId');
47
        if (!$gameId) {
48
            return $this->redirect()->toRoute('admin/playgroundgame/list');
49
        }
50
        
51
        $game = $this->getAdminGameService()->getGameMapper()->findById($gameId);
52
        if (!$game) {
53
            return $this->redirect()->toRoute('admin/playgroundgame/list');
54
        }
55
        $this->game = $game;
56
    }
57
58
    public function createForm($form)
59
    {
60
        // I use the wonderful Form Generator to create the Player form
61
        $this->forward()->dispatch(
62
            'playgroundcore_admin_formgen',
63
            array(
64
                'controller' => 'playgroundcore_admin_formgen',
65
                'action' => 'create'
66
            )
67
        );
68
69
        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, Zend\Psr7Bridge\Zend\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...
70
            $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, Zend\Psr7Bridge\Zend\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...
71
            $form = $this->getAdminGameService()->createForm($data, $this->game, $form);
72
            if ($form) {
73
                $this->flashMessenger()->setNamespace('playgroundgame')->addMessage('The form was created');
0 ignored issues
show
Documentation Bug introduced by
The method flashMessenger does not exist on object<PlaygroundGame\Co...r\Admin\GameController>? 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...
74
            }
75
        }
76
        $formTemplate='';
77
        if ($form) {
78
            $formTemplate = $form->getFormTemplate();
79
        }
80
81
        return array(
82
            'form' => $form,
83
            'formTemplate' => $formTemplate,
84
            'gameId' => $this->game->getId(),
85
            'game' => $this->game,
86
        );
87
    }
88
89
    /**
90
     * @param string $templatePath
91
     * @param string $formId
92
     */
93
    public function editGame($templatePath, $formId)
94
    {
95
        // We try to get FB pages from the logged in user
96
        $session = new Container('facebook');
97
        $config = $this->getServiceLocator()->get('config');
98
        $appsArray = [];
99
        $platformFbAppId = '';
100
        
101 View Code Duplication
        if (isset($config['facebook'])) {
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...
102
            $platformFbAppId     = $config['facebook']['fb_appid'];
103
            $platformFbAppSecret = $config['facebook']['fb_secret'];
104
            $fbPage              = $config['facebook']['fb_page'];
0 ignored issues
show
Unused Code introduced by
$fbPage 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...
105
        }
106
        $fb = new \Facebook\Facebook([
107
            'app_id' => $platformFbAppId,
108
            'app_secret' => $platformFbAppSecret,
0 ignored issues
show
Bug introduced by
The variable $platformFbAppSecret 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...
109
            'default_graph_version' => 'v3.1',
110
            //'cookie' => false,
111
            //'default_access_token' => '{access-token}', // optional
112
        ]);
113
114
        $helper = $fb->getRedirectLoginHelper();
115
        $fb_args_param = array('req_perms' => 'manage_pages,publish_pages');
116
        $fb_login_url = $helper->getLoginUrl($this->url()->fromRoute(
117
            'admin/playgroundgame/list',
118
            array(),
119
            array('force_canonical' => true)), $fb_args_param);
120
        $accessToken = $helper->getAccessToken();
121
122
        if (isset($accessToken) || $session->offsetExists('fb_token')) {
123
            if (isset($accessToken)) {
124
                $session->offsetSet('fb_token', $accessToken);
125
            }
126
127
            // checking if user access token is not valid then ask user to login again
128
            $debugToken = $fb->get('/debug_token?input_token='. $session->offsetGet('fb_token'), $platformFbAppId . '|' . $platformFbAppSecret)
129
            ->getGraphNode()
130
            ->asArray();
131
            if (isset($debugToken['error']['code'])) {
132
                $session->offsetUnset('fb_token');
133
            } else {
134
                // setting default user access token for future requests
135
                $fb->setDefaultAccessToken($session->offsetGet('fb_token'));
136
                $pages = $fb->get('/me/accounts')
137
                    ->getGraphEdge()
138
                    ->asArray();
139
140
                foreach ($pages as $key) {
141
                    $app_label = '';
142
                    if (isset($key['name'])) {
143
                        $app_label .= $key['name'];
144
                    }
145
                    if (isset($key['id'])) {
146
                        $app_label .= ' ('.$key['id'].')';
147
                    }
148
                    $appsArray[$key['id']] = $app_label;
149
                }
150
                $fb_login_url = '';
151
152
                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, Zend\Psr7Bridge\Zend\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...
153
                    $data = array_replace_recursive(
154
                        $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, Zend\Psr7Bridge\Zend\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...
155
                        $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, Zend\Psr7Bridge\Zend\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...
156
                    );
157
                    // Removing a previously page tab set on this game
158
                    if( 
159
                        $this->game && 
160
                        !empty($this->game->getFbPageId()) &&
161
                        !empty($this->game->getFbAppId()) &&
162
                        (   
163
                            $this->game->getFbPageId() !== $data['fbPageId'] ||
164
                            $this->game->getFbAppId() !== $data['fbAppId']
165
                        )
166
                    ) {
167
                        $oldPage = $fb->get('/' . $this->game->getFbPageId() . '?fields=access_token,name,id')
168
                            ->getGraphNode()
169
                            ->asArray();
170
                        $removeTab = $fb->delete(
0 ignored issues
show
Unused Code introduced by
$removeTab 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...
171
                                '/' . $this->game->getFbPageId() . '/tabs',
172
                                [
173
                                    'tab' => 'app_'.$this->game->getFbAppId(),
174
                                ],
175
                                $oldPage['access_token']
176
                            )
177
                            ->getGraphNode()
178
                            ->asArray();
179
                    }
180
                }
181
            }
182
        }
183
184
        $viewModel = new ViewModel();
185
        $viewModel->setTemplate($templatePath);
186
187
        $gameForm = new ViewModel();
188
        $gameForm->setTemplate('playground-game/game/game-form');
189
190
        $form   = $this->getServiceLocator()->get($formId);
191
        $form->setAttribute(
192
            'action',
193
            $this->url()->fromRoute(
194
                'admin/playgroundgame/edit-' . $this->game->getClassType(),
195
                array('gameId' => $this->game->getId())
196
            )
197
        );
198
        $form->setAttribute('method', 'post');
199
200
        $pageIds = $form->get('fbPageId')->getOption('value_options');
201
        foreach($appsArray as $k => $v) {
202
            $pageIds[$k] = $v;
203
        }
204
        $form->get('fbPageId')->setAttribute('options', $pageIds);
205
206
        //if($form->get('fbAppId')->getValue() == '') {
207
            $form->get('fbAppId')->setValue($platformFbAppId);
208
        //}
209
210
        // if ($this->game->getFbAppId()) {
211
        //     $data['fbAppId'] = $form->get('fbAppId')->getOption('value_options');
212
        //     $appIds[$this->game->getFbAppId()] = $this->game->getFbAppId();
213
        //     $form->get('fbAppId')->setAttribute('options', $appIds);
214
        // }
215
216
        $gameOptions = $this->getAdminGameService()->getOptions();
217
        $gameStylesheet = $gameOptions->getMediaPath() . '/' . 'stylesheet_'. $this->game->getId(). '.css';
218 View Code Duplication
        if (is_file($gameStylesheet)) {
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...
219
            $values = $form->get('stylesheet')->getValueOptions();
220
            $values[$gameStylesheet] = 'Style personnalisé de ce jeu';
221
222
            $form->get('stylesheet')->setAttribute('options', $values);
223
        }
224
225
        $form->bind($this->game);
226
227
        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, Zend\Psr7Bridge\Zend\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...
228
            $data = array_replace_recursive(
229
                $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, Zend\Psr7Bridge\Zend\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...
230
                $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, Zend\Psr7Bridge\Zend\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...
231
            );
232
            if (empty($data['prizes'])) {
233
                $data['prizes'] = array();
234
            }
235 View Code Duplication
            if (isset($data['drawDate']) && $data['drawDate']) {
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...
236
                $data['drawDate'] = \DateTime::createFromFormat('d/m/Y', $data['drawDate']);
237
            }
238
            $game = $this->getAdminGameService()->createOrUpdate($data, $this->game, $formId);
239
240
            if ($game) {
241
                // Let's record the FB page tab if it is configured
242
                if ($session->offsetExists('fb_token')) {        
243
                    // adding page tab to selected page using page access token
244
                    if (!empty($data['fbPageId']) && !empty($data['fbAppId'])) {
245
                        $page = $fb->get('/' . $data['fbPageId'] . '?fields=access_token,name,id')
246
                        ->getGraphNode()
247
                        ->asArray();
248
249
                        try {
250
                            $addTab = $fb->post(
0 ignored issues
show
Unused Code introduced by
$addTab 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...
251
                                '/' . $page['id'] . '/tabs',
252
                                [
253
                                    'app_id' => $data['fbAppId'],
254
                                    'custom_name' => (!empty($data['fbPageTabTitle'])) ? $data['fbPageTabTitle'] : $data['title'],
255
                                    'custom_image_url' => ($game->getFbPageTabImage() !== '') ? 
256
                                        $this->getAdminGameService()->getServiceManager()->get('ViewRenderer')->url(
257
                                            'frontend',
258
                                            array(),
259
                                            array('force_canonical' => true)
260
                                        ).$game->getFbPageTabImage() :
261
                                        null,
262
                                    'position' => (!empty($data['fbPageTabPosition'])) ? $data['fbPageTabPosition'] : 99
263
                                ],
264
                                $page['access_token'])
265
                                ->getGraphNode()
266
                                ->asArray();
267
                        } catch (\Exception $e) {
268
                            // (#324) Missing or invalid image file
269
                            if($e->getCode() == '324') {
270
                                try {
271
                                    $addTab = $fb->post(
0 ignored issues
show
Unused Code introduced by
$addTab 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...
272
                                        '/' . $page['id'] . '/tabs',
273
                                        [
274
                                            'app_id' => $data['fbAppId'],
275
                                            'custom_name' => (!empty($data['fbPageTabTitle'])) ? $data['fbPageTabTitle'] : $data['title'],
276
                                            'position' => (!empty($data['fbPageTabPosition'])) ? $data['fbPageTabPosition'] : 99
277
                                        ],
278
                                        $page['access_token'])
279
                                        ->getGraphNode()
280
                                        ->asArray();
281
                                } catch (\Exception $e) {
282
                                    throw $e;
283
                                }
284
                            }
285
                        }
286
                    }
287
                }
288
                return $this->redirect()->toRoute('admin/playgroundgame/list');
289
            }
290
        }
291
292
        $gameForm->setVariables(
293
            array(
294
                'platform_fb_app_id' => $platformFbAppId,
295
                'fb_login_url' => $fb_login_url,
296
                'form' => $form,
297
                'game' => $this->game
298
            )
299
        );
300
        $viewModel->addChild($gameForm, 'game_form');
301
302
        return $viewModel->setVariables(
303
            array(
304
                'form' => $form,
305
                'title' => 'Edit this game',
306
            )
307
        );
308
    }
309
310
    public function listAction()
311
    {
312
        // We try to get FB pages from the logged in user
313
        $session = new Container('facebook');
314
        $config = $this->getServiceLocator()->get('config');
315
        
316 View Code Duplication
        if (isset($config['facebook'])) {
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...
317
            $platformFbAppId     = $config['facebook']['fb_appid'];
318
            $platformFbAppSecret = $config['facebook']['fb_secret'];
319
            $fbPage              = $config['facebook']['fb_page'];
0 ignored issues
show
Unused Code introduced by
$fbPage 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...
320
        }
321
        $fb = new \Facebook\Facebook([
322
            'app_id' => $platformFbAppId,
0 ignored issues
show
Bug introduced by
The variable $platformFbAppId 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...
323
            'app_secret' => $platformFbAppSecret,
0 ignored issues
show
Bug introduced by
The variable $platformFbAppSecret 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...
324
            'default_graph_version' => 'v3.1',
325
        ]);
326
327
        $helper = $fb->getRedirectLoginHelper();
328
        $accessToken = $helper->getAccessToken();
329
330
        if (isset($accessToken) || $session->offsetExists('fb_token')) {
331
            if (isset($accessToken)) {
332
                $session->offsetSet('fb_token', $accessToken);
333
            }
334
335
            // checking if user access token is not valid then ask user to login again
336
            $debugToken = $fb->get('/debug_token?input_token='. $session->offsetGet('fb_token'), $platformFbAppId . '|' . $platformFbAppSecret)
337
            ->getGraphNode()
338
            ->asArray();
339
            if (isset($debugToken['error']['code'])) {
340
                $session->offsetUnset('fb_token');
341
            } else {
342
                // setting default user access token for future requests
343
                $fb->setDefaultAccessToken($session->offsetGet('fb_token'));
344
            }
345
        }
346
        $filter    = $this->getEvent()->getRouteMatch()->getParam('filter');
347
        $type    = $this->getEvent()->getRouteMatch()->getParam('type');
348
349
        $service    = $this->getAdminGameService();
350
        $adapter = new DoctrineAdapter(new ORMPaginator($service->getQueryGamesOrderBy($type, $filter)));
351
        $paginator = new Paginator($adapter);
352
        $paginator->setItemCountPerPage(25);
353
        $paginator->setCurrentPageNumber($this->getEvent()->getRouteMatch()->getParam('p'));
354
355
        foreach ($paginator as $game) {
356
            $game->entry = $service->getEntryMapper()->countByGame($game);
357
        }
358
359
        return array(
360
            'games'    => $paginator,
361
            'type'        => $type,
362
            'filter'    => $filter,
363
        );
364
    }
365
366
    public function entryAction()
367
    {
368
        $this->checkGame();
369
370
        $adapter = new DoctrineAdapter(
371
            new LargeTablePaginator(
372
                $this->getAdminGameService()->getEntriesQuery($this->game)
373
            )
374
        );
375
        $paginator = new Paginator($adapter);
376
        $paginator->setItemCountPerPage(10);
377
        $paginator->setCurrentPageNumber($this->getEvent()->getRouteMatch()->getParam('p'));
378
379
        $header = $this->getAdminGameService()->getEntriesHeader($this->game);
380
        $entries = $this->getAdminGameService()->getGameEntries($header, $paginator, $this->game);
381
382
        return array(
383
            'paginator' => $paginator,
384
            'entries' => $entries,
385
            'header' => $header,
386
            'game' => $this->game,
387
            'gameId' => $this->game->getId()
388
        );
389
    }
390
391 View Code Duplication
    public function invitationAction()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
392
    {
393
        $this->checkGame();
394
395
        $adapter = new DoctrineAdapter(
396
            new LargeTablePaginator(
397
                $this->getAdminGameService()->getInvitationMapper()->queryByGame($this->game)
398
            )
399
        );
400
        $paginator = new Paginator($adapter);
401
        $paginator->setItemCountPerPage(25);
402
        $paginator->setCurrentPageNumber($this->getEvent()->getRouteMatch()->getParam('p'));
403
404
        return new ViewModel(
405
            array(
406
                'invitations' => $paginator,
407
                'gameId'      => $this->game->getId(),
408
                'game'        => $this->game,
409
            )
410
        );
411
    }
412
413
    public function removeInvitationAction()
414
    {
415
        $this->checkGame();
416
417
        $service = $this->getAdminGameService();
418
        $invitationId = $this->getEvent()->getRouteMatch()->getParam('invitationId');
419
        if ($invitationId) {
420
            $invitation   = $service->getInvitationMapper()->findById($invitationId);
421
            $service->getInvitationMapper()->remove($invitation);
422
        }
423
424
        return $this->redirect()->toRoute(
425
            'admin/'. $this->game->getClassType() .'/invitation',
426
            array('gameId'=>$this->game->getId())
427
        );
428
    }
429
    
430
    public function downloadAction()
431
    {
432
        $this->checkGame();
433
        $header = $this->getAdminGameService()->getEntriesHeader($this->game);
434
        $query = $this->getAdminGameService()->getEntriesQuery($this->game);
435
436
        $content = "\xEF\xBB\xBF"; // UTF-8 BOM
437
        $content .= $this->getAdminGameService()->getCSV(
438
            $this->getAdminGameService()->getGameEntries(
439
                $header,
440
                $query->getResult(),
441
                $this->game
442
            )
443
        );
444
445
        $response = $this->getResponse();
446
        $headers = $response->getHeaders();
447
        $headers->addHeaderLine('Content-Encoding: UTF-8');
448
        $headers->addHeaderLine('Content-Type', 'text/csv; charset=UTF-8');
449
        $headers->addHeaderLine('Content-Disposition', "attachment; filename=\"entry.csv\"");
450
        $headers->addHeaderLine('Accept-Ranges', 'bytes');
451
        $headers->addHeaderLine('Content-Length', strlen($content));
452
453
        $response->setContent($content);
454
455
        return $response;
456
    }
457
458
    // Only used for Quiz and Lottery
459
    public function drawAction()
460
    {
461
        $this->checkGame();
462
463
        $winningEntries = $this->getAdminGameService()->draw($this->game);
464
465
        $content = "\xEF\xBB\xBF"; // UTF-8 BOM
466
        $content .= "ID;Pseudo;Nom;Prenom;E-mail;Etat\n";
467
468
        foreach ($winningEntries as $e) {
469
            $etat = 'gagnant';
470
471
            $content   .= $e->getUser()->getId()
472
            . ";" . $e->getUser()->getUsername()
473
            . ";" . $e->getUser()->getLastname()
474
            . ";" . $e->getUser()->getFirstname()
475
            . ";" . $e->getUser()->getEmail()
476
            . ";" . $etat
477
            ."\n";
478
        }
479
480
        $response = $this->getResponse();
481
        $headers = $response->getHeaders();
482
        $headers->addHeaderLine('Content-Encoding: UTF-8');
483
        $headers->addHeaderLine('Content-Type', 'text/csv; charset=UTF-8');
484
        $headers->addHeaderLine('Content-Disposition', "attachment; filename=\"gagnants.csv\"");
485
        $headers->addHeaderLine('Accept-Ranges', 'bytes');
486
        $headers->addHeaderLine('Content-Length', strlen($content));
487
488
        $response->setContent($content);
489
490
        return $response;
491
    }
492
    
493
    /**
494
     * This method serialize a game an export it as a txt file
495
     * @return \Zend\Stdlib\ResponseInterface
496
     */
497
    public function exportAction()
498
    {
499
        $this->checkGame();
500
        $content = serialize($this->game);
501
502
        $response = $this->getResponse();
503
        $headers = $response->getHeaders();
504
        $headers->addHeaderLine('Content-Encoding: UTF-8');
505
        $headers->addHeaderLine('Content-Type', 'text/plain; charset=UTF-8');
506
        $headers->addHeaderLine(
507
            'Content-Disposition',
508
            "attachment; filename=\"". $this->game->getIdentifier() .".txt\""
509
        );
510
        $headers->addHeaderLine('Accept-Ranges', 'bytes');
511
        $headers->addHeaderLine('Content-Length', strlen($content));
512
    
513
        $response->setContent($content);
514
    
515
        return $response;
516
    }
517
    
518
    /**
519
     * This method take an uploaded txt file containing a serialized game
520
     * and persist it in the database
521
     * @return unknown
522
     */
523
    public function importAction()
524
    {
525
        $form = $this->getServiceLocator()->get('playgroundgame_import_form');
526
        $form->setAttribute('action', $this->url()->fromRoute('admin/playgroundgame/import'));
527
        $form->setAttribute('method', 'post');
528
        
529
        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, Zend\Psr7Bridge\Zend\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...
530
            $data = array_replace_recursive(
531
                $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, Zend\Psr7Bridge\Zend\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...
532
                $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, Zend\Psr7Bridge\Zend\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...
533
            );
534
            
535
            if (! empty($data['import_file']['tmp_name'])) {
536
                ErrorHandler::start();
537
                $game = unserialize(file_get_contents($data['import_file']['tmp_name']));
538
                $game->setId(null);
539
                if ($data['slug']) {
540
                    $game->setIdentifier($data['slug']);
541
                }
542
                $duplicate = $this->getAdminGameService()->getGameMapper()->findByIdentifier($game->getIdentifier());
543
                if (!$duplicate) {
544
                    $this->getAdminGameService()->getGameMapper()->insert($game);
545
                }
546
547
                ErrorHandler::stop(true);
548
            }
549
            
550
            return $this->redirect()->toRoute('admin/playgroundgame/list');
551
        }
552
        
553
        return array(
554
            'form' => $form,
555
        );
556
    }
557
558
    public function removeAction()
559
    {
560
        $this->checkGame();
561
562
        try {
563
            $this->getAdminGameService()->getGameMapper()->remove($this->game);
564
            $this->flashMessenger()->setNamespace('playgroundgame')->addMessage('The game has been edited');
0 ignored issues
show
Documentation Bug introduced by
The method flashMessenger does not exist on object<PlaygroundGame\Co...r\Admin\GameController>? 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...
565
        } catch (\Doctrine\DBAL\DBALException $e) {
566
            $this->flashMessenger()->setNamespace('playgroundgame')->addMessage(
0 ignored issues
show
Documentation Bug introduced by
The method flashMessenger does not exist on object<PlaygroundGame\Co...r\Admin\GameController>? 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...
567
                'Il y a déjà eu des participants à ce jeu. Vous ne pouvez plus le supprimer'
568
            );
569
        }
570
571
        return $this->redirect()->toRoute('admin/playgroundgame/list');
572
    }
573
574
    public function setActiveAction()
575
    {
576
        $this->checkGame();
577
578
        $this->game->setActive(!$this->game->getActive());
579
        $this->getAdminGameService()->getGameMapper()->update($this->game);
580
581
        return $this->redirect()->toRoute('admin/playgroundgame/list');
582
    }
583
584
    public function formAction()
585
    {
586
        $this->checkGame();
587
        
588
        $form = $this->game->getPlayerForm();
589
590
        return $this->createForm($form);
591
    }
592
593
    public function setOptions(ModuleOptions $options)
594
    {
595
        $this->options = $options;
596
597
        return $this;
598
    }
599
600
    public function getOptions()
601
    {
602
        if (!$this->options instanceof ModuleOptions) {
603
            $this->setOptions($this->getServiceLocator()->get('playgroundgame_module_options'));
604
        }
605
606
        return $this->options;
607
    }
608
609
    public function getAdminGameService()
610
    {
611
        if (!$this->adminGameService) {
612
            $this->adminGameService = $this->getServiceLocator()->get('playgroundgame_game_service');
613
        }
614
615
        return $this->adminGameService;
616
    }
617
618
    public function setAdminGameService(AdminGameService $adminGameService)
619
    {
620
        $this->adminGameService = $adminGameService;
621
622
        return $this;
623
    }
624
}
625