Completed
Push — develop ( 034c89...77bab4 )
by greg
03:35
created

Game::getGameUserMediaUrl()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 7
Ratio 100 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 7
loc 7
rs 9.4285
cc 1
eloc 4
nc 1
nop 2
1
<?php
2
namespace PlaygroundGame\Service;
3
4
use PlaygroundGame\Entity\Entry;
5
use Zend\Session\Container;
6
use Zend\ServiceManager\ServiceManagerAwareInterface;
7
use Zend\ServiceManager\ServiceManager;
8
use ZfcBase\EventManager\EventProvider;
9
use PlaygroundGame\Options\ModuleOptions;
10
use PlaygroundGame\Mapper\GameInterface as GameMapperInterface;
11
use DoctrineModule\Validator\NoObjectExists as NoObjectExistsValidator;
12
use Zend\Validator\File\Size;
13
use Zend\Validator\File\IsImage;
14
use Zend\Stdlib\ErrorHandler;
15
use PlaygroundCore\Filter\Sanitize;
16
use Zend\Form\Element;
17
use Zend\Form\Form;
18
use Zend\InputFilter\Factory as InputFactory;
19
20
class Game extends EventProvider implements ServiceManagerAwareInterface
21
{
22
    /**
23
     *
24
     * @var GameMapperInterface
25
     */
26
    protected $gameMapper;
27
28
    /**
29
     *
30
     * @var EntryMapperInterface
31
     */
32
    protected $entryMapper;
33
34
    /**
35
     *
36
     * @var ServiceManager
37
     */
38
    protected $serviceManager;
39
40
    /**
41
     *
42
     * @var UserServiceOptionsInterface
43
     */
44
    protected $options;
45
46
    protected $playerformMapper;
47
48
    protected $invitationMapper;
49
50
    protected $userMapper;
51
    
52
    protected $anonymousIdentifier = null;
53
54 View Code Duplication
    public function getGameUserPath($game, $user)
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...
55
    {
56
        $path = $this->getOptions()->getMediaPath() . DIRECTORY_SEPARATOR;
57
        $path .= 'game' . $game->getId() . DIRECTORY_SEPARATOR;
58
        if (!is_dir($path)) {
59
            mkdir($path, 0777, true);
60
        }
61
        $path .= 'user'. $user->getId() . DIRECTORY_SEPARATOR;
62
        if (!is_dir($path)) {
63
            mkdir($path, 0777, true);
64
        }
65
66
        return $path;
67
    }
68
69 View Code Duplication
    public function getGameUserMediaUrl($game, $user)
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...
70
    {
71
        $media_url = $this->getOptions()->getMediaUrl() . '/';
72
        $media_url .= 'game' . $game->getId() . '/' . 'user'. $user->getId() . '/';
73
74
        return $media_url;
75
    }
76
77
    /**
78
     *
79
     *
80
     * This service is ready for all types of games
81
     *
82
     * @param array $data
83
     * @param string $formClass
84
     * @return \PlaygroundGame\Entity\Game
85
     */
86
    public function createOrUpdate(array $data, $game, $formClass)
87
    {
88
        $entityManager = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
89
90
        $form = $this->getServiceManager()->get($formClass);
91
        $form->get('publicationDate')->setOptions(array(
92
            'format' => 'Y-m-d H:i:s'
93
        ));
94
        $form->get('startDate')->setOptions(array(
95
            'format' => 'Y-m-d H:i:s'
96
        ));
97
        $form->get('endDate')->setOptions(array(
98
            'format' => 'Y-m-d H:i:s'
99
        ));
100
        $form->get('closeDate')->setOptions(array(
101
            'format' => 'Y-m-d H:i:s'
102
        ));
103
104
        $form->bind($game);
105
106
        $path = $this->getOptions()->getMediaPath() . '/';
107
        $media_url = $this->getOptions()->getMediaUrl() . '/';
108
109
        $identifierInput = $form->getInputFilter()->get('identifier');
110
        $noObjectExistsValidator = new NoObjectExistsValidator(array(
111
            'object_repository' => $entityManager->getRepository('PlaygroundGame\Entity\Game'),
112
            'fields' => 'identifier',
113
            'messages' => array(
114
                'objectFound' => 'This url already exists !'
115
            )
116
        ));
117
118
        if ($game->getIdentifier() != $data['identifier']) {
119
            $identifierInput->getValidatorChain()->addValidator($noObjectExistsValidator);
120
        }
121
122
        // I must switch from original format to the Y-m-d format because
123
        // this is the only one accepted by new DateTime($value)
124 View Code Duplication
        if (isset($data['publicationDate']) && $data['publicationDate']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
125
            $tmpDate = \DateTime::createFromFormat('d/m/Y H:i:s', $data['publicationDate']);
126
            $data['publicationDate'] = $tmpDate->format('Y-m-d H:i:s');
127
        }
128 View Code Duplication
        if (isset($data['startDate']) && $data['startDate']) {
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...
129
            $tmpDate = \DateTime::createFromFormat('d/m/Y H:i:s', $data['startDate']);
130
            $data['startDate'] = $tmpDate->format('Y-m-d H:i:s');
131
        }
132 View Code Duplication
        if (isset($data['endDate']) && $data['endDate']) {
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...
133
            $tmpDate = \DateTime::createFromFormat('d/m/Y H:i:s', $data['endDate']);
134
            $data['endDate'] = $tmpDate->format('Y-m-d H:i:s');
135
        }
136 View Code Duplication
        if (isset($data['closeDate']) && $data['closeDate']) {
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...
137
            $tmpDate = \DateTime::createFromFormat('d/m/Y H:i:s', $data['closeDate']);
138
            $data['closeDate'] = $tmpDate->format('Y-m-d H:i:s');
139
        }
140
141
        // If publicationDate is null, I update it with the startDate if not null neither
142
        if ((! isset($data['publicationDate']) || $data['publicationDate'] == '') &&
143
            (isset($data['startDate']) && $data['startDate'] != '')
144
        ) {
145
            $data['publicationDate'] = $data['startDate'];
146
        }
147
148
        // If the identifier has not been set, I use the title to create one.
149 View Code Duplication
        if ((! isset($data['identifier']) || empty($data['identifier'])) && isset($data['title'])) {
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...
150
            $data['identifier'] = $data['title'];
151
        }
152
153
        $form->setData($data);
154
155
        // If someone want to claim... It's time to do it ! used for exemple by PlaygroundFacebook Module
156
        $result = $this->getEventManager()->trigger(__FUNCTION__ . '.validate', $this, array(
157
            'game' => $game,
158
            'data' => $data
159
        ));
160
        if (is_array($result) && ! $result[0]) {
161
            $form->get('fbAppId')->setMessages(array(
162
                'Vous devez d\'abord désinstaller l\'appli Facebook'
163
            ));
164
165
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by PlaygroundGame\Service\Game::createOrUpdate of type PlaygroundGame\Entity\Game.

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...
166
        }
167
168
        if (! $form->isValid()) {
169 View Code Duplication
            if (isset($data['publicationDate']) && $data['publicationDate']) {
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...
170
                $tmpDate = \DateTime::createFromFormat('Y-m-d H:i:s', $data['publicationDate']);
171
                $data['publicationDate'] = $tmpDate->format('d/m/Y H:i:s');
172
                $form->setData(array(
173
                    'publicationDate' => $data['publicationDate']
174
                ));
175
            }
176 View Code Duplication
            if (isset($data['startDate']) && $data['startDate']) {
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...
177
                $tmpDate = \DateTime::createFromFormat('Y-m-d H:i:s', $data['startDate']);
178
                $data['startDate'] = $tmpDate->format('d/m/Y H:i:s');
179
                $form->setData(array(
180
                    'startDate' => $data['startDate']
181
                ));
182
            }
183 View Code Duplication
            if (isset($data['endDate']) && $data['endDate']) {
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...
184
                $tmpDate = \DateTime::createFromFormat('Y-m-d H:i:s', $data['endDate']);
185
                $data['endDate'] = $tmpDate->format('d/m/Y H:i:s');
186
                $form->setData(array(
187
                    'endDate' => $data['endDate']
188
                ));
189
            }
190 View Code Duplication
            if (isset($data['closeDate']) && $data['closeDate']) {
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...
191
                $tmpDate = \DateTime::createFromFormat('Y-m-d H:i:s', $data['closeDate']);
192
                $data['closeDate'] = $tmpDate->format('d/m/Y H:i:s');
193
                $form->setData(array(
194
                    'closeDate' => $data['closeDate']
195
                ));
196
            }
197
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by PlaygroundGame\Service\Game::createOrUpdate of type PlaygroundGame\Entity\Game.

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...
198
        }
199
200
        $game = $form->getData();
201
        $game = $this->getGameMapper()->insert($game);
202
203
        // I wait for the game to be saved to obtain its ID.
204 View Code Duplication
        if (! empty($data['uploadMainImage']['tmp_name'])) {
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...
205
            ErrorHandler::start();
206
            $data['uploadMainImage']['name'] = $this->fileNewname(
207
                $path,
208
                $game->getId() . "-" . $data['uploadMainImage']['name']
209
            );
210
            move_uploaded_file($data['uploadMainImage']['tmp_name'], $path . $data['uploadMainImage']['name']);
211
            $game->setMainImage($media_url . $data['uploadMainImage']['name']);
212
            ErrorHandler::stop(true);
213
        }
214
215 View Code Duplication
        if (isset($data['deleteMainImage']) &&
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...
216
            $data['deleteMainImage'] &&
217
            empty($data['uploadMainImage']['tmp_name'])
218
        ) {
219
            ErrorHandler::start();
220
            $image = $game->getMainImage();
221
            $image = str_replace($media_url, '', $image);
222
            unlink($path . $image);
223
            $game->setMainImage(null);
224
            ErrorHandler::stop(true);
225
        }
226
227 View Code Duplication
        if (! empty($data['uploadSecondImage']['tmp_name'])) {
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...
228
            ErrorHandler::start();
229
            $data['uploadSecondImage']['name'] = $this->fileNewname(
230
                $path,
231
                $game->getId() . "-" . $data['uploadSecondImage']['name']
232
            );
233
            move_uploaded_file($data['uploadSecondImage']['tmp_name'], $path . $data['uploadSecondImage']['name']);
234
            $game->setSecondImage($media_url . $data['uploadSecondImage']['name']);
235
            ErrorHandler::stop(true);
236
        }
237
238 View Code Duplication
        if (isset($data['deleteSecondImage']) &&
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...
239
            $data['deleteSecondImage'] &&
240
            empty($data['uploadSecondImage']['tmp_name'])
241
        ) {
242
            ErrorHandler::start();
243
            $image = $game->getSecondImage();
244
            $image = str_replace($media_url, '', $image);
245
            unlink($path . $image);
246
            $game->setSecondImage(null);
247
            ErrorHandler::stop(true);
248
        }
249
250
        if (! empty($data['uploadStylesheet']['tmp_name'])) {
251
            ErrorHandler::start();
252
            move_uploaded_file($data['uploadStylesheet']['tmp_name'], $path . 'stylesheet_' . $game->getId() . '.css');
253
            $game->setStylesheet($media_url . 'stylesheet_' . $game->getId() . '.css');
254
            ErrorHandler::stop(true);
255
        }
256
257 View Code Duplication
        if (! empty($data['uploadFbShareImage']['tmp_name'])) {
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...
258
            ErrorHandler::start();
259
            $data['uploadFbShareImage']['name'] = $this->fileNewname(
260
                $path,
261
                $game->getId() . "-" . $data['uploadFbShareImage']['name']
262
            );
263
            move_uploaded_file($data['uploadFbShareImage']['tmp_name'], $path . $data['uploadFbShareImage']['name']);
264
            $game->setFbShareImage($media_url . $data['uploadFbShareImage']['name']);
265
            ErrorHandler::stop(true);
266
        }
267
268 View Code Duplication
        if (isset($data['deleteFbShareImage']) &&
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...
269
            $data['deleteFbShareImage'] &&
270
            empty($data['uploadFbShareImage']['tmp_name'])
271
        ) {
272
            ErrorHandler::start();
273
            $image = $game->getFbShareImage();
274
            $image = str_replace($media_url, '', $image);
275
            unlink($path . $image);
276
            $game->setFbShareImage(null);
277
            ErrorHandler::stop(true);
278
        }
279
280
        if (! empty($data['uploadFbPageTabImage']['tmp_name'])) {
281
            ErrorHandler::start();
282
            $extension = $this->getExtension(strtolower($data['uploadFbPageTabImage']['name']));
283
            $src = $this->getSrc($extension, $data['uploadFbPageTabImage']['tmp_name']);
284
            $this->resize(
285
                $data['uploadFbPageTabImage']['tmp_name'],
286
                $extension,
287
                $path . $game->getId() . "-" . $data['uploadFbPageTabImage']['name'],
288
                $src,
289
                111,
290
                74
291
            );
292
293
            $game->setFbPageTabImage($media_url . $game->getId() . "-" . $data['uploadFbPageTabImage']['name']);
294
            ErrorHandler::stop(true);
295
        }
296
297 View Code Duplication
        if (isset($data['deleteFbPageTabImage']) &&
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...
298
            $data['deleteFbPageTabImage'] &&
299
            empty($data['uploadFbPageTabImage']['tmp_name'])
300
        ) {
301
            ErrorHandler::start();
302
            $image = $game->getFbPageTabImage();
303
            $image = str_replace($media_url, '', $image);
304
            unlink($path . $image);
305
            $game->setFbPageTabImage(null);
306
            ErrorHandler::stop(true);
307
        }
308
309
        $game = $this->getGameMapper()->update($game);
310
311
        $prize_mapper = $this->getServiceManager()->get('playgroundgame_prize_mapper');
312
        if (isset($data['prizes'])) {
313
            foreach ($data['prizes'] as $prize_data) {
314
                if (! empty($prize_data['picture_file']['tmp_name']) && ! $prize_data['picture_file']['error']) {
315
                    if ($prize_data['id']) {
316
                        $prize = $prize_mapper->findById($prize_data['id']);
317
                    } else {
318
                        $some_prizes = $prize_mapper->findBy(array(
319
                            'game' => $game,
320
                            'title' => $prize_data['title']
321
                        ));
322
                        if (count($some_prizes) == 1) {
323
                            $prize = $some_prizes[0];
324
                        } else {
325
                            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by PlaygroundGame\Service\Game::createOrUpdate of type PlaygroundGame\Entity\Game.

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...
326
                        }
327
                    }
328
                    // Remove if existing image
329
                    if ($prize->getPicture() && file_exists($prize->getPicture())) {
330
                        unlink($prize->getPicture());
331
                        $prize->getPicture(null);
332
                    }
333
                    // Upload and set new
334
                    ErrorHandler::start();
335
                    $filename = "game-" . $game->getId() . "-prize-";
336
                    $filename .= $prize->getId() . "-" . $prize_data['picture_file']['name'];
337
                    move_uploaded_file($prize_data['picture_file']['tmp_name'], $path . $filename);
338
                    $prize->setPicture($media_url . $filename);
339
                    ErrorHandler::stop(true);
340
                    $prize_mapper->update($prize);
341
                }
342
            }
343
        }
344
        // If I receive false, it means that the FB Id was not available anymore
345
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
346
            'game' => $game
347
        ));
