Completed
Push — master ( 6a8f56...0bbdea )
by greg
11s
created

GameController::drawAction()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 33
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 33
rs 8.8571
cc 2
eloc 23
nc 2
nop 0
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
16
class GameController extends AbstractActionController
17
{
18
    protected $options;
19
20
    /**
21
     * @var \PlaygroundGame\Service\Game
22
     */
23
    protected $adminGameService;
24
25
    protected $game;
26
27
    /**
28
     *
29
     * @var ServiceManager
30
     */
31
    protected $serviceLocator;
32
33
    public function __construct(ServiceLocatorInterface $locator)
34
    {
35
        $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...
36
    }
37
38
    public function getServiceLocator()
39
    {
40
        
41
        return $this->serviceLocator;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->serviceLocator; (PlaygroundGame\Controller\Admin\ServiceManager) is incompatible with the return type of the parent method Zend\Mvc\Controller\Abst...ller::getServiceLocator of type Zend\ServiceManager\ServiceLocatorInterface.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
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 Post & Vote form
61
        $this->forward()->dispatch(
62
            'PlaygroundCore\Controller\Formgen',
63
            array(
64
                'controller' => 'PlaygroundCore\Controller\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.

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.

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');
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
        $viewModel = new ViewModel();
96
        $viewModel->setTemplate($templatePath);
97
98
        $gameForm = new ViewModel();
99
        $gameForm->setTemplate('playground-game/game/game-form');
100
101
        $form   = $this->getServiceLocator()->get($formId);
102
        $form->setAttribute(
103
            'action',
104
            $this->url()->fromRoute(
105
                'admin/playgroundgame/edit-' . $this->game->getClassType(),
106
                array('gameId' => $this->game->getId())
107
            )
108
        );
109
        $form->setAttribute('method', 'post');
110
111
        if ($this->game->getFbAppId()) {
112
            $appIds = $form->get('fbAppId')->getOption('value_options');
113
            $appIds[$this->game->getFbAppId()] = $this->game->getFbAppId();
114
            $form->get('fbAppId')->setAttribute('options', $appIds);
115
        }
116
117
        $gameOptions = $this->getAdminGameService()->getOptions();
118
        $gameStylesheet = $gameOptions->getMediaPath() . '/' . 'stylesheet_'. $this->game->getId(). '.css';
119 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...
120
            $values = $form->get('stylesheet')->getValueOptions();
121
            $values[$gameStylesheet] = 'Style personnalisé de ce jeu';
122
123
            $form->get('stylesheet')->setAttribute('options', $values);
124
        }
125
126
        $form->bind($this->game);
127
128
        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...
129
            $data = array_replace_recursive(
130
                $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...
131
                $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...
132
            );
133
            if (empty($data['prizes'])) {
134
                $data['prizes'] = array();
135
            }
136
            if (isset($data['drawDate']) && $data['drawDate']) {
137
                $data['drawDate'] = \DateTime::createFromFormat('d/m/Y', $data['drawDate']);
138
            }
139
            $result = $this->getAdminGameService()->createOrUpdate($data, $this->game, $formId);
140
141
            if ($result) {
142
                return $this->redirect()->toRoute('admin/playgroundgame/list');
143
            }
144
        }
145
146
        $gameForm->setVariables(array('form' => $form, 'game' => $this->game));
147
        $viewModel->addChild($gameForm, 'game_form');
148
149
        return $viewModel->setVariables(
150
            array(
151
                'form' => $form,
152
                'title' => 'Edit this game',
153
            )
154
        );
155
    }
156
157
    public function listAction()
158
    {
159
        $filter    = $this->getEvent()->getRouteMatch()->getParam('filter');
160
        $type    = $this->getEvent()->getRouteMatch()->getParam('type');
161
162
        $service    = $this->getAdminGameService();
163
        $adapter = new DoctrineAdapter(new ORMPaginator($service->getQueryGamesOrderBy($type, $filter)));
164
        $paginator = new Paginator($adapter);
165
        $paginator->setItemCountPerPage(25);
166
        $paginator->setCurrentPageNumber($this->getEvent()->getRouteMatch()->getParam('p'));
167
168
        foreach ($paginator as $game) {
169
            $game->entry = $service->getEntryMapper()->countByGame($game);
170
        }
171
172
        return array(
173
            'games'    => $paginator,
174
            'type'        => $type,
175
            'filter'    => $filter,
176
        );
177
    }
178
179
    public function entryAction()
180
    {
181
        $this->checkGame();
182
183
        $adapter = new DoctrineAdapter(
184
            new LargeTablePaginator(
185
                $this->getAdminGameService()->getEntriesQuery($this->game)
186
            )
187
        );
188
        $paginator = new Paginator($adapter);
189
        $paginator->setItemCountPerPage(10);
190
        $paginator->setCurrentPageNumber($this->getEvent()->getRouteMatch()->getParam('p'));
191
192
        $header = $this->getAdminGameService()->getEntriesHeader($this->game);
193
        $entries = $this->getAdminGameService()->getGameEntries($header, $paginator, $this->game);
194
195
        return array(
196
            'paginator' => $paginator,
197
            'entries' => $entries,
198
            'header' => $header,
199
            'game' => $this->game,
200
            'gameId' => $this->game->getId()
201
        );
202
    }
203
204 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...
205
    {
206
        $this->checkGame();
207
208
        $adapter = new DoctrineAdapter(
209
            new LargeTablePaginator(
210
                $this->getAdminGameService()->getInvitationMapper()->queryByGame($this->game)
211
            )
212
        );
213
        $paginator = new Paginator($adapter);
214
        $paginator->setItemCountPerPage(25);
215
        $paginator->setCurrentPageNumber($this->getEvent()->getRouteMatch()->getParam('p'));
216
217
        return new ViewModel(
218
            array(
219
                'invitations' => $paginator,
220
                'gameId'      => $this->game->getId(),
221
                'game'        => $this->game,
222
            )
223
        );
224
    }
225
226
    public function removeInvitationAction()
227
    {
228
        $this->checkGame();
229
230
        $service = $this->getAdminGameService();
231
        $invitationId = $this->getEvent()->getRouteMatch()->getParam('invitationId');
232
        if ($invitationId) {
233
            $invitation   = $service->getInvitationMapper()->findById($invitationId);
234
            $service->getInvitationMapper()->remove($invitation);
235
        }
236
237
        return $this->redirect()->toRoute(
238
            'admin/'. $this->game->getClassType() .'/invitation',
239
            array('gameId'=>$this->game->getId())
240
        );
241
    }
242
    
243
    public function downloadAction()
244
    {
245
        $this->checkGame();
246
        $header = $this->getAdminGameService()->getEntriesHeader($this->game);
247
        $query = $this->getAdminGameService()->getEntriesQuery($this->game);
248
249
        $content = "\xEF\xBB\xBF"; // UTF-8 BOM
250
        $content .= $this->getAdminGameService()->getCSV(
251
            $this->getAdminGameService()->getGameEntries(
252
                $header,
253
                $query->getResult(),
254
                $this->game
255
            )
256
        );
257
258
        $response = $this->getResponse();
259
        $headers = $response->getHeaders();
260
        $headers->addHeaderLine('Content-Encoding: UTF-8');
261
        $headers->addHeaderLine('Content-Type', 'text/csv; charset=UTF-8');
262
        $headers->addHeaderLine('Content-Disposition', "attachment; filename=\"entry.csv\"");
263
        $headers->addHeaderLine('Accept-Ranges', 'bytes');
264
        $headers->addHeaderLine('Content-Length', strlen($content));
265
266
        $response->setContent($content);
267
268
        return $response;
269
    }
270
271
    // Only used for Quiz and Lottery
272
    public function drawAction()
273
    {
274
        $this->checkGame();
275
276
        $winningEntries = $this->getAdminGameService()->draw($this->game);
277
278
        $content = "\xEF\xBB\xBF"; // UTF-8 BOM
279
        $content .= "ID;Pseudo;Nom;Prenom;E-mail;Etat\n";
280
281
        foreach ($winningEntries as $e) {
282
            $etat = 'gagnant';
283
284
            $content   .= $e->getUser()->getId()
285
            . ";" . $e->getUser()->getUsername()
286
            . ";" . $e->getUser()->getLastname()
287
            . ";" . $e->getUser()->getFirstname()
288
            . ";" . $e->getUser()->getEmail()
289
            . ";" . $etat
290
            ."\n";
291
        }
292
293
        $response = $this->getResponse();
294
        $headers = $response->getHeaders();
295
        $headers->addHeaderLine('Content-Encoding: UTF-8');
296
        $headers->addHeaderLine('Content-Type', 'text/csv; charset=UTF-8');
297
        $headers->addHeaderLine('Content-Disposition', "attachment; filename=\"gagnants.csv\"");
298
        $headers->addHeaderLine('Accept-Ranges', 'bytes');
299
        $headers->addHeaderLine('Content-Length', strlen($content));
300
301
        $response->setContent($content);
302
303
        return $response;
304
    }
305
    
306
    /**
307
     * This method serialize a game an export it as a txt file
308
     * @return \Zend\Stdlib\ResponseInterface
309
     */
310
    public function exportAction()
311
    {
312
        $this->checkGame();
313
        $content = serialize($this->game);
314
315
        $response = $this->getResponse();
316
        $headers = $response->getHeaders();
317
        $headers->addHeaderLine('Content-Encoding: UTF-8');
318
        $headers->addHeaderLine('Content-Type', 'text/plain; charset=UTF-8');
319
        $headers->addHeaderLine(
320
            'Content-Disposition',
321
            "attachment; filename=\"". $this->game->getIdentifier() .".txt\""
322
        );
323
        $headers->addHeaderLine('Accept-Ranges', 'bytes');
324
        $headers->addHeaderLine('Content-Length', strlen($content));
325
    
326
        $response->setContent($content);
327
    
328
        return $response;
329
    }
330
    
331
    /**
332
     * This method take an uploaded txt file containing a serialized game
333
     * and persist it in the database
334
     * @return unknown
335
     */
336
    public function importAction()
337
    {
338
        $form = $this->getServiceLocator()->get('playgroundgame_import_form');
339
        $form->setAttribute('action', $this->url()->fromRoute('admin/playgroundgame/import'));
340
        $form->setAttribute('method', 'post');
341
        
342
        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...
343
            $data = array_replace_recursive(
344
                $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...
345
                $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...
346
            );
347
            
348
            if (! empty($data['import_file']['tmp_name'])) {
349
                ErrorHandler::start();
350
                $game = unserialize(file_get_contents($data['import_file']['tmp_name']));
351
                $game->setId(null);
352
                if ($data['slug']) {
353
                    $game->setIdentifier($data['slug']);
354
                }
355
                $duplicate = $this->getAdminGameService()->getGameMapper()->findByIdentifier($game->getIdentifier());
356
                if (!$duplicate) {
357
                    $this->getAdminGameService()->getGameMapper()->insert($game);
358
                }
359
360
                ErrorHandler::stop(true);
361
            }
362
            
363
            return $this->redirect()->toRoute('admin/playgroundgame/list');
364
        }
365
        
366
        return array(
367
            'form' => $form,
368
        );
369
    }