348
349
        return $game;
350
    }
351
    
352
    /**
353
     * getActiveGames
354
     *
355
     * @return Array of PlaygroundGame\Entity\Game
356
     */
357
    public function getActiveGames($displayHome = true, $classType = '', $order = '')
358
    {
359
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
360
        $today = new \DateTime("now");
361
        $today = $today->format('Y-m-d H:i:s');
362
        $orderBy = 'g.publicationDate';
363
        if ($order != '') {
364
            $orderBy = 'g.'.$order;
365
        }
366
367
        $qb = $em->createQueryBuilder();
368
        $and = $qb->expr()->andx();
369
        $and->add(
370
            $qb->expr()->orX(
371
                $qb->expr()->lte('g.publicationDate', ':date'),
372
                $qb->expr()->isNull('g.publicationDate')
373
            )
374
        );
375
        $and->add(
376
            $qb->expr()->orX(
377
                $qb->expr()->gte('g.closeDate', ':date'),
378
                $qb->expr()->isNull('g.closeDate')
379
            )
380
        );
381
        $qb->setParameter('date', $today);
382
        
383
        $and->add($qb->expr()->eq('g.active', '1'));
384
        $and->add($qb->expr()->eq('g.broadcastPlatform', '1'));
385
        
386
        if ($classType != '') {
387
            $and->add($qb->expr()->eq('g.classType', ':classType'));
388
            $qb->setParameter('classType', $classType);
389
        }
390
        
391
        if ($displayHome) {
392
            $and->add($qb->expr()->eq('g.displayHome', true));
393
        }
394
        
395
        $qb->select('g')
396
        ->from('PlaygroundGame\Entity\Game', 'g')
397
        ->where($and)
398
        ->orderBy($orderBy, 'DESC');
399
        
400
        $query = $qb->getQuery();
401
        $games = $query->getResult();
402
        
403
        // je les classe par date de publication (date comme clé dans le tableau afin de pouvoir merger les objets
404
        // de type article avec le même procédé en les classant naturellement par date asc ou desc
405
        $arrayGames = array();
406 View Code Duplication
        foreach ($games as $game) {
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...
407
            if ($game->getPublicationDate()) {
408
                $key = $game->getPublicationDate()->format('Ymd');
409
            } elseif ($game->getStartDate()) {
410
                $key = $game->getStartDate()->format('Ymd');
411
            } else {
412
                $key = $game->getUpdatedAt()->format('Ymd');
413
            }
414
            $key .= $game->getUpdatedAt()->format('Ymd') . '-' . $game->getId();
415
            $arrayGames[$key] = $game;
416
        }
417
418
        return $arrayGames;
419
    }
420
421
    /**
422
     * getAvailableGames : Games OnLine and not already played by $user
423
     *
424
     * @return Array of PlaygroundGame\Entity\Game
425
     */
426
    public function getAvailableGames($user, $maxResults = 2)
427
    {
428
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
429
        $today = new \DateTime("now");
430
        $today = $today->format('Y-m-d H:i:s');
431
432
        // Game active with a start_date before today (or without start_date)
433
        // and end_date after today (or without end-date)
434
        $query = $em->createQuery('SELECT g FROM PlaygroundGame\Entity\Game g
435
                WHERE NOT EXISTS (SELECT l FROM PlaygroundGame\Entity\Entry l WHERE l.game = g AND l.user = :user)
436
                AND (g.startDate <= :date OR g.startDate IS NULL)
437
                AND (g.endDate >= :date OR g.endDate IS NULL)
438
                AND g.active = 1 AND g.broadcastPlatform = 1
439
                ORDER BY g.startDate ASC');
440
        $query->setParameter('date', $today);
441
        $query->setParameter('user', $user);
442
        $query->setMaxResults($maxResults);
443
        $games = $query->getResult();
444
445
        return $games;
446
    }
447
448 View Code Duplication
    public function getEntriesQuery($game)
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...
449
    {
450
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
451
452
        $qb = $em->createQueryBuilder();
453
        $qb->select('
454
            e.id,
455
            u.username,
456
            u.title,
457
            u.firstname,
458
            u.lastname,
459
            u.email,
460
            u.optin,
461
            u.optinPartner,
462
            u.address,
463
            u.address2,
464
            u.postalCode,
465
            u.city,
466
            u.country,
467
            u.telephone,
468
            u.mobile,
469
            u.created_at,
470
            u.dob,
471
            e.winner,
472
            e.socialShares,
473
            e.playerData,
474
            e.updated_at
475
            ')
476
            ->from('PlaygroundGame\Entity\Entry', 'e')
477
            ->leftJoin('e.user', 'u')
478
            ->where($qb->expr()->eq('e.game', ':game'));
479
        
480
        $qb->setParameter('game', $game);
481
482
        return $qb->getQuery();
483
    }
484
485
    public function getEntriesHeader($game)
486
    {
487
        if ($game->getPlayerForm()) {
488
            $formPV = json_decode($game->getPlayerForm()->getForm(), true);
489
            $header = array('id'=> 1);
490 View Code Duplication
            foreach ($formPV as $element) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
491
                foreach ($element as $k => $v) {
492
                    if ($k !== 'form_properties') {
493
                        $header[$v[0]['name']] = 1;
494
                    }
495
                }
496
            }
497
        } else {
498
            $header = array(
499
                'id' => 1,
500
                'username' => 1,
501
                'title' => 1,
502
                'firstname' => 1,
503
                'lastname' => 1,
504
                'email' => 1,
505
                'optin' => 1,
506
                'optinPartner' => 1,
507
                'address' => 1,
508
                'address2' => 1,
509
                'postalCode' => 1,
510
                'city' => 1,
511
                'country' => 1,
512
                'telephone' => 1,
513
                'mobile' => 1,
514
                'created_at' => 1,
515
                'dob' => 1,
516
                'winner' => 1
517
            );
518
        }
519
        $header['winner'] = 1;
520
        $header['socialShares'] = 1;
521
        $header['updated_at'] = 1;
522
523
        return $header;
524
    }
525
526
    /**
527
    * getGameEntries : I create an array of entries based on playerData + header
528
    *
529
    * @return Array of PlaygroundGame\Entity\Game
530
    */
531
    public function getGameEntries($header, $entries, $game)
532
    {
533
        $header = $this->getEntriesHeader($game);
534
535
        $results = array();
536
537
        foreach ($entries as $k => $entry) {
538
            $entryData = json_decode($entry['playerData'], true);
539 View Code Duplication
            foreach ($header as $key => $v) {
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...
540
                if (isset($entryData[$key])) {
541
                    $results[$k][$key] = (is_array($entryData[$key]))?implode(', ', $entryData[$key]):$entryData[$key];
542
                } elseif (array_key_exists($key, $entry)) {
543
                    $results[$k][$key] = ($entry[$key] instanceof \DateTime)?
544
                        $entry[$key]->format('Y-m-d H:i:s'):
545
                        $entry[$key];
546
                } else {
547
                    $results[$k][$key] = '';
548
                }
549
            }
550
        }
551
552
        return $results;
553
    }
554
555
    /**
556
     * getActiveSliderGames
557
     *
558
     * @return Array of PlaygroundGame\Entity\Game
559
     */
560
    public function getActiveSliderGames()
561
    {
562
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
563
        $today = new \DateTime("now");
564
        $today = $today->format('Y-m-d H:i:s');
565
566
        // Game active with a start_date before today (or without start_date)
567
        // and end_date after today (or without end-date)
568
        $query = $em->createQuery('SELECT g FROM PlaygroundGame\Entity\Game g
569
            WHERE (g.publicationDate <= :date OR g.publicationDate IS NULL)
570
            AND (g.closeDate >= :date OR g.closeDate IS NULL)
571
            AND g.active = true AND g.broadcastPlatform = 1 AND g.pushHome = true');
572
        $query->setParameter('date', $today);
573
        $games = $query->getResult();
574
575
        // je les classe par date de publication (date comme clé dans le tableau afin de pouvoir merger les objets
576
        // de type article avec le même procédé en les classant naturellement par date asc ou desc
577
        $arrayGames = array();
578 View Code Duplication
        foreach ($games as $game) {
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...
579
            if ($game->getPublicationDate()) {
580
                $key = $game->getPublicationDate()->format('Ymd');
581
            } elseif ($game->getStartDate()) {
582
                $key = $game->getStartDate()->format('Ymd');
583
            } else {
584
                $key = $game->getUpdatedAt()->format('Ymd');
585
            }
586
            $key .= $game->getUpdatedAt()->format('Ymd') . '-' . $game->getId();
587
            $arrayGames[$key] = $game;
588
        }
589
590
        return $arrayGames;
591
    }
592
593
    /**
594
     * getPrizeCategoryGames
595
     *
596
     * @return Array of PlaygroundGame\Entity\Game
597
     */
598 View Code Duplication
    public function getPrizeCategoryGames($categoryid)
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...
599
    {
600
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
601
602
        $query = $em->createQuery('SELECT g FROM PlaygroundGame\Entity\Game g
603
            WHERE (g.prizeCategory = :categoryid AND g.broadcastPlatform = 1)
604
            ORDER BY g.publicationDate DESC');
605
        $query->setParameter('categoryid', $categoryid);
606
        $games = $query->getResult();
607
608
        return $games;
609
    }
610
611
    public function checkGame($identifier, $checkIfStarted = true)
612
    {
613
        $gameMapper = $this->getGameMapper();
614
615
        if (! $identifier) {
616
            return false;
617
        }
618
619
        $game = $gameMapper->findByIdentifier($identifier);
620
621
        // the game has not been found
622
        if (! $game) {
623
            return false;
624
        }
625
626
        // for preview stuff as admin
627
        if ($this->isAllowed('game', 'edit')) {
628
            $r =$this->getServiceManager()->get('request');
629
            if ($r->getQuery()->get('preview')) {
630
                $game->setActive(true);
631
                $game->setStartDate(null);
632
                $game->setEndDate(null);
633
                $game->setPublicationDate(null);
634
                $game->setBroadcastPlatform(true);
635
636
                // I don't want the game to be updated through any update during the preview mode.
637
                // I mark it as readonly for Doctrine
638
                $this->getServiceManager()
639
                    ->get('doctrine.entitymanager.orm_default')
640
                    ->getUnitOfWork()
641
                    ->markReadOnly($game);
642
                    
643
                return $game;
644
            }
645
        }
646
647
        // The game is inactive
648
        if (! $game->getActive()) {
649
            return false;
650
        }
651
652
        // the game has not begun yet
653
        if (! $game->isOpen()) {
654
            return false;
655
        }
656
657
        // the game is finished and closed
658
        if (! $game->isStarted() && $checkIfStarted) {
659
            return false;
660
        }
661
662
        return $game;
663
    }
664
665
    /**
666
     * Return the last entry of the user on this game, if it exists.
667
     * An entry can be associated to :
668
     * - A user account (a real one, linked to PlaygroundUser
669
     * - An anonymous Identifier (based on one value of playerData (generally email))
670
     * - A cookie set on the player device (the less secure)
671
     * If the active param is set, it can check if the entry is active or not.
672
     * If the bonus param is set, it can check if the entry is a bonus or not.
673
     *
674
     * @param unknown $game
675
     * @param string $user
676
     * @param boolean $active
677
     * @param boolean $bonus
678
     * @return boolean
679
     */
680
    public function checkExistingEntry($game, $user = null, $active = null, $bonus = null)
681
    {
682
        $search = array('game'  => $game);
683
684
        if ($user) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $user of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
685
            $search['user'] = $user;
686
        } elseif ($this->getAnonymousIdentifier()) {
687
            $search['anonymousIdentifier'] = $this->getAnonymousIdentifier();
688
            $search['user'] = null;
689
        } else {
690
            $search['anonymousId'] = $this->getAnonymousId();
691
            $search['user'] = null;
692
        }
693
        
694
        if (! is_null($active)) {
695
            $search['active'] = $active;
696
        }
697
        if (! is_null($bonus)) {
698
            $search['bonus'] = $bonus;
699
        }
700
701
        $entry = $this->getEntryMapper()->findOneBy($search, array('updated_at' => 'desc'));
702
703
        return $entry;
704
    }
705
706
    /*
707
    * This function updates the entry with the player data after checking 
708
    * that the data are compliant with the formUser Game attribute
709
    *
710
    * The $data has to be a json object
711
    */
712
    public function updateEntryPlayerForm($data, $game, $user, $entry, $mandatory = true)
0 ignored issues
show
Unused Code introduced by
The parameter $user is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
713
    {
714
        $form = $this->createFormFromJson($game->getPlayerForm()->getForm(), 'playerForm');
715
        $form->setData($data);
716
717
        if (!$mandatory) {
718
            $filter = $form->getInputFilter();
719
            foreach ($form->getElements() as $element) {
720
                try {
721
                    $elementInput = $filter->get($element->getName());
722
                    $elementInput->setRequired(false);
0 ignored issues
show
Bug introduced by
The method setRequired does only exist in Zend\InputFilter\InputInterface, but not in Zend\InputFilter\InputFilterInterface.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
723
                    $form->get($element->getName())->setAttribute('required', false);
724
                } catch (\Zend\Form\Exception\InvalidElementException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
725
                }
726
            }
727
        }
728
729
        if ($form->isValid()) {
730
            $dataJson = json_encode($form->getData());
731
732
            if ($game->getAnonymousAllowed() &&
733
                $game->getAnonymousIdentifier() &&
734
                isset($data[$game->getAnonymousIdentifier()])
735
            ) {
736
                $session = new \Zend\Session\Container('anonymous_identifier');
737
                if (empty($session->offsetGet('anonymous_identifier'))) {
738
                    $anonymousIdentifier = $data[$game->getAnonymousIdentifier()];
739
                
740
                    $entry->setAnonymousIdentifier($anonymousIdentifier);
741
                
742
                    // I must transmit this info during the whole game workflow
743
                    $session->offsetSet('anonymous_identifier', $anonymousIdentifier);
744
                }
745
            }
746
747
            $entry->setPlayerData($dataJson);
748
            $this->getEntryMapper()->update($entry);
749
        } else {
750
            return false;
751
        }
752
753
        return true;
754
    }
755
756
757
    public function checkIsFan($game)
0 ignored issues
show
Unused Code introduced by
The parameter $game is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
758
    {
759
        // If on Facebook, check if you have to be a FB fan to play the game
760
        $session = new Container('facebook');
761
762
        if ($session->offsetExists('signed_request')) {
763
            // I'm on Facebook
764
            $sr = $session->offsetGet('signed_request');
765
            if ($sr['page']['liked'] == 1) {
766
                return true;
767
            }
768
        } else {
769
            // I'm not on Facebook
770
            return true;
771
        }
772
773
        return false;
774
    }
775
    
776
    public function getAnonymousIdentifier()
777
    {
778
        if (is_null($this->anonymousIdentifier)) {
779
            // If on Facebook, check if you have to be a FB fan to play the game
780
            $session = new Container('anonymous_identifier');
781
            
782
            if ($session->offsetExists('anonymous_identifier')) {
783
                $this->anonymousIdentifier = $session->offsetGet('anonymous_identifier');
784
            } else {
785
                $this->anonymousIdentifier = false;
786
            }
787
        }
788
    
789
        return $this->anonymousIdentifier;
790
    }
791
792
    /**
793
     * errors :
794
     * -1 : user not connected
795
     * -2 : limit entry games for this user reached
796
     *
797
     * @param \PlaygroundGame\Entity\Game $game
798
     * @param \PlaygroundUser\Entity\UserInterface $user
799
     * @return number unknown
800
     */
801
    public function play($game, $user)
802
    {
803
804
        // certaines participations peuvent rester ouvertes.
805
        // On autorise alors le joueur à reprendre là ou il en était
806
        // par exemple les postvote...
807
        $entry = $this->checkExistingEntry($game, $user, true);
0 ignored issues
show
Documentation introduced by
$user is of type object<PlaygroundUser\Entity\UserInterface>, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
808
809
        if (! $entry) {
810
            if ($this->hasReachedPlayLimit($game, $user)) {
811
                return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by PlaygroundGame\Service\Game::play of type integer|double.

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...
812
            }
813
814
            $entry = new Entry();
815
            $entry->setGame($game);
816
            $entry->setUser($user);
817
            $entry->setPoints(0);
818
            $entry->setIp($this->getIp());
819
            $entry->setAnonymousId($this->getAnonymousId());
820
            if ($this->getAnonymousIdentifier()) {
821
                $entry->setAnonymousIdentifier($this->getAnonymousIdentifier());
822
            }
823
824
            $entry = $this->getEntryMapper()->insert($entry);
825
            $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
826
                'user' => $user,
827
                'game' => $game,
828
                'entry' => $entry
829
            ));
830
        }
831
832
        return $entry;
833
    }