370
371
    public function removeAction()
372
    {
373
        $this->checkGame();
374
375
        try {
376
            $this->getAdminGameService()->getGameMapper()->remove($this->game);
377
            $this->flashMessenger()->setNamespace('playgroundgame')->addMessage('The game has been edited');
378
        } catch (\Doctrine\DBAL\DBALException $e) {
379
            $this->flashMessenger()->setNamespace('playgroundgame')->addMessage(
380
                'Il y a déjà eu des participants à ce jeu. Vous ne pouvez plus le supprimer'
381
            );
382
        }
383
384
        return $this->redirect()->toRoute('admin/playgroundgame/list');
385
    }
386
387
    public function setActiveAction()
388
    {
389
        $this->checkGame();
390
391
        $this->game->setActive(!$this->game->getActive());
392
        $this->getAdminGameService()->getGameMapper()->update($this->game);
393
394
        return $this->redirect()->toRoute('admin/playgroundgame/list');
395
    }
396
397
    public function formAction()
398
    {
399
        $this->checkGame();
400
        
401
        $form = $this->game->getPlayerForm();
402
403
        return $this->createForm($form);
404
    }
405
406
    public function setOptions(ModuleOptions $options)
407
    {
408
        $this->options = $options;
409
410
        return $this;
411
    }
412
413
    public function getOptions()
414
    {
415
        if (!$this->options instanceof ModuleOptions) {
416
            $this->setOptions($this->getServiceLocator()->get('playgroundgame_module_options'));
417
        }
418
419
        return $this->options;
420
    }
421
422
    public function getAdminGameService()
423
    {
424
        if (!$this->adminGameService) {
425
            $this->adminGameService = $this->getServiceLocator()->get('playgroundgame_game_service');
426
        }
427
428
        return $this->adminGameService;
429
    }
430
431
    public function setAdminGameService(AdminGameService $adminGameService)
432
    {
433
        $this->adminGameService = $adminGameService;
434
435
        return $this;
436
    }
437
}
438