834
835
    /**
836
     * @param \PlaygroundGame\Entity\Game $game
837
     * @param \PlaygroundUser\Entity\UserInterface $user
838
     */
839
    public function hasReachedPlayLimit($game, $user)
840
    {
841
        // Is there a limitation on the game ?
842
        $limitAmount = $game->getPlayLimit();
843
        if ($limitAmount) {
844
            $limitScale = $game->getPlayLimitScale();
845
            $userEntries = $this->findLastEntries($game, $user, $limitScale);
846
847
            // player has reached the game limit
848
            if ($userEntries >= $limitAmount) {
849
                return true;
850
            }
851
        }
852
        return false;
853
    }
854
    
855
    /**
856
     * @param \PlaygroundGame\Entity\Game $game
857
     * @param \PlaygroundUser\Entity\UserInterface $user
858
     */
859
    public function findLastEntries($game, $user, $limitScale)
860
    {
861
        $limitDate = $this->getLimitDate($limitScale);
862
863
        if ($user) {
864
            return $this->getEntryMapper()->findLastEntriesByUser($game, $user, $limitDate);
865
        } elseif ($this->getAnonymousIdentifier()) {
866
            return $this->getEntryMapper()->findLastEntriesByAnonymousIdentifier(
867
                $game,
868
                $this->getAnonymousIdentifier(),
869
                $limitDate
870
            );
871
        } else {
872
            return $this->getEntryMapper()->findLastEntriesByIp($game, $this->getIp(), $limitDate);
873
        }
874
    }
875
876
    /**
877
    *
878
    *
879
    */
880
    public function getLimitDate($limitScale)
881
    {
882
        $now = new \DateTime("now");
883
        switch ($limitScale) {
884
            case 'always':
885
                $interval = 'P100Y';
886
                $now->sub(new \DateInterval($interval));
887
                $dateLimit = $now->format('Y-m-d H:i:s');
888
                break;
889 View Code Duplication
            case 'day':
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...
890
                $interval = 'P1D';
891
                $now->sub(new \DateInterval($interval));
892
                $dateLimit = $now->format('Y-m-d H:i:s');
893
                break;
894 View Code Duplication
            case 'week':
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...
895
                $interval = 'P7D';
896
                $now->sub(new \DateInterval($interval));
897
                $dateLimit = $now->format('Y-m-d H:i:s');
898
                break;
899 View Code Duplication
            case 'month':
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...
900
                $interval = 'P1M';
901
                $now->sub(new \DateInterval($interval));
902
                $dateLimit = $now->format('Y-m-d H:i:s');
903
                break;
904
            case 'year':
905
                $interval = 'P1Y';
906
                $now->sub(new \DateInterval($interval));
907
                $dateLimit = $now->format('Y-m-d H:i:s');
908
                break;
909
            default:
910
                $interval = 'P100Y';
911
                $now->sub(new \DateInterval($interval));
912
                $dateLimit = $now->format('Y-m-d H:i:s');
913
        }
914
915
        return $dateLimit;
916
    }
917
918
    public function findLastActiveEntry($game, $user)
919
    {
920
        return $this->checkExistingEntry($game, $user, true);
921
    }
922
923
    public function findLastInactiveEntry($game, $user)
924
    {
925
        return $this->checkExistingEntry($game, $user, false, false);
926
    }
927
928
    public function findLastEntry($game, $user)
929
    {
930
        return $this->checkExistingEntry($game, $user, null, false);
931
    }
932
933
    public function inviteToTeam($data, $game, $user)
934
    {
935
        $mailService = $this->getServiceManager()->get('playgroundgame_message');
936
        $invitationMapper = $this->getServiceManager()->get('playgroundgame_invitation_mapper');
937
938
        $sentInvitations = $invitationMapper->findBy(array('host' => $user, 'game' => $game));
939
        $nbInvitations = count($sentInvitations);
940
        $to = $data['email'];
941
        if (empty($to)) {
942
            return ['result'=>false, 'message'=>'no email'];
943
        }
944
945
        if ($nbInvitations < 20) {
946
            $alreadyInvited = $invitationMapper->findBy(array('requestKey' => $to, 'game' => $game));
947
            if (!$alreadyInvited) {
948
                $alreadyInvited = $this->getUserMapper()->findByEmail($to);
949
            }
950
951
            if (empty($alreadyInvited)) {
952
                $invitation = new \PlaygroundGame\Entity\Invitation();
953
                $invitation->setRequestKey($to);
954
                $invitation->setGame($game);
955
                $invitation->setHost($user);
956
                $invitationMapper->insert($invitation);
957
958
                $from = $this->getOptions()->getEmailFromAddress();
959
                $subject = $this->getServiceManager()->get('translator')->translate(
960
                    $this->getOptions()->getInviteToTeamSubjectLine(),
961
                    'playgroundgame'
962
                );
963
                $message = $mailService->createHtmlMessage(
964
                    $from,
965
                    $to,
966
                    $subject,
967
                    'playground-game/email/invite_team',
968
                    array(
969
                        'game' => $game,
970
                        'user' => $user,
971
                        'data' => $data,
972
                        'from' => $from
973
                    )
974
                );
975
                try {
976
                    $mailService->send($message);
977
                } catch (\Zend\Mail\Protocol\Exception\RuntimeException $e) {
978
                    return ['result' => true, 'message' => $this->getServiceManager()->get('translator')->translate(
979
                        'mail error'
980
                    )];
981
                }
982
983
                return ['result' => true, 'message' => ''];
984
            } else {
985
                return ['result' => false, 'message' => 'already invited'];
986
            }
987
        } else {
988
            return [
989
                'result' => false,
990
                'message' => $this->getServiceManager()->get('translator')->translate(
991
                    'Too many invitations for this user'
992
                )
993
            ];
994
        }
995
    }
996
997
    public function sendShareMail(
998
        $data,
999
        $game,
1000
        $user,
1001
        $entry,
1002
        $template = 'share_game',
1003
        $topic = null,
1004
        $userTimer = array(),
1005
        $subject = ''
1006
    ) {
1007
        $mailService = $this->getServiceManager()->get('playgroundgame_message');
1008
        $mailSent = false;
1009
        $from = $this->getOptions()->getEmailFromAddress();
1010
1011
        if (empty($subject)) {
1012
            $subject = $this->getServiceManager()->get('translator')->translate(
1013
                $this->getOptions()->getShareSubjectLine(),
1014
                'playgroundgame'
1015
            );
1016
        } else {
1017
            $subject = $this->getServiceManager()->get('translator')->translate(
1018
                $subject,
1019
                'playgroundgame'
1020
            );
1021
        }
1022
1023
        $renderer = $this->getServiceManager()->get('Zend\View\Renderer\RendererInterface');
1024
        $skinUrl = $renderer->url(
1025
            'frontend',
1026
            array(),
1027
            array('force_canonical' => true)
1028
        );
1029
        $secretKey = strtoupper(substr(sha1(uniqid('pg_', true) . '####' . time()), 0, 15));
1030
1031
        if (! $topic) {
1032
            $topic = $game->getTitle();
1033
        }
1034
1035
        if (isset($data['email']) && !is_array($data['email'])) {
1036
            $data['email'] = array($data['email']);
1037
        }
1038
        
1039
        foreach ($data['email'] as $to) {
1040
            $mailSent = true;
1041
            if (!empty($to)) {
1042
                $message = $mailService->createHtmlMessage(
1043
                    $from,
1044
                    $to,
1045
                    $subject,
1046
                    'playground-game/email/' . $template,
1047
                    array(
1048
                        'game' => $game,
1049
                        'data' => $data,
1050
                        'from' => $from,
1051
                        'to' => $to,
1052
                        'secretKey' => $secretKey,
1053
                        'skinUrl' => $skinUrl,
1054
                        'userTimer' => $userTimer
1055
                    )
1056
                );
1057
                try {
1058
                    $mailService->send($message);
1059
                } catch (\Zend\Mail\Protocol\Exception\RuntimeException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
1060
                }
1061
                
1062
                if ($entry) {
1063
                    $shares = json_decode($entry->getSocialShares(), true);
1064
                    (!isset($shares['mail']))? $shares['mail'] = 1:$shares['mail'] += 1;
1065
                }
1066
            }
1067
        }
1068
1069
        if ($mailSent) {
1070
            if ($entry) {
1071
                $sharesJson = json_encode($shares);
0 ignored issues
show
Bug introduced by
The variable $shares 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...
1072
                $entry->setSocialShares($sharesJson);
1073
                $entry = $this->getEntryMapper()->update($entry);
1074
            }
1075
            
1076
            $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1077
                'user' => $user,
1078
                'topic' => $topic,
1079
                'secretKey' => $secretKey,
1080
                'data' => $data,
1081
                'game' => $game,
1082
                'entry' => $entry
1083
            ));
1084
1085
            return true;
1086
        }
1087
1088
        return false;
1089
    }
1090
1091
    /**
1092
     * @param \PlaygroundGame\Entity\Game $game
1093
     * @param \PlaygroundUser\Entity\User $user
1094
     * @param Entry $entry
1095
     * @param \PlaygroundGame\Entity\Prize $prize
1096
     */
1097
    public function sendResultMail($game, $user, $entry, $template = 'entry', $prize = null)
1098
    {
1099
        $mailService = $this->getServiceManager()->get('playgroundgame_message');
1100
        $from = $this->getOptions()->getEmailFromAddress();
1101
        if ($user) {
1102
            $to = $user->getEmail();
1103
        } elseif ($entry->getAnonymousIdentifier()) {
1104
            $to = $entry->getAnonymousIdentifier();
1105
        } else {
1106
            return false;
1107
        }
1108
        $subject = $game->getTitle();
1109
        $renderer = $this->getServiceManager()->get('Zend\View\Renderer\RendererInterface');
1110
        $skinUrl = $renderer->url(
1111
            'frontend',
1112
            array(),
1113
            array('force_canonical' => true)
1114
        );
1115
        $message = $mailService->createHtmlMessage($from, $to, $subject, 'playground-game/email/' . $template, array(
1116
            'game' => $game,
1117
            'entry' => $entry,
1118
            'skinUrl' => $skinUrl,
1119
            'prize' => $prize
1120
        ));
1121
        $mailService->send($message);
1122
    }
1123
1124
    public function sendGameMail($game, $user, $post, $template = 'postvote')
1125
    {
1126
        $mailService = $this->getServiceManager()->get('playgroundgame_message');
1127
        $from = $this->getOptions()->getEmailFromAddress();
1128
        $to = $user->getEmail();
1129
        $subject = $this->getServiceManager()->get('translator')->translate(
1130
            $this->getOptions()->getParticipationSubjectLine(),
1131
            'playgroundgame'
1132
        );
1133
        $renderer = $this->getServiceManager()->get('Zend\View\Renderer\RendererInterface');
1134
        $skinUrl = $renderer->url(
1135
            'frontend',
1136
            array(),
1137
            array('force_canonical' => true)
1138
        );
1139
1140
        $message = $mailService->createHtmlMessage($from, $to, $subject, 'playground-game/email/' . $template, array(
1141
            'game' => $game,
1142
            'post' => $post,
1143
            'skinUrl' => $skinUrl
1144
        ));
1145
        $mailService->send($message);
1146
    }
1147
1148 View Code Duplication
    public function postFbWall($secretKey, $game, $user, $entry)
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...
1149
    {
1150
        $topic = $game->getTitle();
1151
        
1152
        $shares = json_decode($entry->getSocialShares(), true);
1153
        if (!isset($shares['fbwall'])) {
1154
            $shares['fbwall'] = 1;
1155
        } else {
1156
            $shares['fbwall'] += 1;
1157
        }
1158
        $sharesJson = json_encode($shares);
1159
        $entry->setSocialShares($sharesJson);
1160
        $entry = $this->getEntryMapper()->update($entry);
1161
        
1162
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1163
            'user' => $user,
1164
            'game' => $game,
1165
            'secretKey' => $secretKey,
1166
            'topic' => $topic,
1167
            'entry' => $entry
1168
        ));
1169
1170
        return true;
1171
    }
1172
1173
    public function postFbRequest($secretKey, $game, $user, $entry, $to)
1174
    {
1175
        $shares = json_decode($entry->getSocialShares(), true);
1176
        $to = explode(',', $to);
1177
        if (!isset($shares['fbrequest'])) {
1178
            $shares['fbrequest'] = count($to);
1179
        } else {
1180
            $shares['fbrequest'] += count($to);
1181
        }
1182
        $sharesJson = json_encode($shares);
1183
        $entry->setSocialShares($sharesJson);
1184
        $entry = $this->getEntryMapper()->update($entry);
1185
        
1186
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1187
            'user' => $user,
1188
            'game' => $game,
1189
            'secretKey' => $secretKey,
1190
            'entry' => $entry,
1191
            'invites' => count($to)
1192
        ));
1193
1194
        return true;
1195
    }
1196
1197 View Code Duplication
    public function postTwitter($secretKey, $game, $user, $entry)
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...
1198
    {
1199
        $topic = $game->getTitle();
1200
1201
        $shares = json_decode($entry->getSocialShares(), true);
1202
        if (!isset($shares['fbrequest'])) {
1203
            $shares['tweet'] = 1;
1204
        } else {
1205
            $shares['tweet'] += 1;
1206
        }
1207
        $sharesJson = json_encode($shares);
1208
        $entry->setSocialShares($sharesJson);
1209
        $entry = $this->getEntryMapper()->update($entry);
1210
        
1211
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1212
            'user' => $user,
1213
            'game' => $game,
1214
            'secretKey' => $secretKey,
1215
            'topic' => $topic,
1216
            'entry' => $entry
1217
        ));
1218
1219
        return true;
1220
    }
1221
1222 View Code Duplication
    public function postGoogle($secretKey, $game, $user, $entry)
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...
1223
    {
1224
        $topic = $game->getTitle();
1225
        
1226
        $shares = json_decode($entry->getSocialShares(), true);
1227
        if (!isset($shares['fbrequest'])) {
1228
            $shares['google'] = 1;
1229
        } else {
1230
            $shares['google'] += 1;
1231
        }
1232
        $sharesJson = json_encode($shares);
1233
        $entry->setSocialShares($sharesJson);
1234
        $entry = $this->getEntryMapper()->update($entry);
1235
1236
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1237
            'user' => $user,
1238
            'game' => $game,
1239
            'secretKey' => $secretKey,
1240
            'topic' => $topic,
1241
            'entry' => $entry
1242
        ));
1243
1244
        return true;
1245
    }
1246
1247
    /**
1248
     * Is it possible to trigger a bonus entry ?
1249
     *
1250
     * @param unknown_type $game
1251
     * @param unknown_type $user
1252
     */
1253
    public function allowBonus($game, $user)
1254
    {
1255
        if (! $game->getPlayBonus() || $game->getPlayBonus() == 'none') {
1256
            return false;
1257
        } elseif ($game->getPlayBonus() == 'one') {
1258
            if ($this->getEntryMapper()->findOneBy(array(
1259
                'game' => $game,
1260
                'user' => $user,
1261
                'bonus' => 1
1262
            ))) {
1263
                return false;
1264
            } else {
1265
                return true;
1266
            }
1267
        } elseif ($game->getPlayBonus() == 'per_entry') {
1268
            return $this->getEntryMapper()->checkBonusEntry($game, $user);
1269
        }
1270
1271
        return false;
1272
    }
1273
1274
    public function addAnotherEntry($game, $user, $winner = 0)
1275
    {
1276
        $entry = new Entry();
1277
        $entry->setGame($game);
1278
        $entry->setUser($user);
1279
        $entry->setPoints(0);
1280
        $entry->setIp($this->getIp());
1281
        $entry->setActive(0);
1282
        $entry->setBonus(1);
1283
        $entry->setWinner($winner);
1284
        $entry = $this->getEntryMapper()->insert($entry);
1285
1286
        return $entry;
1287
    }
1288
1289
    /**
1290
     * This bonus entry doesn't give points nor badges
1291
     * It's just there to increase the chances during the Draw
1292
     * Old Name playBonus
1293
     *
1294
     * @param PlaygroundGame\Entity\Game $game
1295
     * @param unknown $user
1296
     * @return boolean unknown
1297
     */
1298
    public function addAnotherChance($game, $user, $winner = 0)
1299
    {
1300
        if ($this->allowBonus($game, $user)) {
1301
            $this->addAnotherEntry($game, $user, $winner);
1302
1303
            return true;
1304
        }
1305
1306
        return false;
1307
    }
1308
1309
    /**
1310
     * This bonus entry doesn't give points nor badges but can play again
1311
     *
1312
     * @param PlaygroundGame\Entity\Game $game
1313
     * @param user $user
1314
     * @return boolean unknown
1315
     */
1316
    public function playAgain($game, $user, $winner = 0)
1317
    {
1318
        if ($this->allowBonus($game, $user)) {
1319
            $entry = $this->addAnotherEntry($game, $user, $winner);
1320
            $entry->setActive(1);
1321
            $entry = $this->getEntryMapper()->update($entry);
1322
            if ($entry->getActive() == 1) {
1323
                return true;
1324
            }
1325
        }
1326
1327
        return false;
1328
    }
1329
1330
    /**
1331
     * @param string $path
1332
     */
1333
    public function uploadFile($path, $file)
1334
    {
1335
        $err = $file["error"];
1336
        $message = '';
1337
        if ($err > 0) {
1338
            switch ($err) {
1339
                case '1':
1340
                    $message .= 'Max file size exceeded. (php.ini)';
1341
                    break;
1342
                case '2':
1343
                    $message .= 'Max file size exceeded.';
1344
                    break;
1345
                case '3':
1346
                    $message .= 'File upload was only partial.';
1347
                    break;
1348
                case '4':
1349
                    $message .= 'No file was attached.';
1350
                    break;
1351
                case '7':
1352
                    $message .= 'File permission denied.';
1353
                    break;
1354
                default:
1355
                    $message .= 'Unexpected error occurs.';
1356
            }
1357
1358
            return $err;
1359
        } else {
1360
            $fileNewname = $this->fileNewname($path, $file['name'], true);
1361
1362
            if (isset($file["base64"])) {
1363
                list(, $img) = explode(',', $file["base64"]);
1364
                $img = str_replace(' ', '+', $img);
1365
                $im = base64_decode($img);
1366
                if ($im !== false) {
1367
                    // getimagesizefromstring
1368
                    file_put_contents($path . $fileNewname, $im);
1369
                } else {
1370
                    return 1;
1371
                }
1372
1373
                return $fileNewname;
1374
            } else {
1375
                $adapter = new \Zend\File\Transfer\Adapter\Http();
1376
                // 1Mo
1377
                $size = new Size(array(
1378
                    'max' => 1024000
1379
                ));
1380
                $is_image = new IsImage('jpeg,png,gif,jpg');
1381
                $adapter->setValidators(array(
1382
                    $size,
1383
                    $is_image
1384
                ), $fileNewname);
1385
1386
                if (! $adapter->isValid()) {
1387
                    return false;
1388
                }
1389
1390
                @move_uploaded_file($file["tmp_name"], $path . $fileNewname);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1391
            }
1392
1393
            
1394
            if (class_exists("Imagick")) {
1395
                $ext = pathinfo($fileNewname, PATHINFO_EXTENSION);
1396
                $img = new \Imagick($path . $fileNewname);
1397
                $img->cropThumbnailImage(100, 100);
1398
                $img->setImageCompression(\Imagick::COMPRESSION_JPEG);
1399
                $img->setImageCompressionQuality(75);
1400
                // Strip out unneeded meta data
1401
                $img->stripImage();
1402
                $img->writeImage($path . str_replace('.'.$ext, '-thumbnail.'.$ext, $fileNewname));
1403
                ErrorHandler::stop(true);
1404
            }
1405
        }
1406
1407
        return $fileNewname;
1408
    }
1409
1410
    /**
1411
     * @param string $path
1412
     */
1413
    public function fileNewname($path, $filename, $generate = false)
1414
    {
1415
        $sanitize = new Sanitize();
1416
        $name = $sanitize->filter($filename);
1417
        $newpath = $path . $name;
1418
1419
        if ($generate) {
1420
            if (file_exists($newpath)) {
1421
                $filename = pathinfo($name, PATHINFO_FILENAME);
1422
                $ext = pathinfo($name, PATHINFO_EXTENSION);
1423
1424
                $name = $filename . '_' . rand(0, 99) . '.' . $ext;
1425
            }
1426
        }
1427
1428
        unset($sanitize);
1429
1430
        return $name;
1431
    }
1432
1433
    /**
1434
     * This function returns the list of games, order by $type
1435
     */
1436
    public function getQueryGamesOrderBy($type = 'createdAt', $order = 'DESC')
1437
    {
1438
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
1439
        $today = new \DateTime("now");
1440
        $today = $today->format('Y-m-d H:i:s');
1441
1442
        $onlineGames = '(
1443
            (
1444
                CASE WHEN (
1445
                    g.active = 1
1446
                    AND g.broadcastPlatform = 1
1447
                    AND (g.startDate <= :date OR g.startDate IS NULL)
1448
                    AND (g.closeDate >= :date OR g.closeDate IS NULL)
1449
                ) THEN 1 ELSE 0 END
1450
            ) +
1451
            (
1452
                CASE WHEN (
1453
                    g.active = 0
1454
                    AND (g.broadcastPlatform = 0 OR g.broadcastPlatform IS NULL)
1455
                    AND g.startDate > :date
1456
                    AND g.closeDate < :date
1457
                ) THEN 1 ELSE 0 END
1458
            )
1459
        )';
1460
1461
        $qb = $em->createQueryBuilder();
1462
        $qb->select('g')->from('PlaygroundGame\Entity\Game', 'g');
1463
        
1464
        switch ($type) {
1465
            case 'startDate':
1466
                $qb->orderBy('g.startDate', $order);
1467
                break;
1468
            case 'activeGames':
1469
                $qb->orderBy('g.active', $order);
1470
                break;
1471
            case 'onlineGames':
1472
                $qb->orderBy($onlineGames, $order);
1473
                $qb->setParameter('date', $today);
1474
                break;
1475
            case 'createdAt':
1476
                $qb->orderBy('g.createdAt', $order);
1477
                break;
1478
        }
1479
1480
        $query = $qb->getQuery();
1481
1482
        return $query;
1483
    }
1484
1485
    public function draw($game)
1486
    {
1487
        $total = $game->getWinners();
1488
1489
        // I Have to know what is the User Class used
1490
        $zfcUserOptions = $this->getServiceManager()->get('zfcuser_module_options');
1491
        $userClass = $zfcUserOptions->getUserEntityClass();
1492
1493
        $result = $this->getEntryMapper()->draw($game, $userClass, $total);
1494
1495
        foreach ($result as $e) {
1496
            $e->setWinner(1);
1497
            $e = $this->getEntryMapper()->update($e);
1498
            $this->getEventManager()->trigger('win_lottery.post', $this, array(
1499
                'user' => $e->getUser(),
1500
                'game' => $game,
1501
                'entry' => $e
1502
            ));
1503
        }
1504
1505
        return $result;
1506
    }
1507
1508
    /**
1509
     * getGameMapper
1510
     *
1511
     * @return GameMapperInterface
1512
     */
1513 View Code Duplication
    public function getGameMapper()
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...
1514
    {
1515
        if (null === $this->gameMapper) {
1516
            $this->gameMapper = $this->getServiceManager()->get('playgroundgame_game_mapper');
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->getServiceManager...roundgame_game_mapper') can also be of type array. However, the property $gameMapper is declared as type object<PlaygroundGame\Mapper\GameInterface>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

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

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
1517
        }
1518
1519
        return $this->gameMapper;
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->gameMapper; of type object|array adds the type array to the return on line 1519 which is incompatible with the return type documented by PlaygroundGame\Service\Game::getGameMapper of type PlaygroundGame\Mapper\GameInterface.
Loading history...
1520
    }
1521
1522
    /**
1523
     * setGameMapper
1524
     *
1525
     * @param GameMapperInterface $gameMapper
1526
     * @return Game
1527
     */
1528
    public function setGameMapper(GameMapperInterface $gameMapper)
1529
    {
1530
        $this->gameMapper = $gameMapper;
1531
1532
        return $this;
1533
    }
1534
1535
    /**
1536
     * getEntryMapper
1537
     *
1538
     * @return EntryMapperInterface
1539
     */
1540
    public function getEntryMapper()
1541
    {
1542
        if (null === $this->entryMapper) {
1543
            $this->entryMapper = $this->getServiceManager()->get('playgroundgame_entry_mapper');
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->getServiceManager...oundgame_entry_mapper') can also be of type array. However, the property $entryMapper is declared as type object<PlaygroundGame\Se...e\EntryMapperInterface>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

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

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
1544
        }
1545
1546
        return $this->entryMapper;
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->entryMapper; of type object|array adds the type array to the return on line 1546 which is incompatible with the return type documented by PlaygroundGame\Service\Game::getEntryMapper of type PlaygroundGame\Service\EntryMapperInterface.
Loading history...
1547
    }
1548
1549
    /**
1550
     * setEntryMapper
1551
     *
1552
     * @param EntryMapperInterface $entryMapper
1553
     * @return Game
1554
     */
1555
    public function setEntryMapper($entryMapper)
1556
    {
1557
        $this->entryMapper = $entryMapper;
1558
1559
        return $this;
1560
    }
1561
1562
    public function setOptions(ModuleOptions $options)
1563
    {
1564
        $this->options = $options;
0 ignored issues
show
Documentation Bug introduced by
It seems like $options of type object<PlaygroundGame\Options\ModuleOptions> is incompatible with the declared type object<PlaygroundGame\Se...erviceOptionsInterface> of property $options.

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...
1565
1566
        return $this;
1567
    }
1568
1569
    public function getOptions()
1570
    {
1571
        if (! $this->options instanceof ModuleOptions) {
1572
            $this->setOptions($this->getServiceManager()
0 ignored issues
show
Documentation introduced by
$this->getServiceManager...ndgame_module_options') is of type object|array, but the function expects a object<PlaygroundGame\Options\ModuleOptions>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1573
                ->get('playgroundgame_module_options'));
1574
        }
1575
1576
        return $this->options;
1577
    }
1578
1579
    /**
1580
     * Retrieve service manager instance
1581
     *
1582
     * @return ServiceManager
1583
     */
1584
    public function getServiceManager()
1585
    {
1586
        return $this->serviceManager;
1587
    }
1588
1589
    /**
1590
     * Set service manager instance
1591
     *
1592
     * @param ServiceManager $serviceManager
1593
     * @return Game
1594
     */
1595
    public function setServiceManager(ServiceManager $serviceManager)
1596
    {
1597
        $this->serviceManager = $serviceManager;
1598
1599
        return $this;
1600
    }
1601
1602
    /**
1603
     * @param string $str
1604
     */
1605
    public function getExtension($str)
1606
    {
1607
        $i = strrpos($str, '.');
1608
1609
        $l = strlen($str) - $i;
1610
        $ext = substr($str, $i + 1, $l);
1611
1612
        return $ext;
1613
    }
1614
1615
    /**
1616
     * @param string $extension
1617
     */
1618
    public function getSrc($extension, $temp_path)
1619
    {
1620
        $image_src = '';
1621
        switch ($extension) {
1622
            case 'jpg':
1623
                $image_src = imagecreatefromjpeg($temp_path);
1624
                break;
1625
            case 'jpeg':
1626
                $image_src = imagecreatefromjpeg($temp_path);
1627
                break;
1628
            case 'png':
1629
                $image_src = imagecreatefrompng($temp_path);
1630
                break;
1631
            case 'gif':
1632
                $image_src = imagecreatefromgif($temp_path);
1633
                break;
1634
        }
1635
1636
        return $image_src;
1637
    }
1638
1639
    /**
1640
     * @param string $extension
1641
     * @param string $rep
1642
     * @param integer $mini_width
1643
     * @param integer $mini_height
1644
     */
1645
    public function resize($tmp_file, $extension, $rep, $src, $mini_width, $mini_height)
0 ignored issues
show
Unused Code introduced by
The parameter $extension is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1646
    {
1647
        list($src_width, $src_height) = getimagesize($tmp_file);
1648
1649
        $ratio_src = $src_width / $src_height;
1650
        $ratio_mini = $mini_width / $mini_height;
1651
1652
        if ($ratio_src >= $ratio_mini) {
1653
            $new_height_mini = $mini_height;
1654
            $new_width_mini = $src_width / ($src_height / $mini_height);
1655
        } else {
1656
            $new_width_mini = $mini_width;
1657
            $new_height_mini = $src_height / ($src_width / $mini_width);
1658
        }
1659
1660
        $new_image_mini = imagecreatetruecolor($mini_width, $mini_height);
1661
1662
        imagecopyresampled(
1663
            $new_image_mini,
1664
            $src,
1665
            0 - ($new_width_mini - $mini_width) / 2,
1666
            0 - ($new_height_mini - $mini_height) / 2,
1667
            0,
1668
            0,
1669
            $new_width_mini,
1670
            $new_height_mini,
1671
            $src_width,
1672
            $src_height
1673
        );
1674
        imagejpeg($new_image_mini, $rep);
1675
1676
        imagedestroy($new_image_mini);
1677
    }
1678
1679
    public function getGameEntity()
1680
    {
1681
        return new \PlaygroundGame\Entity\Game();
1682
    }
1683
1684
    /**
1685
     * @param string $resource
1686
     * @param string $privilege
1687
     */
1688
    public function isAllowed($resource, $privilege = null)
1689
    {
1690
        $auth = $this->getServiceManager()->get('BjyAuthorize\Service\Authorize');
1691
1692
        return $auth->isAllowed($resource, $privilege);
1693
    }
1694
1695
    public function getIp()
1696
    {
1697
        $ipaddress = '';
0 ignored issues
show
Unused Code introduced by
$ipaddress 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...
1698
        if (isset($_SERVER['HTTP_CLIENT_IP'])) {
1699
            $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
1700
        } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1701
            $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
1702
        } elseif (isset($_SERVER['HTTP_X_FORWARDED'])) {
1703
            $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
1704
        } elseif (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
1705
            $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
1706
        } elseif (isset($_SERVER['HTTP_FORWARDED'])) {
1707
            $ipaddress = $_SERVER['HTTP_FORWARDED'];
1708
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
1709
            $ipaddress = $_SERVER['REMOTE_ADDR'];
1710
        } else {
1711
            $ipaddress = 'UNKNOWN';
1712
        }
1713
1714
        return $ipaddress;
1715
    }
1716
1717
    public function getAnonymousId()
1718
    {
1719
        $anonymousId = '';
1720
        if ($_COOKIE && array_key_exists('pg_anonymous', $_COOKIE)) {
1721
            $anonymousId = $_COOKIE['pg_anonymous'];
1722
        }
1723
1724
        return $anonymousId;
1725
    }
1726
1727
    /**
1728
     *
1729
     *
1730
     * This service is ready for all types of games
1731
     *
1732
     * @param array $data
1733
     * @return \PlaygroundGame\Entity\Game
1734
     */
1735 View Code Duplication
    public function createForm(array $data, $game, $form = null)
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...
1736
    {
1737
        $title = '';
1738
        $description = '';
1739
1740
        if ($data['form_jsonified']) {
1741
            $jsonPV = json_decode($data['form_jsonified']);
1742
            foreach ($jsonPV as $element) {
1743
                if ($element->form_properties) {
1744
                    $attributes = $element->form_properties[0];
1745
                    $title = $attributes->title;
1746
                    $description = $attributes->description;
1747
1748
                    break;
1749
                }
1750
            }
1751
        }
1752
        if (! $form) {
1753
            $form = new \PlaygroundGame\Entity\PlayerForm();
1754
        }
1755
        $form->setGame($game);
1756
        $form->setTitle($title);
1757
        $form->setDescription($description);
1758
        $form->setForm($data['form_jsonified']);
1759
        $form->setFormTemplate($data['form_template']);
1760
1761
        $form = $this->getPlayerFormMapper()->insert($form);
1762
1763
        return $form;
1764
    }
1765
1766
    /**
1767
     *  getCSV creates lines of CSV and returns it.
1768
     */
1769
    public function getCSV($array)
1770
    {
1771
        ob_start(); // buffer the output ...
1772
        $out = fopen('php://output', 'w');
1773
        fputcsv($out, array_keys($array[0]), ";");
1774
        foreach ($array as $line) {
1775
            fputcsv($out, $line, ";");
1776
        }
1777
        fclose($out);
1778
        return ob_get_clean(); // ... then return it as a string!
1779
    }
1780
    
1781
    public function getAttributes($attributes)
1782
    {
1783
        $a = array();
1784
1785
        $a['name']          = isset($attributes->name)? $attributes->name : '';
1786
        $a['placeholder']   = isset($attributes->data->placeholder)? $attributes->data->placeholder : '';
1787
        $a['label']         = isset($attributes->data->label)? $attributes->data->label : '';
1788
        $a['required']      = (isset($attributes->data->required) && $attributes->data->required == 'true')?
1789
            true:
1790
            false;
1791
        $a['class']         = isset($attributes->data->class)? $attributes->data->class : '';
1792
        $a['id']            = isset($attributes->data->id)? $attributes->data->id : '';
1793
        $a['lengthMin']     = isset($attributes->data->length)? $attributes->data->length->min : '';
1794
        $a['lengthMax']     = isset($attributes->data->length)? $attributes->data->length->max : '';
1795
        $a['validator']     = isset($attributes->data->validator)? $attributes->data->validator : '';
1796
        $a['innerData']     = isset($attributes->data->innerData)? $attributes->data->innerData : array();
1797
        $a['dropdownValues']= isset($attributes->data->dropdownValues)?
1798
            $attributes->data->dropdownValues :
1799
            array();
1800
        $a['filesizeMin']   = isset($attributes->data->filesize)? $attributes->data->filesize->min : 0;
1801
        $a['filesizeMax']   = isset($attributes->data->filesize)? $attributes->data->filesize->max : 10*1024*1024;
1802
1803
        return $a;
1804
    }
1805
1806
    /**
1807
     * @param \Zend\InputFilter\InputFilter $inputFilter
1808
     */
1809
    public function decorate($element, $attr, $inputFilter)
1810
    {
1811
        $factory = new InputFactory();
1812
        $element->setAttributes(
1813
            array(
1814
                'placeholder'   => $attr['placeholder'],
1815
                'required'      => $attr['required'],
1816
                'class'         => $attr['class'],
1817
                'id'            => $attr['id']
1818
            )
1819
        );
1820
1821
        $options = array();
1822
        $options['encoding'] = 'UTF-8';
1823
        if ($attr['lengthMin'] && $attr['lengthMin'] > 0) {
1824
            $options['min'] = $attr['lengthMin'];
1825
        }
1826
        if ($attr['lengthMax'] && $attr['lengthMax'] > $attr['lengthMin']) {
1827
            $options['max'] = $attr['lengthMax'];
1828
            $element->setAttribute('maxlength', $attr['lengthMax']);
1829
            $options['messages'] = array(
1830
                \Zend\Validator\StringLength::TOO_LONG => sprintf(
1831
                    $this->getServiceManager()->get('translator')->translate(
1832
                        'This field contains more than %s characters',
1833
                        'playgroundgame'
1834
                    ),
1835
                    $attr['lengthMax']
1836
                )
1837
            );
1838
        }
1839
1840
        $validators = array(
1841
            array(
1842
                'name'    => 'StringLength',
1843
                'options' => $options,
1844
            ),
1845
        );
1846
        if ($attr['validator']) {
1847
            $regex = "/.*\(([^)]*)\)/";
1848
            preg_match($regex, $attr['validator'], $matches);
1849
            $valArray = array(
1850
                'name' => str_replace(
1851
                    '('.$matches[1].')',
1852
                    '',
1853
                    $attr['validator']
1854
                ),
1855
                'options' => array($matches[1])
1856
            );
1857
            $validators[] = $valArray;
1858
        }
1859
1860
        $inputFilter->add($factory->createInput(array(
1861
            'name'     => $attr['name'],
1862
            'required' => $attr['required'],
1863
            'filters'  => array(
1864
                array('name' => 'StripTags'),
1865
                array('name' => 'StringTrim'),
1866
            ),
1867
            'validators' => $validators,
1868
        )));
1869
1870
        return $element;
1871
    }
1872
    /**
1873
     * Create a ZF2 Form from json data
1874
     * @return Form
1875
     */
1876
    public function createFormFromJson($jsonForm, $id = 'jsonForm')
1877
    {
1878
        $formPV = json_decode($jsonForm);
1879
        
1880
        $form = new Form();
1881
        $form->setAttribute('id', $id);
1882
        $form->setAttribute('enctype', 'multipart/form-data');
1883
        
1884
        $inputFilter = new \Zend\InputFilter\InputFilter();
1885
        $factory = new InputFactory();
1886
        
1887
        foreach ($formPV as $element) {
1888 View Code Duplication
            if (isset($element->line_text)) {
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...
1889
                $attr  = $this->getAttributes($element->line_text[0]);
1890
                $element = new Element\Text($attr['name']);
1891
                $element = $this->decorate($element, $attr, $inputFilter);
1892
                $form->add($element);
1893
            }
1894 View Code Duplication
            if (isset($element->line_password)) {
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...
1895
                $attr = $this->getAttributes($element->line_password[0]);
1896
                $element = new Element\Password($attr['name']);
1897
                $element = $this->decorate($element, $attr, $inputFilter);
1898
                $form->add($element);
1899
            }
1900 View Code Duplication
            if (isset($element->line_hidden)) {
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...
1901
                $attr = $this->getAttributes($element->line_hidden[0]);
1902
                $element = new Element\Hidden($attr['name']);
1903
                $element = $this->decorate($element, $attr, $inputFilter);
1904
                $form->add($element);
1905
            }
1906 View Code Duplication
            if (isset($element->line_email)) {
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...
1907
                $attr = $this->getAttributes($element->line_email[0]);
1908
                $element = new Element\Email($attr['name']);
1909
                $element = $this->decorate($element, $attr, $inputFilter);
1910
                $form->add($element);
1911
            }
1912 View Code Duplication
            if (isset($element->line_radio)) {
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...
1913
                $attr = $this->getAttributes($element->line_radio[0]);
1914
                $element = new Element\Radio($attr['name']);
1915
1916
                $element->setLabel($attr['label']);
1917
                $element->setAttributes(
1918
                    array(
1919
                        'name'      => $attr['name'],
1920
                        'required'  => $attr['required'],
1921
                        'allowEmpty'=> !$attr['required'],
1922
                        'class'     => $attr['class'],
1923
                        'id'        => $attr['id']
1924
                    )
1925
                );
1926
                $values = array();
1927
                foreach ($attr['innerData'] as $value) {
1928
                    $values[] = $value->label;
1929
                }
1930
                $element->setValueOptions($values);
1931
        
1932
                $options = array();
1933
                $options['encoding'] = 'UTF-8';
1934
                $options['disable_inarray_validator'] = true;
1935
        
1936
                $element->setOptions($options);
1937
        
1938
                $form->add($element);
1939
        
1940
                $inputFilter->add($factory->createInput(array(
1941
                    'name'     => $attr['name'],
1942
                    'required' => $attr['required'],
1943
                    'allowEmpty' => !$attr['required'],
1944
                )));
1945
            }
1946 View Code Duplication
            if (isset($element->line_checkbox)) {
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...
1947
                $attr = $this->getAttributes($element->line_checkbox[0]);
1948
                $element = new Element\MultiCheckbox($attr['name']);
1949
        
1950
                $element->setLabel($attr['label']);
1951
                $element->setAttributes(
1952
                    array(
1953
                        'name'      => $attr['name'],
1954
                        'required'  => $attr['required'],
1955
                        'allowEmpty'=> !$attr['required'],
1956
                        'class'     => $attr['class'],
1957
                        'id'        => $attr['id']
1958
                    )
1959
                );
1960
1961
                $values = array();
1962
                foreach ($attr['innerData'] as $value) {
1963
                    $values[] = $value->label;
1964
                }
1965
                $element->setValueOptions($values);
1966
                $form->add($element);
1967
        
1968
                $options = array();
1969
                $options['encoding'] = 'UTF-8';
1970
                $options['disable_inarray_validator'] = true;
1971
        
1972
                $element->setOptions($options);
1973
        
1974
                $inputFilter->add($factory->createInput(array(
1975
                    'name'      => $attr['name'],
1976
                    'required'  => $attr['required'],
1977
                    'allowEmpty'=> !$attr['required'],
1978
                )));
1979
            }
1980 View Code Duplication
            if (isset($element->line_dropdown)) {
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...
1981
                $attr = $this->getAttributes($element->line_dropdown[0]);
1982
                $element = new Element\Select($attr['name']);
1983
1984
                $element->setLabel($attr['label']);
1985
                $element->setAttributes(
1986
                    array(
1987
                        'name'      => $attr['name'],
1988
                        'required'  => $attr['required'],
1989
                        'allowEmpty'=> !$attr['required'],
1990
                        'class'     => $attr['class'],
1991
                        'id'        => $attr['id']
1992
                    )
1993
                );
1994
                $values = array();
1995
                foreach ($attr['dropdownValues'] as $value) {
1996
                    $values[] = $value->dropdown_label;
1997
                }
1998
                $element->setValueOptions($values);
1999
                $form->add($element);
2000
        
2001
                $options = array();
2002
                $options['encoding'] = 'UTF-8';
2003
                $options['disable_inarray_validator'] = true;
2004
        
2005
                $element->setOptions($options);
2006
        
2007
                $inputFilter->add($factory->createInput(array(
2008
                    'name'     => $attr['name'],
2009
                    'required' => $attr['required'],
2010
                    'allowEmpty' => !$attr['required'],
2011
                )));
2012
            }
2013 View Code Duplication
            if (isset($element->line_paragraph)) {
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...
2014
                $attr = $this->getAttributes($element->line_paragraph[0]);
2015
                $element = new Element\Textarea($attr['name']);
2016
                $element = $this->decorate($element, $attr, $inputFilter);
2017
                $form->add($element);
2018
            }
2019
            if (isset($element->line_upload)) {
2020
                $attr = $this->getAttributes($element->line_upload[0]);
2021
                $element = new Element\File($attr['name']);
2022
2023
                $element->setLabel($attr['label']);
2024
                $element->setAttributes(
2025
                    array(
2026
                        'name'      => $attr['name'],
2027
                        'required'  => $attr['required'],
2028
                        'class'     => $attr['class'],
2029
                        'id'        => $attr['id']
2030
                    )
2031
                );
2032
                $form->add($element);
2033
        
2034
                $inputFilter->add($factory->createInput(array(
2035
                    'name'     => $attr['name'],
2036
                    'required' => $attr['required'],
2037
                    'validators' => array(
2038
                        array(
2039
                            'name' => '\Zend\Validator\File\Size',
2040
                            'options' => array('min' => $attr['filesizeMin'], 'max' => $attr['filesizeMax'])
2041
                        ),
2042
                        array(
2043
                            'name' => '\Zend\Validator\File\Extension',
2044
                            'options'  => array(
2045
                                'png,PNG,jpg,JPG,jpeg,JPEG,gif,GIF',
2046
                                'messages' => array(
2047
                                    \Zend\Validator\File\Extension::FALSE_EXTENSION =>'Veuillez télécharger une image'
2048
                                )
2049
                            )
2050
                        ),
2051
                    ),
2052
                )));
2053
            }
2054
        }
2055
        
2056
        $form->setInputFilter($inputFilter);
2057
        
2058
        return $form;
2059
    }
2060
2061
    /**
2062
     * Send mail for winner and/or loser
2063
     * @param \PlaygroundGame\Entity\Game $game
2064
     * @param \PlaygroundUser\Entity\User $user
2065
     * @param \PlaygroundGame\Entity\Entry $lastEntry
2066
     * @param \PlaygroundGame\Entity\Prize $prize
2067
     */
2068
    public function sendMail($game, $user, $lastEntry, $prize = null)
2069
    {
2070 View Code Duplication
        if (($user || ($game->getAnonymousAllowed() && $game->getAnonymousIdentifier())) &&
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...
2071
            $game->getMailWinner() &&
2072
            $lastEntry->getWinner()
2073
        ) {
2074
            $this->sendResultMail($game, $user, $lastEntry, 'winner', $prize);
2075
        }
2076
2077 View Code Duplication
        if (($user || ($game->getAnonymousAllowed() && $game->getAnonymousIdentifier())) &&
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...
2078
            $game->getMailLooser() &&
2079
            !$lastEntry->getWinner()
2080
        ) {
2081
            $this->sendResultMail($game, $user, $lastEntry, 'looser');
2082
        }
2083
    }
2084
2085
    public function getPlayerFormMapper()
2086
    {
2087
        if (null === $this->playerformMapper) {
2088
            $this->playerformMapper = $this->getServiceManager()->get('playgroundgame_playerform_mapper');
2089
        }
2090
2091
        return $this->playerformMapper;
2092
    }
2093
2094
    public function setPlayerFormMapper($playerformMapper)
2095
    {
2096
        $this->playerformMapper = $playerformMapper;
2097
2098
        return $this;
2099
    }
2100
2101
    public function getInvitationMapper()
2102
    {
2103
        if (null === $this->invitationMapper) {
2104
            $this->invitationMapper = $this->getServiceManager()->get('playgroundgame_invitation_mapper');
2105
        }
2106
2107
        return $this->invitationMapper;
2108
    }
2109
2110
    public function setInvitationMapper($invitationMapper)
2111
    {
2112
        $this->invitationMapper = $invitationMapper;
2113
2114
        return $this;
2115
    }
2116
2117
    /**
2118
     * getUserMapper
2119
     *
2120
     * @return UserMapperInterface
2121
     */
2122
    public function getUserMapper()
2123
    {
2124
        if (null === $this->userMapper) {
2125
            $this->userMapper = $this->getServiceManager()->get('zfcuser_user_mapper');
2126
        }
2127
2128
        return $this->userMapper;
2129
    }
2130
}
2131