Completed
Push — develop ( 7ecade...971ef0 )
by greg
02:34
created

Game::getGrid()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 71

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 71
rs 8.6327
c 0
b 0
f 0
cc 1
nc 1
nop 1

How to fix   Long Method   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
namespace PlaygroundGame\Service;
3
4
use PlaygroundGame\Entity\Entry;
5
use Zend\Session\Container;
6
use Zend\ServiceManager\ServiceManager;
7
use Zend\EventManager\EventManagerAwareTrait;
8
use Zend\EventManager\EventManager;
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
use Zend\ServiceManager\ServiceLocatorInterface;
20
use ZfcDatagrid\Column;
21
use ZfcDatagrid\Action;
22
use ZfcDatagrid\Column\Formatter;
23
use ZfcDatagrid\Column\Type;
24
use ZfcDatagrid\Column\Style;
25
use ZfcDatagrid\Filter;
26
use Doctrine\ORM\Query\Expr;
27
28
class Game
29
{
30
    use EventManagerAwareTrait;
31
32
    /**
33
     *
34
     * @var GameMapperInterface
35
     */
36
    protected $gameMapper;
37
38
    /**
39
     *
40
     * @var EntryMapperInterface
41
     */
42
    protected $entryMapper;
43
44
    /**
45
     *
46
     * @var UserServiceOptionsInterface
47
     */
48
    protected $options;
49
50
    protected $playerformMapper;
51
52
    protected $invitationMapper;
53
54
    protected $userMapper;
55
    
56
    protected $anonymousIdentifier = null;
57
58
    /**
59
     *
60
     * @var ServiceManager
61
     */
62
    protected $serviceLocator;
63
64
    protected $event;
65
66
    public function __construct(ServiceLocatorInterface $locator)
67
    {
68
        $this->serviceLocator = $locator;
0 ignored issues
show
Documentation Bug introduced by
$locator is of type object<Zend\ServiceManag...erviceLocatorInterface>, but the property $serviceLocator was declared to be of type object<Zend\ServiceManager\ServiceManager>. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof 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 given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
69
    }
70
71 View Code Duplication
    public function getEventManager()
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...
72
    {
73
        if (null === $this->event) {
74
            $this->event = new EventManager($this->serviceLocator->get('SharedEventManager'), [get_class($this)]);
75
        }
76
77
        return $this->event;
78
    }
79
80 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...
81
    {
82
        $path = $this->getOptions()->getMediaPath() . DIRECTORY_SEPARATOR;
83
        $path .= 'game' . $game->getId() . DIRECTORY_SEPARATOR;
84
        if (!is_dir($path)) {
85
            mkdir($path, 0777, true);
86
        }
87
        $path .= 'user'. $user->getId() . DIRECTORY_SEPARATOR;
88
        if (!is_dir($path)) {
89
            mkdir($path, 0777, true);
90
        }
91
92
        return $path;
93
    }
94
95 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...
96
    {
97
        $media_url = $this->getOptions()->getMediaUrl() . '/';
98
        $media_url .= 'game' . $game->getId() . '/' . 'user'. $user->getId() . '/';
99
100
        return $media_url;
101
    }
102
103
    /**
104
     *
105
     * This service is ready for all types of games
106
     *
107
     * @param array $data
108
     * @param string $formClass
109
     * @return \PlaygroundGame\Entity\Game
110
     */
111
    public function createOrUpdate(array $data, $game, $formClass)
112
    {
113
        $entityManager = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
114
115
        $form = $this->serviceLocator->get($formClass);
116
        $form->get('publicationDate')->setOptions(array(
117
            'format' => 'Y-m-d H:i:s'
118
        ));
119
        $form->get('startDate')->setOptions(array(
120
            'format' => 'Y-m-d H:i:s'
121
        ));
122
        $form->get('endDate')->setOptions(array(
123
            'format' => 'Y-m-d H:i:s'
124
        ));
125
        $form->get('closeDate')->setOptions(array(
126
            'format' => 'Y-m-d H:i:s'
127
        ));
128
129
        $form->bind($game);
130
131
        $path = $this->getOptions()->getMediaPath() . '/';
132
        if (!is_dir($path)) {
133
            mkdir($path, 0777, true);
134
        }
135
        $media_url = $this->getOptions()->getMediaUrl() . '/';
136
137
        $identifierInput = $form->getInputFilter()->get('identifier');
138
        $noObjectExistsValidator = new NoObjectExistsValidator(array(
139
            'object_repository' => $entityManager->getRepository('PlaygroundGame\Entity\Game'),
140
            'fields' => 'identifier',
141
            'messages' => array(
142
                'objectFound' => 'This url already exists !'
143
            )
144
        ));
145
146
        if ($game->getIdentifier() != $data['identifier']) {
147
            $identifierInput->getValidatorChain()->addValidator($noObjectExistsValidator);
148
        }
149
150
        // I must switch from original format to the Y-m-d format because
151
        // this is the only one accepted by new DateTime($value)
152 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...
153
            $tmpDate = \DateTime::createFromFormat('d/m/Y H:i:s', $data['publicationDate']);
154
            $data['publicationDate'] = $tmpDate->format('Y-m-d H:i:s');
155
        }
156 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...
157
            $tmpDate = \DateTime::createFromFormat('d/m/Y H:i:s', $data['startDate']);
158
            $data['startDate'] = $tmpDate->format('Y-m-d H:i:s');
159
        }
160 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...
161
            $tmpDate = \DateTime::createFromFormat('d/m/Y H:i:s', $data['endDate']);
162
            $data['endDate'] = $tmpDate->format('Y-m-d H:i:s');
163
        }
164 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...
165
            $tmpDate = \DateTime::createFromFormat('d/m/Y H:i:s', $data['closeDate']);
166
            $data['closeDate'] = $tmpDate->format('Y-m-d H:i:s');
167
        }
168
169
        // If publicationDate is null, I update it with the startDate if not null neither
170
        if ((! isset($data['publicationDate']) || $data['publicationDate'] == '') &&
171
            (isset($data['startDate']) && $data['startDate'] != '')
172
        ) {
173
            $data['publicationDate'] = $data['startDate'];
174
        }
175
176
        // If the identifier has not been set, I use the title to create one.
177 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...
178
            $data['identifier'] = $data['title'];
179
        }
180
181
        $form->setData($data);
182
183
        // If someone want to claim... It's time to do it ! used for exemple by PlaygroundFacebook Module
184
        $result = $this->getEventManager()->trigger(__FUNCTION__ . '.validate', $this, array(
185
            'game' => $game,
186
            'data' => $data
187
        ));
188
        if (is_array($result) && ! $result[0]) {
189
            $form->get('fbAppId')->setMessages(array(
190
                'Vous devez d\'abord désinstaller l\'appli Facebook'
191
            ));
192
193
            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...
194
        }
195
196
        if (! $form->isValid()) {
197 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...
198
                $tmpDate = \DateTime::createFromFormat('Y-m-d H:i:s', $data['publicationDate']);
199
                $data['publicationDate'] = $tmpDate->format('d/m/Y H:i:s');
200
                $form->setData(array(
201
                    'publicationDate' => $data['publicationDate']
202
                ));
203
            }
204 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...
205
                $tmpDate = \DateTime::createFromFormat('Y-m-d H:i:s', $data['startDate']);
206
                $data['startDate'] = $tmpDate->format('d/m/Y H:i:s');
207
                $form->setData(array(
208
                    'startDate' => $data['startDate']
209
                ));
210
            }
211 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...
212
                $tmpDate = \DateTime::createFromFormat('Y-m-d H:i:s', $data['endDate']);
213
                $data['endDate'] = $tmpDate->format('d/m/Y H:i:s');
214
                $form->setData(array(
215
                    'endDate' => $data['endDate']
216
                ));
217
            }
218 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...
219
                $tmpDate = \DateTime::createFromFormat('Y-m-d H:i:s', $data['closeDate']);
220
                $data['closeDate'] = $tmpDate->format('d/m/Y H:i:s');
221
                $form->setData(array(
222
                    'closeDate' => $data['closeDate']
223
                ));
224
            }
225
            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...
226
        }
227
228
        $game = $form->getData();
229
        $game = $this->getGameMapper()->insert($game);
230
231
        // I wait for the game to be saved to obtain its ID.
232 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...
233
            ErrorHandler::start();
234
            $data['uploadMainImage']['name'] = $this->fileNewname(
235
                $path,
236
                $game->getId() . "-" . $data['uploadMainImage']['name']
237
            );
238
            move_uploaded_file($data['uploadMainImage']['tmp_name'], $path . $data['uploadMainImage']['name']);
239
            $game->setMainImage($media_url . $data['uploadMainImage']['name']);
240
            ErrorHandler::stop(true);
241
        }
242
243
        if (isset($data['deleteMainImage']) &&
244
            $data['deleteMainImage'] &&
245
            empty($data['uploadMainImage']['tmp_name'])
246
        ) {
247
            ErrorHandler::start();
248
            $image = $game->getMainImage();
249
            $image = str_replace($media_url, '', $image);
250
            unlink($path . $image);
251
            $game->setMainImage(null);
252
            ErrorHandler::stop(true);
253
        }
254
255 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...
256
            ErrorHandler::start();
257
            $data['uploadSecondImage']['name'] = $this->fileNewname(
258
                $path,
259
                $game->getId() . "-" . $data['uploadSecondImage']['name']
260
            );
261
            move_uploaded_file($data['uploadSecondImage']['tmp_name'], $path . $data['uploadSecondImage']['name']);
262
            $game->setSecondImage($media_url . $data['uploadSecondImage']['name']);
263
            ErrorHandler::stop(true);
264
        }
265
266
        if (isset($data['deleteSecondImage']) &&
267
            $data['deleteSecondImage'] &&
268
            empty($data['uploadSecondImage']['tmp_name'])
269
        ) {
270
            ErrorHandler::start();
271
            $image = $game->getSecondImage();
272
            $image = str_replace($media_url, '', $image);
273
            unlink($path . $image);
274
            $game->setSecondImage(null);
275
            ErrorHandler::stop(true);
276
        }
277
278
        if (! empty($data['uploadStylesheet']['tmp_name'])) {
279
            ErrorHandler::start();
280
            move_uploaded_file($data['uploadStylesheet']['tmp_name'], $path . 'stylesheet_' . $game->getId() . '.css');
281
            $game->setStylesheet($media_url . 'stylesheet_' . $game->getId() . '.css');
282
            ErrorHandler::stop(true);
283
        }
284
285 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...
286
            ErrorHandler::start();
287
            $data['uploadFbShareImage']['name'] = $this->fileNewname(
288
                $path,
289
                $game->getId() . "-" . $data['uploadFbShareImage']['name']
290
            );
291
            move_uploaded_file($data['uploadFbShareImage']['tmp_name'], $path . $data['uploadFbShareImage']['name']);
292
            $game->setFbShareImage($media_url . $data['uploadFbShareImage']['name']);
293
            ErrorHandler::stop(true);
294
        }
295
296
        if (isset($data['deleteFbShareImage']) &&
297
            $data['deleteFbShareImage'] &&
298
            empty($data['uploadFbShareImage']['tmp_name'])
299
        ) {
300
            ErrorHandler::start();
301
            $image = $game->getFbShareImage();
302
            $image = str_replace($media_url, '', $image);
303
            unlink($path . $image);
304
            $game->setFbShareImage(null);
305
            ErrorHandler::stop(true);
306
        }
307
308
        if (! empty($data['uploadFbPageTabImage']['tmp_name'])) {
309
            ErrorHandler::start();
310
            $extension = $this->getExtension(strtolower($data['uploadFbPageTabImage']['name']));
311
            $src = $this->getSrc($extension, $data['uploadFbPageTabImage']['tmp_name']);
312
            $this->resize(
313
                $data['uploadFbPageTabImage']['tmp_name'],
314
                $extension,
315
                $path . $game->getId() . "-" . $data['uploadFbPageTabImage']['name'],
316
                $src,
317
                111,
318
                74
319
            );
320
321
            $game->setFbPageTabImage($media_url . $game->getId() . "-" . $data['uploadFbPageTabImage']['name']);
322
            ErrorHandler::stop(true);
323
        }
324
325
        if (isset($data['deleteFbPageTabImage']) &&
326
            $data['deleteFbPageTabImage'] &&
327
            empty($data['uploadFbPageTabImage']['tmp_name'])
328
        ) {
329
            ErrorHandler::start();
330
            $image = $game->getFbPageTabImage();
331
            $image = str_replace($media_url, '', $image);
332
            unlink($path . $image);
333
            $game->setFbPageTabImage(null);
334
            ErrorHandler::stop(true);
335
        }
336
337
        // Let's remove the fbPostId if there is no post to send anymore
338
        if ($data['broadcastPostFacebook'] == 0) {
339
            $game->setFbPostId(null);
340
        }
341
342
        $game = $this->getGameMapper()->update($game);
343
344
        $prize_mapper = $this->serviceLocator->get('playgroundgame_prize_mapper');
345
        if (isset($data['prizes'])) {
346
            foreach ($data['prizes'] as $prize_data) {
347
                if (! empty($prize_data['picture_file']['tmp_name']) && ! $prize_data['picture_file']['error']) {
348
                    if ($prize_data['id']) {
349
                        $prize = $prize_mapper->findById($prize_data['id']);
350
                    } else {
351
                        $some_prizes = $prize_mapper->findBy(array(
352
                            'game' => $game,
353
                            'title' => $prize_data['title']
354
                        ));
355
                        if (count($some_prizes) == 1) {
356
                            $prize = $some_prizes[0];
357
                        } else {
358
                            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...
359
                        }
360
                    }
361
                    // Remove if existing image
362
                    if ($prize->getPicture() && file_exists($prize->getPicture())) {
363
                        unlink($prize->getPicture());
364
                        $prize->getPicture(null);
365
                    }
366
                    // Upload and set new
367
                    ErrorHandler::start();
368
                    $filename = "game-" . $game->getId() . "-prize-";
369
                    $filename .= $prize->getId() . "-" . $prize_data['picture_file']['name'];
370
                    move_uploaded_file($prize_data['picture_file']['tmp_name'], $path . $filename);
371
                    $prize->setPicture($media_url . $filename);
372
                    ErrorHandler::stop(true);
373
                    $prize_mapper->update($prize);
374
                }
375
            }
376
        }
377
        // If I receive false, it means that the FB Id was not available anymore
378
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
379
            'game' => $game
380
        ));
381
382
        return $game;
383
    }
384
 
385
    /**
386
     * getNextGames
387
     *
388
     * @return Array of PlaygroundGame\Entity\Game
389
     */
390
    public function getNextGames($dateStart = null, $dateEnd = null, $classType = null, $cost = null, $order = null, $dir = 'DESC')
391
    {
392
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
393
        if ($dateStart === null) {
394
            $today = new \DateTime("now");
395
        } else {
396
            $today = new \DateTime($dateStart);
397
        }
398
        
399
        $today = $today->format('Y-m-d H:i:s');
400
        $orderBy = 'g.startDate';
401
        if ($order != null) {
402
            $orderBy = 'g.'.$order;
403
        }
404
405
        $qb = $em->createQueryBuilder();
406
        $and = $qb->expr()->andx();
407
        $and->add($qb->expr()->gte('g.startDate', ':date'));
408
        $qb->setParameter('date', $today);
409
        if ($dateEnd != null) {
410
            $dateEnd = new \DateTime($dateEnd);
411
            $end = $dateEnd->format('Y-m-d H:i:s');
412
            $and->add($qb->expr()->lte('g.endDate', ':datefin'));
413
            $qb->setParameter('datefin', $end);
414
        }
415
        
416
        $and->add($qb->expr()->eq('g.active', '1'));
417
        $and->add($qb->expr()->eq('g.broadcastPlatform', '1'));
418
        
419
        if ($classType != '') {
420
            $and->add($qb->expr()->eq('g.classType', ':classType'));
421
            $qb->setParameter('classType', $classType);
422
        }
423
        
424
        if ($cost !== null) {
425
            $and->add($qb->expr()->eq('g.costToPlay', ':cost'));
426
            $qb->setParameter('cost', $cost);
427
        }
428
        
429
        $qb->select('g')
430
            ->from('PlaygroundGame\Entity\Game', 'g')
431
            ->where($and)
432
            ->orderBy($orderBy, $dir);
433
        
434
        $query = $qb->getQuery();
435
        //echo $query->getSql();
436
        $games = $query->getResult();
437
        
438
        // je les classe par date de publication (date comme clé dans le tableau afin de pouvoir merger les objets
439
        // de type article avec le même procédé en les classant naturellement par date asc ou desc
440
        $arrayGames = array();
441 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...
442
            if ($game->getPublicationDate()) {
443
                $key = $game->getPublicationDate()->format('Ymd');
444
            } elseif ($game->getStartDate()) {
445
                $key = $game->getStartDate()->format('Ymd');
446
            } else {
447
                $key = $game->getUpdatedAt()->format('Ymd');
448
            }
449
            $key .= $game->getUpdatedAt()->format('Ymd') . '-' . $game->getId();
450
            $arrayGames[$key] = $game;
451
        }
452
453
        return $arrayGames;
454
    }
455
456
    /**
457
     * getActiveGames
458
     *
459
     * @return Array of PlaygroundGame\Entity\Game
460
     */
461
    public function getActiveGames($displayHome = null, $classType = '', $order = '', $dir = 'DESC')
462
    {
463
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
464
        $today = new \DateTime("now");
465
        $today = $today->format('Y-m-d H:i:s');
466
        $orderBy = 'g.publicationDate';
467
        if ($order != '') {
468
            $orderBy = 'g.'.$order;
469
        }
470
471
        $qb = $em->createQueryBuilder();
472
        $and = $qb->expr()->andx();
473
        $and->add(
474
            $qb->expr()->orX(
475
                $qb->expr()->lte('g.publicationDate', ':date'),
476
                $qb->expr()->isNull('g.publicationDate')
477
            )
478
        );
479
        $and->add(
480
            $qb->expr()->orX(
481
                $qb->expr()->gte('g.closeDate', ':date'),
482
                $qb->expr()->isNull('g.closeDate')
483
            )
484
        );
485
        $qb->setParameter('date', $today);
486
        
487
        $and->add($qb->expr()->eq('g.active', '1'));
488
        $and->add($qb->expr()->eq('g.broadcastPlatform', '1'));
489
        
490
        if ($classType != '') {
491
            $and->add($qb->expr()->eq('g.classType', ':classType'));
492
            $qb->setParameter('classType', $classType);
493
        }
494
        
495
        if ($displayHome !== null) {
496
            $and->add($qb->expr()->eq('g.displayHome', ':key'));
497
            $qb->setParameter('key', $displayHome);
498
        }
499
        
500
        $qb->select('g')
501
            ->from('PlaygroundGame\Entity\Game', 'g')
502
            ->where($and)
503
            ->orderBy($orderBy, $dir);
504
        
505
        $query = $qb->getQuery();
506
        $games = $query->getResult();
507
        
508
        // je les classe par date de publication (date comme clé dans le tableau afin de pouvoir merger les objets
509
        // de type article avec le même procédé en les classant naturellement par date asc ou desc
510
        $arrayGames = array();
511 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...
512
            if ($game->getPublicationDate()) {
513
                $key = $game->getPublicationDate()->format('Ymd');
514
            } elseif ($game->getStartDate()) {
515
                $key = $game->getStartDate()->format('Ymd');
516
            } else {
517
                $key = $game->getUpdatedAt()->format('Ymd');
518
            }
519
            $key .= $game->getUpdatedAt()->format('Ymd') . '-' . $game->getId();
520
            $arrayGames[$key] = $game;
521
        }
522
523
        return $arrayGames;
524
    }
525
526
    /**
527
     * getAvailableGames : Games OnLine and not already played by $user
528
     *
529
     * @return Array of PlaygroundGame\Entity\Game
530
     */
531
    public function getAvailableGames($user, $maxResults = 2)
532
    {
533
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
534
        $today = new \DateTime("now");
535
        $today = $today->format('Y-m-d H:i:s');
536
537
        // Game active with a start_date before today (or without start_date)
538
        // and end_date after today (or without end-date)
539
        $query = $em->createQuery('SELECT g FROM PlaygroundGame\Entity\Game g
540
                WHERE NOT EXISTS (SELECT l FROM PlaygroundGame\Entity\Entry l WHERE l.game = g AND l.user = :user)
541
                AND (g.startDate <= :date OR g.startDate IS NULL)
542
                AND (g.endDate >= :date OR g.endDate IS NULL)
543
                AND g.active = 1 AND g.broadcastPlatform = 1
544
                ORDER BY g.startDate ASC');
545
        $query->setParameter('date', $today);
546
        $query->setParameter('user', $user);
547
        $query->setMaxResults($maxResults);
548
        $games = $query->getResult();
549
550
        return $games;
551
    }
552
553
    public function getGrid($game)
554
    {
555
        $qb = $this->getEntriesQuery($game);
556
557
        /* @var $grid \ZfcDatagrid\Datagrid */
558
        $grid = $this->serviceLocator->get('ZfcDatagrid\Datagrid');
559
        $grid->setTitle('Entries');
560
        $grid->setDataSource($qb);
561
562
        $col = new Column\Select('id', 'u');
563
        $col->setLabel('Id');
564
        $col->setIdentity(true);
565
        $grid->addColumn($col);
566
        
567
        $colType = new Type\DateTime(
568
            'Y-m-d H:i:s',
569
            \IntlDateFormatter::MEDIUM,
570
            \IntlDateFormatter::MEDIUM
571
        );
572
        $colType->setSourceTimezone('UTC');
573
574
        $col = new Column\Select('created_at', 'u');
575
        $col->setLabel('Created');
576
        $col->setType($colType);
577
        $grid->addColumn($col);
578
579
        $col = new Column\Select('username', 'u');
580
        $col->setLabel('Username');
581
        $grid->addColumn($col);
582
583
        $col = new Column\Select('email', 'u');
584
        $col->setLabel('Email');
585
        $grid->addColumn($col);
586
587
        $col = new Column\Select('firstname', 'u');
588
        $col->setLabel('Firstname');
589
        $grid->addColumn($col);
590
591
        $col = new Column\Select('lastname', 'u');
592
        $col->setLabel('Lastname');
593
        $grid->addColumn($col);
594
595
        $col = new Column\Select('winner', 'e');
596
        $col->setLabel('Status');
597
        $col->setReplaceValues(
598
            [
599
                0 => 'looser',
600
                1 => 'winner',
601
            ]
602
        );
603
        $grid->addColumn($col);
604
605
        // $actions = new Column\Action();
606
        // $actions->setLabel('');
607
608
        // $viewAction = new Column\Action\Button();
609
        // $viewAction->setLabel('Reset Password');
610
        // $rowId = $viewAction->getRowIdPlaceholder();
611
        // $viewAction->setLink('/admin/user/reset/'.$rowId);
612
        // $actions->addAction($viewAction);
613
614
        // $grid->addColumn($actions);
615
616
        // $action = new Action\Mass();
617
        // $action->setTitle('This is incredible');
618
        // $action->setLink('/test');
619
        // $action->setConfirm(true);
620
        // $grid->addMassAction($action);
621
622
        return $grid;
623
    }
624
625
    public function getEntriesQuery($game)
626
    {
627
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
628
629
        $qb = $em->createQueryBuilder();
630
        $qb->select('
631
            e.id,
632
            u.username,
633
            u.title,
634
            u.firstname,
635
            u.lastname,
636
            u.email,
637
            u.optin,
638
            u.optinPartner,
639
            u.address,
640
            u.address2,
641
            u.postalCode,
642
            u.city,
643
            u.country,
644
            u.telephone,
645
            u.mobile,
646
            u.created_at,
647
            u.dob,
648
            e.winner,
649
            e.socialShares,
650
            e.playerData,
651
            e.geoloc,
652
            e.updated_at
653
            ')
654
            ->from('PlaygroundGame\Entity\Entry', 'e')
655
            ->leftJoin('e.user', 'u')
656
            ->where($qb->expr()->eq('e.game', ':game'));
657
        
658
        $qb->setParameter('game', $game);
659
660
        return $qb;
661
    }
662
663
    /**
664
     * DEPRECATED
665
     */
666
    public function getEntriesHeader($game)
667
    {
668
        if ($game->getAnonymousAllowed() && $game->getPlayerForm()) {
669
            $formPV = json_decode($game->getPlayerForm()->getForm(), true);
670
            $header = array('id'=> 1);
671 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...
672
                foreach ($element as $k => $v) {
673
                    if ($k !== 'form_properties') {
674
                        $header[$v[0]['name']] = 1;
675
                    }
676
                }
677
            }
678
        } elseif ($game->getAnonymousAllowed()) {
679
            $header = array(
680
                'u.id' => 1,
681
                'u.ip' => 1
682
            );
683
        } else {
684
            $header = array(
685
                'u.id' => 1,
686
                'u.username' => 1,
687
                'u.title' => 1,
688
                'u.firstname' => 1,
689
                'u.lastname' => 1,
690
                'u.displayName' => 1,
691
                'u.email' => 1,
692
                'u.optin' => 1,
693
                'u.optinPartner' => 1,
694
                'u.address' => 1,
695
                'u.address2' => 1,
696
                'u.postalCode' => 1,
697
                'u.city' => 1,
698
                'u.country' => 1,
699
                'u.telephone' => 1,
700
                'u.mobile' => 1,
701
                'u.created_at' => 1,
702
                'u.dob' => 1
703
            );
704
        }
705
        $header['e.geoloc'] = 1;
706
        $header['e.winner'] = 1;
707
        $header['e.socialShares'] = 1;
708
        $header['e.updated_at'] = 1;
709
710
        return $header;
711
    }
712
713
    /**
714
     * DEPRECATED
715
     * getGameEntries : I create an array of entries based on playerData + header
716
     *
717
     * @return Array of PlaygroundGame\Entity\Game
718
     */
719
    public function getGameEntries($header, $entries, $game)
720
    {
721
        $header = $this->getEntriesHeader($game);
722
723
        $results = array();
724
725
        foreach ($entries as $k => $entry) {
726
            $entryData = json_decode($entry['playerData'], true);
727 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...
728
                if (isset($entryData[$key])) {
729
                    $results[$k][$key] = (is_array($entryData[$key]))?implode(', ', $entryData[$key]):$entryData[$key];
730
                } elseif (array_key_exists($key, $entry)) {
731
                    $results[$k][$key] = ($entry[$key] instanceof \DateTime)?
732
                        $entry[$key]->format('Y-m-d H:i:s'):
733
                        $entry[$key];
734
                } else {
735
                    $results[$k][$key] = '';
736
                }
737
            }
738
        }
739
740
        return $results;
741
    }
742
743
    /**
744
     * getActiveSliderGames
745
     *
746
     * @return Array of PlaygroundGame\Entity\Game
747
     */
748
    public function getActiveSliderGames()
749
    {
750
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
751
        $today = new \DateTime("now");
752
        $today = $today->format('Y-m-d H:i:s');
753
754
        // Game active with a start_date before today (or without start_date)
755
        // and end_date after today (or without end-date)
756
        $query = $em->createQuery('SELECT g FROM PlaygroundGame\Entity\Game g
757
            WHERE (g.publicationDate <= :date OR g.publicationDate IS NULL)
758
            AND (g.closeDate >= :date OR g.closeDate IS NULL)
759
            AND g.active = true AND g.broadcastPlatform = 1 AND g.pushHome = true');
760
        $query->setParameter('date', $today);
761
        $games = $query->getResult();
762
763
        // je les classe par date de publication (date comme clé dans le tableau afin de pouvoir merger les objets
764
        // de type article avec le même procédé en les classant naturellement par date asc ou desc
765
        $arrayGames = array();
766 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...
767
            if ($game->getPublicationDate()) {
768
                $key = $game->getPublicationDate()->format('Ymd');
769
            } elseif ($game->getStartDate()) {
770
                $key = $game->getStartDate()->format('Ymd');
771
            } else {
772
                $key = $game->getUpdatedAt()->format('Ymd');
773
            }
774
            $key .= $game->getUpdatedAt()->format('Ymd') . '-' . $game->getId();
775
            $arrayGames[$key] = $game;
776
        }
777
778
        return $arrayGames;
779
    }
780
781
    /**
782
     * getPrizeCategoryGames
783
     *
784
     * @return Array of PlaygroundGame\Entity\Game
785
     */
786 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...
787
    {
788
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
789
790
        $query = $em->createQuery('SELECT g FROM PlaygroundGame\Entity\Game g
791
            WHERE (g.prizeCategory = :categoryid AND g.broadcastPlatform = 1)
792
            ORDER BY g.publicationDate DESC');
793
        $query->setParameter('categoryid', $categoryid);
794
        $games = $query->getResult();
795
796
        return $games;
797
    }
798
799
    public function getGameIdentifierFromFacebook($fbPageId)
800
    {
801
        $identifier = null;
802
        $game = $this->getGameMapper()->findOneBy(array('fbPageId' => $fbPageId, 'broadcastFacebook' => 1));
803
804
        if ($game && $game->getIdentifier() !== null) {
805
            $identifier = $game->getIdentifier();
806
        }
807
808
        return $identifier;
809
    }
810
811
    public function checkGame($identifier, $checkIfStarted = true)
812
    {
813
        $gameMapper = $this->getGameMapper();
814
815
        if (! $identifier) {
816
            return false;
817
        }
818
819
        $game = $gameMapper->findByIdentifier($identifier);
820
821
        // the game has not been found
822
        if (! $game) {
823
            return false;
824
        }
825
826
        // for preview stuff as admin
827
        if ($this->isAllowed('game', 'edit')) {
828
            //$r =$this->serviceLocator->get('request');
829
            //if ($r->getQuery()->get('preview')) {
830
                $game->setActive(true);
831
                $game->setStartDate(null);
832
                $game->setEndDate(null);
833
                $game->setPublicationDate(null);
834
                $game->setBroadcastPlatform(true);
835
836
                // I don't want the game to be updated through any update during the preview mode.
837
                // I mark it as readonly for Doctrine
838
                $this->serviceLocator
839
                    ->get('doctrine.entitymanager.orm_default')
840
                    ->getUnitOfWork()
841
                    ->markReadOnly($game);
842
                    
843
                return $game;
844
            //}
845
        }
846
847
        // The game is inactive
848
        if (! $game->getActive()) {
849
            return false;
850
        }
851
852
        // the game has not begun yet
853
        if (! $game->isOpen()) {
854
            return false;
855
        }
856
857
        // the game is finished and closed
858
        if (! $game->isStarted() && $checkIfStarted) {
859
            return false;
860
        }
861
862
        return $game;
863
    }
864
865
    /**
866
     * Return the last entry of the user on this game, if it exists.
867
     * An entry can be associated to :
868
     * - A user account (a real one, linked to PlaygroundUser
869
     * - An anonymous Identifier (based on one value of playerData (generally email))
870
     * - A cookie set on the player device (the less secure)
871
     * If the active param is set, it can check if the entry is active or not.
872
     * If the bonus param is set, it can check if the entry is a bonus or not.
873
     *
874
     * @param unknown $game
875
     * @param string $user
876
     * @param boolean $active
877
     * @param boolean $bonus
878
     * @return boolean
879
     */
880
    public function checkExistingEntry($game, $user = null, $active = null, $bonus = null)
881
    {
882
        $search = array('game'  => $game);
883
884
        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...
885
            $search['user'] = $user;
886
        } elseif ($this->getAnonymousIdentifier()) {
887
            $search['anonymousIdentifier'] = $this->getAnonymousIdentifier();
888
            $search['user'] = null;
889
        } else {
890
            $search['anonymousId'] = $this->getAnonymousId();
891
            $search['user'] = null;
892
        }
893
        
894
        if (! is_null($active)) {
895
            $search['active'] = $active;
896
        }
897
        if (! is_null($bonus)) {
898
            $search['bonus'] = $bonus;
899
        }
900
901
        $entry = $this->getEntryMapper()->findOneBy($search, array('updated_at' => 'desc'));
902
903
        return $entry;
904
    }
905
906
    /*
907
    * This function updates the entry with the player data after checking
908
    * that the data are compliant with the formUser Game attribute
909
    *
910
    * The $data has to be a json object
911
    */
912
    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...
913
    {
914
        $form = $this->createFormFromJson($game->getPlayerForm()->getForm(), 'playerForm');
915
        $form->setData($data);
916
917
        if (!$mandatory) {
918
            $filter = $form->getInputFilter();
919
            foreach ($form->getElements() as $element) {
920
                try {
921
                    $elementInput = $filter->get($element->getName());
922
                    $elementInput->setRequired(false);
923
                    $form->get($element->getName())->setAttribute('required', false);
924
                } 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...
925
                }
926
            }
927
        }
928
929
        if ($form->isValid()) {
930
            $dataJson = json_encode($form->getData());
931
932
            if ($game->getAnonymousAllowed() &&
933
                $game->getAnonymousIdentifier() &&
934
                isset($data[$game->getAnonymousIdentifier()])
935
            ) {
936
                $session = new \Zend\Session\Container('anonymous_identifier');
937
                $anonymousIdentifier = $data[$game->getAnonymousIdentifier()];
938
                $entry->setAnonymousIdentifier($anonymousIdentifier);
939
                if (empty($session->offsetGet('anonymous_identifier'))) {
940
                    $session->offsetSet('anonymous_identifier', $anonymousIdentifier);
941
                }
942
            }
943
944
            $entry->setPlayerData($dataJson);
945
            $this->getEntryMapper()->update($entry);
946
        } else {
947
            return false;
948
        }
949
950
        return true;
951
    }
952
953
954
    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...
955
    {
956
        // If on Facebook, check if you have to be a FB fan to play the game
957
        $session = new Container('facebook');
958
959
        if ($session->offsetExists('signed_request')) {
960
            // I'm on Facebook
961
            $sr = $session->offsetGet('signed_request');
962
            if ($sr['page']['liked'] == 1) {
963
                return true;
964
            }
965
        } else {
966
            // I'm not on Facebook
967
            return true;
968
        }
969
970
        return false;
971
    }
972
    
973
    public function getAnonymousIdentifier()
974
    {
975
        if (is_null($this->anonymousIdentifier) || $this->anonymousIdentifier === false) {
976
            $session = new Container('anonymous_identifier');
977
            
978
            if ($session->offsetExists('anonymous_identifier')) {
979
                $this->anonymousIdentifier = $session->offsetGet('anonymous_identifier');
980
            } else {
981
                $this->anonymousIdentifier = false;
982
            }
983
        }
984
    
985
        return $this->anonymousIdentifier;
986
    }
987
988
    /**
989
     * setTermsOptin
990
     *
991
     * @return Boolean the result of the terms optin update
992
     */
993
    public function setTermsOptin($optin, $game, $user)
994
    {
995
        $entry = $this->checkExistingEntry($game, $user, true);
996
997
        if ($entry) {
998
            $entry->setTermsOptin($optin);
0 ignored issues
show
Bug introduced by
The method setTermsOptin cannot be called on $entry (of type boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
999
            $entry = $this->getEntryMapper()->update($entry);
1000
        } else {
1001
            if (!$this->hasReachedPlayLimit($game, $user)
1002
                && $this->canPayToPlay($game, $user)
1003
            ) {
1004
                $ip = $this->getIp();
1005
                $geoloc = $this->getGeoloc($ip);
1006
                $entry = new Entry();
1007
                $entry->setGame($game);
1008
                $entry->setUser($user);
1009
                $entry->setPoints(0);
1010
                $entry->setIp($ip);
1011
                $entry->setGeoloc($geoloc);
1012
                $entry->setAnonymousId($this->getAnonymousId());
1013
                if ($this->getAnonymousIdentifier()) {
1014
                    $entry->setAnonymousIdentifier($this->getAnonymousIdentifier());
1015
                }
1016
                $entry->setTermsOptin($optin);
1017
                $entry = $this->getEntryMapper()->insert($entry);
1018
            }
1019
        }
1020
1021
        if ($entry) {
1022
            $this->getEventManager()->trigger(
1023
                __FUNCTION__ . '.post',
1024
                $this,
1025
                [
1026
                    'user' => $user,
1027
                    'game' => $game,
1028
                    'entry' => $entry,
1029
                ]
1030
            );
1031
1032
            return true;
1033
        }
1034
1035
        return false;
1036
    }
1037
1038
    /**
1039
     * errors :
1040
     * -1 : limit entry games for this user reached
1041
     * -2 : no terms optin
1042
     * -3 : no payment
1043
     *
1044
     * @param \PlaygroundGame\Entity\Game $game
1045
     * @param \PlaygroundUser\Entity\UserInterface $user
1046
     * @return number unknown
1047
     */
1048
    public function play($game, $user, &$error = null)
1049
    {
1050
        //some entries can stay open during days.
1051
        // The player can take back the entry to go on playing
1052
        // like in a postvote or for quizzes
1053
        // We create also an entry before the game when an optin is needed
1054
        $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...
1055
1056
        // If the game needs an optin and the player has not opted in
1057
        if ($entry && $game->getTermsOptin() && !$entry->getTermsOptin()) {
0 ignored issues
show
Bug introduced by
The method getTermsOptin cannot be called on $entry (of type boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
1058
            $error = -2;
1059
            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...
1060
        }
1061
1062
        // If the game has a cost and the player has not paid yet
1063
        // (this case occurs when the entry has been created by the termsOptin
1064
        // and the game has a price to play)
1065
        if ($entry && !$entry->getPaid() && $game->getCostToPlay() > 0) {
0 ignored issues
show
Bug introduced by
The method getPaid cannot be called on $entry (of type boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
1066
            if (!$this->payToPlay($game, $user, $entry)) {
1067
                $error = -3;
1068
                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...
1069
            } else {
1070
                $entry->setPaid(1);
0 ignored issues
show
Bug introduced by
The method setPaid cannot be called on $entry (of type boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
1071
                $entry->setPaidAmount($game->getCostToPlay());
0 ignored issues
show
Bug introduced by
The method setPaidAmount cannot be called on $entry (of type boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
1072
                $entry = $this->getEntryMapper()->update($entry);
1073
            }
1074
        }
1075
1076
        if (! $entry) {
1077
            // Play limit reached
1078
            if ($this->hasReachedPlayLimit($game, $user)) {
1079
                $error = -1;
1080
                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...
1081
            }
1082
            // Can't pay for the game
1083
            if (!$this->canPayToPlay($game, $user)) {
1084
                $error = -3;
1085
                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...
1086
            }
1087
            // Terms optin not checked
1088
            if ($game->getTermsOptin()) {
1089
                $error = -2;
1090
                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...
1091
            }
1092
1093
            $ip = $this->getIp();
1094
            $geoloc = $this->getGeoloc($ip);
1095
            $entry = new Entry();
1096
            $entry->setGame($game);
1097
            $entry->setUser($user);
1098
            $entry->setPoints(0);
1099
            $entry->setIp($ip);
1100
            $entry->setGeoloc($geoloc);
1101
            $entry->setAnonymousId($this->getAnonymousId());
1102
            
1103
            if ($this->getAnonymousIdentifier()) {
1104
                $entry->setAnonymousIdentifier($this->getAnonymousIdentifier());
1105
            }
1106
            if ($game->getCostToPlay() === 0) {
1107
                $entry->setPaid(true);
1108
                $entry = $this->getEntryMapper()->insert($entry);
1109
                $this->getEventManager()->trigger(
1110
                    __FUNCTION__ . '.post',
1111
                    $this,
1112
                    [
1113
                        'user' => $user,
1114
                        'game' => $game,
1115
                        'entry' => $entry,
1116
                    ]
1117
                );
1118
            } else {
1119
                $entry = $this->getEntryMapper()->insert($entry);
1120
                $entryPaid = $this->payToPlay($game, $user, $entry);
1121
                if ($entryPaid) {
1122
                    $entry = $this->getEntryMapper()->update($entryPaid);
1123
                    $this->getEventManager()->trigger(
1124
                        __FUNCTION__ . '.post',
1125
                        $this,
1126
                        [
1127
                            'user' => $user,
1128
                            'game' => $game,
1129
                            'entry' => $entry,
1130
                        ]
1131
                    );
1132
                } else {
1133
                    $entry->setActive(false);
1134
                    $entry = $this->getEntryMapper()->update($entry);
0 ignored issues
show
Unused Code introduced by
$entry 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...
1135
                    $error = -3;
1136
                    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...
1137
                }
1138
            }
1139
        }
1140
1141
        return $entry;
1142
    }
1143
1144
    /**
1145
     * @param \PlaygroundGame\Entity\Game $game
1146
     * @param \PlaygroundUser\Entity\UserInterface $user
1147
     */
1148
    public function hasReachedPlayLimit($game, $user)
1149
    {
1150
        // Is there a limitation on the game ?
1151
        $limitAmount = $game->getPlayLimit();
1152
        if ($limitAmount) {
1153
            $limitScale = $game->getPlayLimitScale();
1154
            $userEntries = $this->findLastEntries($game, $user, $limitScale);
1155
1156
            // player has reached the game limit
1157
            if ($userEntries >= $limitAmount) {
1158
                return true;
1159
            }
1160
        }
1161
        return false;
1162
    }
1163
1164
    /**
1165
     * If the game has a cost to be played (costToPlay>0)
1166
     * I check and decrement the price from the leaderboard all of the user
1167
     *
1168
     * @param \PlaygroundGame\Entity\Game $game
1169
     * @param \PlaygroundUser\Entity\UserInterface $user
1170
     */
1171
    public function canPayToPlay($game, $user)
1172
    {
1173
        // Is there a limitation on the game ?
1174
        $cost = $game->getCostToPlay();
1175
        if ($cost && $cost > 0) {
1176
            $availableAmount = $this->getEventManager()->trigger(
1177
                'leaderboardUserTotal',
1178
                $this,
1179
                [
1180
                    'user' => $user,
1181
                ]
1182
            )->last();
1183
            if ($availableAmount && $availableAmount >= $cost) {
1184
                return true;
1185
            }
1186
        } else {
1187
            return true;
1188
        }
1189
1190
        return false;
1191
    }
1192
1193
    /**
1194
     * If the game has a cost to be played (costToPlay>0)
1195
     * I check and decrement the price from the leaderboard all of the user
1196
     *
1197
     * @param \PlaygroundGame\Entity\Game $game
1198
     * @param \PlaygroundUser\Entity\UserInterface $user
1199
     */
1200
    public function payToPlay($game, $user, $entry)
1201
    {
1202
        // Is there a limitation on the game ?
1203
        $cost = $game->getCostToPlay();
1204
        if ($cost && $cost > 0) {
1205
            if ($this->canPayToPlay($game, $user)) {
1206
                $entry->setPaid(true);
1207
                $entry->setPaidAmount(-$cost);
1208
                $leaderboard = $this->getEventManager()->trigger(
0 ignored issues
show
Unused Code introduced by
$leaderboard 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...
1209
                    'leaderboardUserUpdate',
1210
                    $this,
1211
                    [
1212
                        'user' => $user,
1213
                        'game' => $game,
1214
                        'points' => -$cost,
1215
                        'entry' => $entry,
1216
                    ]
1217
                )->last();
1218
1219
                return $entry;
1220
            }
1221
        } else {
1222
            $entry->setPaid(true);
1223
            return $entry;
1224
        }
1225
1226
        return false;
1227
    }
1228
    
1229
    /**
1230
     * @param \PlaygroundGame\Entity\Game $game
1231
     * @param \PlaygroundUser\Entity\UserInterface $user
1232
     */
1233
    public function findLastEntries($game, $user, $limitScale)
1234
    {
1235
        $limitDate = $this->getLimitDate($limitScale);
1236
1237
        if ($user) {
1238
            return $this->getEntryMapper()->countLastEntriesByUser($game, $user, $limitDate);
1239
        } elseif ($this->getAnonymousIdentifier()) {
1240
            $entries = $this->getEntryMapper()->countLastEntriesByAnonymousIdentifier(
1241
                $game,
1242
                $this->getAnonymousIdentifier(),
1243
                $limitDate
1244
            );
1245
1246
            return $entries;
1247 View Code Duplication
        } else {
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...
1248
            // If the game is supposed to be a reguler user game or an anonymous identified game,
1249
            // it means that the registration/login is at the end of the game
1250
            if ((!$user &&  !$game->getAnonymousAllowed()) || ($game->getAnonymousAllowed() && $game->getAnonymousIdentifier())) {
1251
                return 0;
1252
            }
1253
            return $this->getEntryMapper()->countLastEntriesByIp($game, $this->getIp(), $limitDate);
1254
        }
1255
    }
1256
1257
    /**
1258
    *
1259
    *
1260
    */
1261
    public function getLimitDate($limitScale)
1262
    {
1263
        $now = new \DateTime("now");
1264
        switch ($limitScale) {
1265
            case 'always':
1266
                $interval = 'P100Y';
1267
                $now->sub(new \DateInterval($interval));
1268
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
1269
                break;
1270
            case 'day':
1271
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
1272
                break;
1273 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...
1274
                $interval = 'P7D';
1275
                $now->sub(new \DateInterval($interval));
1276
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
1277
                break;
1278 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...
1279
                $interval = 'P1M';
1280
                $now->sub(new \DateInterval($interval));
1281
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
1282
                break;
1283 View Code Duplication
            case 'year':
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...
1284
                $interval = 'P1Y';
1285
                $now->sub(new \DateInterval($interval));
1286
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
1287
                break;
1288 View Code Duplication
            default:
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...
1289
                $interval = 'P100Y';
1290
                $now->sub(new \DateInterval($interval));
1291
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
1292
        }
1293
1294
        return $dateLimit;
1295
    }
1296
1297
    public function findLastActiveEntry($game, $user)
1298
    {
1299
        return $this->checkExistingEntry($game, $user, true);
1300
    }
1301
1302
    public function findLastInactiveEntry($game, $user)
1303
    {
1304
        return $this->checkExistingEntry($game, $user, false, false);
1305
    }
1306
1307
    public function findLastEntry($game, $user)
1308
    {
1309
        return $this->checkExistingEntry($game, $user, null, false);
1310
    }
1311
1312
    public function inviteToTeam($data, $game, $user)
1313
    {
1314
        $mailService = $this->serviceLocator->get('playgroundgame_message');
1315
        $invitationMapper = $this->serviceLocator->get('playgroundgame_invitation_mapper');
1316
1317
        $sentInvitations = $invitationMapper->findBy(array('host' => $user, 'game' => $game));
1318
        $nbInvitations = count($sentInvitations);
1319
        $to = $data['email'];
1320
        if (empty($to)) {
1321
            return ['result'=>false, 'message'=>'no email'];
1322
        }
1323
1324
        if ($nbInvitations < 20) {
1325
            $alreadyInvited = $invitationMapper->findBy(array('requestKey' => $to, 'game' => $game));
1326
            if (!$alreadyInvited) {
1327
                $alreadyInvited = $this->getUserMapper()->findByEmail($to);
1328
            }
1329
1330
            if (empty($alreadyInvited)) {
1331
                $invitation = new \PlaygroundGame\Entity\Invitation();
1332
                $invitation->setRequestKey($to);
1333
                $invitation->setGame($game);
1334
                $invitation->setHost($user);
1335
                $invitationMapper->insert($invitation);
1336
1337
                $from = $this->getOptions()->getEmailFromAddress();
1338
                $subject = $this->serviceLocator->get('MvcTranslator')->translate(
1339
                    $this->getOptions()->getInviteToTeamSubjectLine(),
1340
                    'playgroundgame'
1341
                );
1342
                $message = $mailService->createHtmlMessage(
1343
                    $from,
1344
                    $to,
1345
                    $subject,
1346
                    'playground-game/email/invite_team',
1347
                    array(
1348
                        'game' => $game,
1349
                        'user' => $user,
1350
                        'data' => $data,
1351
                        'from' => $from
1352
                    )
1353
                );
1354
                try {
1355
                    $mailService->send($message);
1356
                } catch (\Zend\Mail\Protocol\Exception\RuntimeException $e) {
0 ignored issues
show
Bug introduced by
The class Zend\Mail\Protocol\Exception\RuntimeException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
1357
                    return ['result' => true, 'message' => $this->serviceLocator->get('MvcTranslator')->translate(
1358
                        'mail error'
1359
                    )];
1360
                }
1361
1362
                return ['result' => true, 'message' => ''];
1363
            } else {
1364
                return ['result' => false, 'message' => 'already invited'];
1365
            }
1366
        } else {
1367
            return [
1368
                'result' => false,
1369
                'message' => $this->serviceLocator->get('MvcTranslator')->translate(
1370
                    'Too many invitations for this user'
1371
                )
1372
            ];
1373
        }
1374
    }
1375
1376
    public function sendShareMail(
1377
        $data,
1378
        $game,
1379
        $user,
1380
        $entry,
1381
        $template = 'share_game',
1382
        $subject = ''
1383
    ) {
1384
        $mailService = $this->serviceLocator->get('playgroundgame_message');
1385
        $mailSent = false;
1386
        $from = $this->getOptions()->getEmailFromAddress();
1387
1388
        if (empty($subject) && $game) {
1389
            $subject = $game->getEmailShareSubject();
1390
        }
1391
1392
        $message = '';
1393
        if ($game && !empty($game->getEmailShareMessage())) {
1394
            $message = $game->getEmailShareMessage();
1395
        }
1396
1397
        $renderer = $this->serviceLocator->get('Zend\View\Renderer\RendererInterface');
1398
        $skinUrl = $renderer->url(
1399
            'frontend',
1400
            array(),
1401
            array('force_canonical' => true)
1402
        );
1403
        $secretKey = strtoupper(substr(sha1(uniqid('pg_', true) . '####' . time()), 0, 15));
1404
1405
        if (isset($data['email']) && !is_array($data['email'])) {
1406
            $data['email'] = array($data['email']);
1407
        }
1408
        
1409
        foreach ($data['email'] as $to) {
1410
            $mailSent = true;
1411
            if (!empty($to)) {
1412
                $message = $mailService->createHtmlMessage(
1413
                    $from,
1414
                    $to,
1415
                    $subject,
1416
                    'playground-game/email/' . $template,
1417
                    array(
1418
                        'game' => $game,
1419
                        'data' => $data,
1420
                        'from' => $from,
1421
                        'to' => $to,
1422
                        'secretKey' => $secretKey,
1423
                        'skinUrl' => $skinUrl,
1424
                        'message' => $message,
1425
                    )
1426
                );
1427
                try {
1428
                    $mailService->send($message);
1429
                } 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...
Bug introduced by
The class Zend\Mail\Protocol\Exception\RuntimeException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
1430
                }
1431
                
1432
                if ($entry) {
1433
                    $shares = json_decode($entry->getSocialShares(), true);
1434
                    (!isset($shares['mail']))? $shares['mail'] = 1:$shares['mail'] += 1;
1435
                }
1436
                $this->getEventManager()->trigger(
1437
                    __FUNCTION__ . '.post',
1438
                    $this,
1439
                    array(
1440
                        'user' => $user,
1441
                        'secretKey' => $secretKey,
1442
                        'data' => $data,
1443
                        'game' => $game,
1444
                        'entry' => $entry,
1445
                        'message' => $message,
1446
                        'to' => $to,
1447
                    )
1448
                );
1449
            }
1450
        }
1451
1452
        if ($mailSent) {
1453
            if ($entry) {
1454
                $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...
1455
                $entry->setSocialShares($sharesJson);
1456
                $entry = $this->getEntryMapper()->update($entry);
0 ignored issues
show
Unused Code introduced by
$entry 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...
1457
            }
1458
1459
            return true;
1460
        }
1461
1462
        return false;
1463
    }
1464
1465
    /**
1466
     * @param \PlaygroundGame\Entity\Game $game
1467
     * @param \PlaygroundUser\Entity\User $user
1468
     * @param Entry $entry
1469
     * @param \PlaygroundGame\Entity\Prize $prize
1470
     */
1471
    public function sendResultMail($game, $user, $entry, $template = 'entry', $prize = null)
1472
    {
1473
        $mailService = $this->serviceLocator->get('playgroundgame_message');
1474
        $from = $this->getOptions()->getEmailFromAddress();
1475
        if ($entry->getAnonymousIdentifier()) {
1476
            $to = $entry->getAnonymousIdentifier();
1477
        } elseif ($user) {
1478
            $to = $user->getEmail();
1479
        } else {
1480
            return false;
1481
        }
1482
        $subject = $this->serviceLocator->get('MvcTranslator')->translate(
1483
            $this->getOptions()->getParticipationSubjectLine(),
1484
            'playgroundgame'
1485
        );
1486
        $renderer = $this->serviceLocator->get('Zend\View\Renderer\RendererInterface');
1487
        $skinUrl = $renderer->url(
1488
            'frontend',
1489
            array(),
1490
            array('force_canonical' => true)
1491
        );
1492
        $message = $mailService->createHtmlMessage($from, $to, $subject, 'playground-game/email/' . $template, array(
1493
            'game' => $game,
1494
            'entry' => $entry,
1495
            'skinUrl' => $skinUrl,
1496
            'prize' => $prize
1497
        ));
1498
        $mailService->send($message);
1499
    }
1500
1501
    public function sendGameMail($game, $user, $post, $template = 'postvote')
1502
    {
1503
        $mailService = $this->serviceLocator->get('playgroundgame_message');
1504
        $from = $this->getOptions()->getEmailFromAddress();
1505
        $to = $user->getEmail();
1506
        $subject = $this->serviceLocator->get('MvcTranslator')->translate(
1507
            $this->getOptions()->getParticipationSubjectLine(),
1508
            'playgroundgame'
1509
        );
1510
        $renderer = $this->serviceLocator->get('Zend\View\Renderer\RendererInterface');
1511
        $skinUrl = $renderer->url(
1512
            'frontend',
1513
            array(),
1514
            array('force_canonical' => true)
1515
        );
1516
1517
        $message = $mailService->createHtmlMessage($from, $to, $subject, 'playground-game/email/' . $template, array(
1518
            'game' => $game,
1519
            'post' => $post,
1520
            'skinUrl' => $skinUrl
1521
        ));
1522
        $mailService->send($message);
1523
    }
1524
1525 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...
1526
    {
1527
        $topic = $game->getTitle();
1528
        
1529
        $shares = json_decode($entry->getSocialShares(), true);
1530
        if (!isset($shares['fbwall'])) {
1531
            $shares['fbwall'] = 1;
1532
        } else {
1533
            $shares['fbwall'] += 1;
1534
        }
1535
        $sharesJson = json_encode($shares);
1536
        $entry->setSocialShares($sharesJson);
1537
        $entry = $this->getEntryMapper()->update($entry);
1538
        
1539
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1540
            'user' => $user,
1541
            'game' => $game,
1542
            'secretKey' => $secretKey,
1543
            'topic' => $topic,
1544
            'entry' => $entry
1545
        ));
1546
1547
        return true;
1548
    }
1549
1550
    public function postFbRequest($secretKey, $game, $user, $entry, $to)
1551
    {
1552
        $shares = json_decode($entry->getSocialShares(), true);
1553
        $to = explode(',', $to);
1554
        if (!isset($shares['fbrequest'])) {
1555
            $shares['fbrequest'] = count($to);
1556
        } else {
1557
            $shares['fbrequest'] += count($to);
1558
        }
1559
        $sharesJson = json_encode($shares);
1560
        $entry->setSocialShares($sharesJson);
1561
        $entry = $this->getEntryMapper()->update($entry);
1562
        
1563
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1564
            'user' => $user,
1565
            'game' => $game,
1566
            'secretKey' => $secretKey,
1567
            'entry' => $entry,
1568
            'invites' => count($to)
1569
        ));
1570
1571
        return true;
1572
    }
1573
1574 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...
1575
    {
1576
        $topic = $game->getTitle();
1577
1578
        $shares = json_decode($entry->getSocialShares(), true);
1579
        if (!isset($shares['fbrequest'])) {
1580
            $shares['tweet'] = 1;
1581
        } else {
1582
            $shares['tweet'] += 1;
1583
        }
1584
        $sharesJson = json_encode($shares);
1585
        $entry->setSocialShares($sharesJson);
1586
        $entry = $this->getEntryMapper()->update($entry);
1587
        
1588
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1589
            'user' => $user,
1590
            'game' => $game,
1591
            'secretKey' => $secretKey,
1592
            'topic' => $topic,
1593
            'entry' => $entry
1594
        ));
1595
1596
        return true;
1597
    }
1598
1599 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...
1600
    {
1601
        $topic = $game->getTitle();
1602
        
1603
        $shares = json_decode($entry->getSocialShares(), true);
1604
        if (!isset($shares['fbrequest'])) {
1605
            $shares['google'] = 1;
1606
        } else {
1607
            $shares['google'] += 1;
1608
        }
1609
        $sharesJson = json_encode($shares);
1610
        $entry->setSocialShares($sharesJson);
1611
        $entry = $this->getEntryMapper()->update($entry);
1612
1613
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1614
            'user' => $user,
1615
            'game' => $game,
1616
            'secretKey' => $secretKey,
1617
            'topic' => $topic,
1618
            'entry' => $entry
1619
        ));
1620
1621
        return true;
1622
    }
1623
1624
    /**
1625
     * Is it possible to trigger a bonus entry ?
1626
     *
1627
     * @param unknown_type $game
1628
     * @param unknown_type $user
1629
     */
1630
    public function allowBonus($game, $user)
1631
    {
1632
        if (! $game->getPlayBonus() || $game->getPlayBonus() == 'none') {
1633
            return false;
1634
        } elseif ($game->getPlayBonus() == 'one') {
1635
            if ($this->getEntryMapper()->findOneBy(array(
1636
                'game' => $game,
1637
                'user' => $user,
1638
                'bonus' => 1
1639
            ))) {
1640
                return false;
1641
            } else {
1642
                return true;
1643
            }
1644
        } elseif ($game->getPlayBonus() == 'per_entry') {
1645
            return $this->getEntryMapper()->checkBonusEntry($game, $user);
1646
        }
1647
1648
        return false;
1649
    }
1650
1651
    public function addAnotherEntry($game, $user, $winner = 0)
1652
    {
1653
        $entry = new Entry();
1654
        $entry->setGame($game);
1655
        $entry->setUser($user);
1656
        $entry->setPoints(0);
1657
        $entry->setIp($this->getIp());
1658
        $entry->setActive(0);
1659
        $entry->setBonus(1);
1660
        $entry->setWinner($winner);
1661
        $entry = $this->getEntryMapper()->insert($entry);
1662
1663
        return $entry;
1664
    }
1665
1666
    /**
1667
     * This bonus entry doesn't give points nor badges
1668
     * It's just there to increase the chances during the Draw
1669
     * Old Name playBonus
1670
     *
1671
     * @param PlaygroundGame\Entity\Game $game
1672
     * @param unknown $user
1673
     * @return boolean unknown
1674
     */
1675
    public function addAnotherChance($game, $user, $winner = 0)
1676
    {
1677
        if ($this->allowBonus($game, $user)) {
1678
            $this->addAnotherEntry($game, $user, $winner);
1679
1680
            return true;
1681
        }
1682
1683
        return false;
1684
    }
1685
1686
    /**
1687
     * This bonus entry doesn't give points nor badges but can play again
1688
     *
1689
     * @param PlaygroundGame\Entity\Game $game
1690
     * @param user $user
1691
     * @return boolean unknown
1692
     */
1693
    public function playAgain($game, $user, $winner = 0)
1694
    {
1695
        if ($this->allowBonus($game, $user)) {
1696
            $entry = $this->addAnotherEntry($game, $user, $winner);
1697
            $entry->setActive(1);
1698
            $entry = $this->getEntryMapper()->update($entry);
1699
            if ($entry->getActive() == 1) {
1700
                return true;
1701
            }
1702
        }
1703
1704
        return false;
1705
    }
1706
1707
    /**
1708
     * @param string $path
1709
     * @param boolean $noReplace : If the image name already exist, don't replace it but change the name
1710
     */
1711
    public function uploadFile($path, $file, $noReplace = true)
1712
    {
1713
        $err = $file["error"];
1714
        $message = '';
1715
        if ($err > 0) {
1716
            switch ($err) {
1717
                case '1':
1718
                    $message .= 'Max file size exceeded. (php.ini)';
1719
                    break;
1720
                case '2':
1721
                    $message .= 'Max file size exceeded.';
1722
                    break;
1723
                case '3':
1724
                    $message .= 'File upload was only partial.';
1725
                    break;
1726
                case '4':
1727
                    $message .= 'No file was attached.';
1728
                    break;
1729
                case '7':
1730
                    $message .= 'File permission denied.';
1731
                    break;
1732
                default:
1733
                    $message .= 'Unexpected error occurs.';
1734
            }
1735
1736
            return $err;
1737
        } else {
1738
            $fileNewname = $this->fileNewname($path, $file['name'], $noReplace);
1739
1740
            if (isset($file["base64"])) {
1741
                list(, $img) = explode(',', $file["base64"]);
1742
                $img = str_replace(' ', '+', $img);
1743
                $im = base64_decode($img);
1744
                if ($im !== false) {
1745
                    // getimagesizefromstring
1746
                    file_put_contents($path . $fileNewname, $im);
1747
                } else {
1748
                    return 1;
1749
                }
1750
1751
                return $fileNewname;
1752
            } else {
1753
                $adapter = new \Zend\File\Transfer\Adapter\Http();
1754
                // 1Mo
1755
                $size = new Size(array(
1756
                    'max' => 1024000
1757
                ));
1758
                $is_image = new IsImage('jpeg,png,gif,jpg');
1759
                $adapter->setValidators(array(
1760
                    $size,
1761
                    $is_image
1762
                ), $fileNewname);
1763
1764
                if (! $adapter->isValid()) {
1765
                    return false;
1766
                }
1767
1768
                @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...
1769
            }
1770
1771
            
1772
            if (class_exists("Imagick")) {
1773
                $ext = pathinfo($fileNewname, PATHINFO_EXTENSION);
1774
                $img = new \Imagick($path . $fileNewname);
1775
                $img->cropThumbnailImage(100, 100);
1776
                $img->setImageCompression(\Imagick::COMPRESSION_JPEG);
1777
                $img->setImageCompressionQuality(75);
1778
                // Strip out unneeded meta data
1779
                $img->stripImage();
1780
                $img->writeImage($path . str_replace('.'.$ext, '-thumbnail.'.$ext, $fileNewname));
1781
                ErrorHandler::stop(true);
1782
            }
1783
        }
1784
1785
        return $fileNewname;
1786
    }
1787
1788
    /**
1789
     * @param string $path
1790
     */
1791
    public function fileNewname($path, $filename, $generate = false)
1792
    {
1793
        $sanitize = new Sanitize();
1794
        $name = $sanitize->filter($filename);
1795
        $newpath = $path . $name;
1796
1797
        if ($generate) {
1798
            if (file_exists($newpath)) {
1799
                $filename = pathinfo($name, PATHINFO_FILENAME);
1800
                $ext = pathinfo($name, PATHINFO_EXTENSION);
1801
1802
                $name = $filename . '_' . rand(0, 99) . '.' . $ext;
1803
            }
1804
        }
1805
1806
        unset($sanitize);
1807
1808
        return $name;
1809
    }
1810
1811
    /**
1812
     * This function returns the list of games, ordered by $type
1813
     */
1814
    public function getQueryGamesOrderBy($type = 'createdAt', $order = 'DESC')
1815
    {
1816
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
1817
        $today = new \DateTime("now");
1818
        $today = $today->format('Y-m-d H:i:s');
1819
1820
        $onlineGames = '(
1821
            (
1822
                CASE WHEN (
1823
                    g.active = 1
1824
                    AND g.broadcastPlatform = 1
1825
                    AND (g.startDate <= :date OR g.startDate IS NULL)
1826
                    AND (g.closeDate >= :date OR g.closeDate IS NULL)
1827
                ) THEN 1 ELSE 0 END
1828
            ) +
1829
            (
1830
                CASE WHEN (
1831
                    g.active = 0
1832
                    AND (g.broadcastPlatform = 0 OR g.broadcastPlatform IS NULL)
1833
                    AND g.startDate > :date
1834
                    AND g.closeDate < :date
1835
                ) THEN 1 ELSE 0 END
1836
            )
1837
        )';
1838
1839
        $qb = $em->createQueryBuilder();
1840
        $qb->select('g')->from('PlaygroundGame\Entity\Game', 'g');
1841
        
1842
        switch ($type) {
1843
            case 'startDate':
1844
                $qb->orderBy('g.startDate', $order);
1845
                break;
1846
            case 'activeGames':
1847
                $qb->orderBy('g.active', $order);
1848
                break;
1849
            case 'onlineGames':
1850
                $qb->orderBy($onlineGames, $order);
1851
                $qb->setParameter('date', $today);
1852
                break;
1853
            case 'createdAt':
1854
                $qb->orderBy('g.createdAt', $order);
1855
                break;
1856
        }
1857
1858
        $query = $qb->getQuery();
1859
1860
        return $query;
1861
    }
1862
1863
    public function draw($game)
1864
    {
1865
        $total = $game->getWinners();
1866
1867
        // I Have to know what is the User Class used
1868
        $zfcUserOptions = $this->serviceLocator->get('zfcuser_module_options');
1869
        $userClass = $zfcUserOptions->getUserEntityClass();
1870
1871
        $result = $this->getEntryMapper()->draw($game, $userClass, $total);
1872
1873
        foreach ($result as $e) {
1874
            $e->setWinner(1);
1875
            $e = $this->getEntryMapper()->update($e);
1876
            $this->getEventManager()->trigger('win_lottery.post', $this, array(
1877
                'user' => $e->getUser(),
1878
                'game' => $game,
1879
                'entry' => $e
1880
            ));
1881
        }
1882
1883
        return $result;
1884
    }
1885
1886
    /**
1887
     * getGameMapper
1888
     *
1889
     * @return GameMapperInterface
1890
     */
1891 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...
1892
    {
1893
        if (null === $this->gameMapper) {
1894
            $this->gameMapper = $this->serviceLocator->get('playgroundgame_game_mapper');
1895
        }
1896
1897
        return $this->gameMapper;
1898
    }
1899
1900
    /**
1901
     * setGameMapper
1902
     *
1903
     * @param GameMapperInterface $gameMapper
1904
     * @return Game
1905
     */
1906
    public function setGameMapper(GameMapperInterface $gameMapper)
1907
    {
1908
        $this->gameMapper = $gameMapper;
1909
1910
        return $this;
1911
    }
1912
1913
    /**
1914
     * getEntryMapper
1915
     *
1916
     * @return EntryMapperInterface
1917
     */
1918
    public function getEntryMapper()
1919
    {
1920
        if (null === $this->entryMapper) {
1921
            $this->entryMapper = $this->serviceLocator->get('playgroundgame_entry_mapper');
1922
        }
1923
1924
        return $this->entryMapper;
1925
    }
1926
1927
    /**
1928
     * setEntryMapper
1929
     *
1930
     * @param EntryMapperInterface $entryMapper
1931
     * @return Game
1932
     */
1933
    public function setEntryMapper($entryMapper)
1934
    {
1935
        $this->entryMapper = $entryMapper;
1936
1937
        return $this;
1938
    }
1939
1940
    public function setOptions(ModuleOptions $options)
1941
    {
1942
        $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...
1943
1944
        return $this;
1945
    }
1946
1947
    public function getOptions()
1948
    {
1949
        if (! $this->options instanceof ModuleOptions) {
1950
            $this->setOptions($this->serviceLocator
1951
                ->get('playgroundgame_module_options'));
1952
        }
1953
1954
        return $this->options;
1955
    }
1956
1957
    /**
1958
     * @param string $str
1959
     */
1960
    public function getExtension($str)
1961
    {
1962
        $i = strrpos($str, '.');
1963
1964
        $l = strlen($str) - $i;
1965
        $ext = substr($str, $i + 1, $l);
1966
1967
        return $ext;
1968
    }
1969
1970
    /**
1971
     * @param string $extension
1972
     */
1973
    public function getSrc($extension, $temp_path)
1974
    {
1975
        $image_src = '';
1976
        switch ($extension) {
1977
            case 'jpg':
1978
                $image_src = imagecreatefromjpeg($temp_path);
1979
                break;
1980
            case 'jpeg':
1981
                $image_src = imagecreatefromjpeg($temp_path);
1982
                break;
1983
            case 'png':
1984
                $image_src = imagecreatefrompng($temp_path);
1985
                break;
1986
            case 'gif':
1987
                $image_src = imagecreatefromgif($temp_path);
1988
                break;
1989
        }
1990
1991
        return $image_src;
1992
    }
1993
1994
    /**
1995
     * @param string $extension
1996
     * @param string $rep
1997
     * @param integer $mini_width
1998
     * @param integer $mini_height
1999
     */
2000
    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...
2001
    {
2002
        list($src_width, $src_height) = getimagesize($tmp_file);
2003
2004
        $ratio_src = $src_width / $src_height;
2005
        $ratio_mini = $mini_width / $mini_height;
2006
2007
        if ($ratio_src >= $ratio_mini) {
2008
            $new_height_mini = $mini_height;
2009
            $new_width_mini = $src_width / ($src_height / $mini_height);
2010
        } else {
2011
            $new_width_mini = $mini_width;
2012
            $new_height_mini = $src_height / ($src_width / $mini_width);
2013
        }
2014
2015
        $new_image_mini = imagecreatetruecolor($mini_width, $mini_height);
2016
2017
        imagecopyresampled(
2018
            $new_image_mini,
2019
            $src,
2020
            0 - ($new_width_mini - $mini_width) / 2,
2021
            0 - ($new_height_mini - $mini_height) / 2,
2022
            0,
2023
            0,
2024
            $new_width_mini,
2025
            $new_height_mini,
2026
            $src_width,
2027
            $src_height
2028
        );
2029
        imagejpeg($new_image_mini, $rep);
2030
2031
        imagedestroy($new_image_mini);
2032
    }
2033
2034
    public function getGameEntity()
2035
    {
2036
        return new \PlaygroundGame\Entity\Game();
2037
    }
2038
2039
    /**
2040
     * @param string $resource
2041
     * @param string $privilege
2042
     */
2043
    public function isAllowed($resource, $privilege = null)
2044
    {
2045
        $auth = $this->serviceLocator->get('BjyAuthorize\Service\Authorize');
2046
2047
        return $auth->isAllowed($resource, $privilege);
2048
    }
2049
2050
    public function getIp()
2051
    {
2052
        $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...
2053
        if (isset($_SERVER['HTTP_CLIENT_IP'])) {
2054
            $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
2055
        } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
2056
            $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
2057
        } elseif (isset($_SERVER['HTTP_X_FORWARDED'])) {
2058
            $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
2059
        } elseif (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
2060
            $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
2061
        } elseif (isset($_SERVER['HTTP_FORWARDED'])) {
2062
            $ipaddress = $_SERVER['HTTP_FORWARDED'];
2063
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
2064
            $ipaddress = $_SERVER['REMOTE_ADDR'];
2065
        } else {
2066
            $ipaddress = 'UNKNOWN';
2067
        }
2068
2069
        return $ipaddress;
2070
    }
2071
2072
    public function getGeoloc($ip)
2073
    {
2074
        $geoloc = '';
2075
        try {
2076
            $res = unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip='.$ip));
2077
            if ($res['geoplugin_latitude'] != '') {
2078
                $geoloc = $res['geoplugin_latitude'] . ',' . $res['geoplugin_longitude'];
2079
            }
2080
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
2081
        }
2082
2083
        return $geoloc;
2084
    }
2085
2086
    public function getAnonymousId()
2087
    {
2088
        $anonymousId = '';
2089
        if ($_COOKIE && array_key_exists('pg_anonymous', $_COOKIE)) {
2090
            $anonymousId = $_COOKIE['pg_anonymous'];
2091
        }
2092
2093
        return $anonymousId;
2094
    }
2095
2096
    /**
2097
     *
2098
     *
2099
     * This service is ready for all types of games
2100
     *
2101
     * @param array $data
2102
     * @return \PlaygroundGame\Entity\Game
2103
     */
2104 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...
2105
    {
2106
        $title = '';
2107
        $description = '';
2108
2109
        if ($data['form_jsonified']) {
2110
            $jsonPV = json_decode($data['form_jsonified']);
2111
            foreach ($jsonPV as $element) {
2112
                if ($element->form_properties) {
2113
                    $attributes = $element->form_properties[0];
2114
                    $title = $attributes->title;
2115
                    $description = $attributes->description;
2116
2117
                    break;
2118
                }
2119
            }
2120
        }
2121
        if (! $form) {
2122
            $form = new \PlaygroundGame\Entity\PlayerForm();
2123
        }
2124
        $form->setGame($game);
2125
        $form->setTitle($title);
2126
        $form->setDescription($description);
2127
        $form->setForm($data['form_jsonified']);
2128
        $form->setFormTemplate($data['form_template']);
2129
2130
        $form = $this->getPlayerFormMapper()->insert($form);
2131
2132
        return $form;
2133
    }
2134
2135
    /**
2136
     *  getCSV creates lines of CSV and returns it.
2137
     */
2138
    public function getCSV($array)
2139
    {
2140
        ob_start(); // buffer the output ...
2141
        $out = fopen('php://output', 'w');
2142
        fputcsv($out, array_keys($array[0]), ";");
2143
        foreach ($array as $line) {
2144
            fputcsv($out, $line, ";");
2145
        }
2146
        fclose($out);
2147
        return ob_get_clean(); // ... then return it as a string!
2148
    }
2149
    
2150
    public function getAttributes($attributes)
2151
    {
2152
        $a = array();
2153
2154
        $a['name']          = isset($attributes->name)? $attributes->name : '';
2155
        $a['placeholder']   = isset($attributes->data->placeholder)? $attributes->data->placeholder : '';
2156
        $a['label']         = isset($attributes->data->label)? $attributes->data->label : '';
2157
        $a['required']      = (isset($attributes->data->required) && $attributes->data->required == 'true')?
2158
            true:
2159
            false;
2160
        $a['class']         = isset($attributes->data->class)? $attributes->data->class : '';
2161
        $a['id']            = isset($attributes->data->id)? $attributes->data->id : '';
2162
        $a['lengthMin']     = isset($attributes->data->length)? $attributes->data->length->min : '';
2163
        $a['lengthMax']     = isset($attributes->data->length)? $attributes->data->length->max : '';
2164
        $a['validator']     = isset($attributes->data->validator)? $attributes->data->validator : '';
2165
        $a['innerData']     = isset($attributes->data->innerData)? $attributes->data->innerData : array();
2166
        $a['dropdownValues']= isset($attributes->data->dropdownValues)?
2167
            $attributes->data->dropdownValues :
2168
            array();
2169
        $a['filesizeMin']   = isset($attributes->data->filesize)? $attributes->data->filesize->min : 0;
2170
        $a['filesizeMax']   = isset($attributes->data->filesize)? $attributes->data->filesize->max : 10*1024*1024;
2171
        $a['fileextension']   = isset($attributes->data->fileextension)?
2172
            str_replace(', ', ',', $attributes->data->fileextension) :
2173
            'png,jpg,jpeg,gif';
2174
2175
        // hiddenRequired('fileexcludeextension', '').appendTo(li);
2176
        // hiddenRequired('filemimetype', '').appendTo(li);
2177
        // hiddenRequired('fileexcludemimetype', '').appendTo(li);
2178
        // hiddenRequired('fileexists', '').appendTo(li);
2179
        // hiddenRequired('fileimagesize_minheight', '').appendTo(li);
2180
        // hiddenRequired('fileimagesize_maxheight', '').appendTo(li);
2181
        // hiddenRequired('fileimagesize_minwidth', '').appendTo(li);
2182
        // hiddenRequired('fileimagesize_maxwidth', '').appendTo(li);
2183
        // hiddenRequired('fileiscompressed', '').appendTo(li);
2184
        // hiddenRequired('fileisimage', '').appendTo(li);
2185
        // hiddenRequired('filewordcount_min', '').appendTo(li);
2186
        // hiddenRequired('filewordcount_max', '').appendTo(li);
2187
2188
        return $a;
2189
    }
2190
2191
    /**
2192
     * @param \Zend\InputFilter\InputFilter $inputFilter
2193
     */
2194
    public function decorate($element, $attr, $inputFilter)
2195
    {
2196
        $factory = new InputFactory();
2197
        $element->setLabel($attr['label']);
2198
        $element->setAttributes(
2199
            array(
2200
                'placeholder'   => $attr['placeholder'],
2201
                'required'      => $attr['required'],
2202
                'class'         => $attr['class'],
2203
                'id'            => $attr['id']
2204
            )
2205
        );
2206
2207
        $options = array();
2208
        $options['encoding'] = 'UTF-8';
2209
        if ($attr['lengthMin'] && $attr['lengthMin'] > 0) {
2210
            $options['min'] = $attr['lengthMin'];
2211
        }
2212
        if ($attr['lengthMax'] && $attr['lengthMax'] > $attr['lengthMin']) {
2213
            $options['max'] = $attr['lengthMax'];
2214
            $element->setAttribute('maxlength', $attr['lengthMax']);
2215
            $options['messages'] = array(
2216
                \Zend\Validator\StringLength::TOO_LONG => sprintf(
2217
                    $this->serviceLocator->get('MvcTranslator')->translate(
2218
                        'This field contains more than %s characters',
2219
                        'playgroundgame'
2220
                    ),
2221
                    $attr['lengthMax']
2222
                )
2223
            );
2224
        }
2225
2226
        $validators = array(
2227
            array(
2228
                'name'    => 'StringLength',
2229
                'options' => $options,
2230
            ),
2231
        );
2232
        if ($attr['validator']) {
2233
            $regex = "/.*\(([^)]*)\)/";
2234
            preg_match($regex, $attr['validator'], $matches);
2235
            $valArray = array(
2236
                'name' => str_replace(
2237
                    '('.$matches[1].')',
2238
                    '',
2239
                    $attr['validator']
2240
                ),
2241
                'options' => array($matches[1])
2242
            );
2243
            $validators[] = $valArray;
2244
        }
2245
2246
        $inputFilter->add($factory->createInput(array(
2247
            'name'     => $attr['name'],
2248
            'required' => $attr['required'],
2249
            'filters'  => array(
2250
                array('name' => 'StripTags'),
2251
                array('name' => 'StringTrim'),
2252
            ),
2253
            'validators' => $validators,
2254
        )));
2255
2256
        return $element;
2257
    }
2258
2259
    /**
2260
     * Create a ZF2 Form from json data
2261
     * @return Form
2262
     */
2263
    public function createFormFromJson($jsonForm, $id = 'jsonForm')
2264
    {
2265
        $formPV = json_decode($jsonForm);
2266
        
2267
        $form = new Form();
2268
        $form->setAttribute('id', $id);
2269
        $form->setAttribute('enctype', 'multipart/form-data');
2270
        
2271
        $inputFilter = new \Zend\InputFilter\InputFilter();
2272
        $factory = new InputFactory();
2273
        
2274
        foreach ($formPV as $element) {
2275 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...
2276
                $attr  = $this->getAttributes($element->line_text[0]);
2277
                $element = new Element\Text($attr['name']);
2278
                $element = $this->decorate($element, $attr, $inputFilter);
2279
                $form->add($element);
2280
            }
2281 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...
2282
                $attr = $this->getAttributes($element->line_password[0]);
2283
                $element = new Element\Password($attr['name']);
2284
                $element = $this->decorate($element, $attr, $inputFilter);
2285
                $form->add($element);
2286
            }
2287 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...
2288
                $attr = $this->getAttributes($element->line_hidden[0]);
2289
                $element = new Element\Hidden($attr['name']);
2290
                $element = $this->decorate($element, $attr, $inputFilter);
2291
                $form->add($element);
2292
            }
2293 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...
2294
                $attr = $this->getAttributes($element->line_email[0]);
2295
                $element = new Element\Email($attr['name']);
2296
                $element = $this->decorate($element, $attr, $inputFilter);
2297
                $form->add($element);
2298
            }
2299 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...
2300
                $attr = $this->getAttributes($element->line_radio[0]);
2301
                $element = new Element\Radio($attr['name']);
2302
2303
                $element->setLabel($attr['label']);
2304
                $element->setAttributes(
2305
                    array(
2306
                        'name'      => $attr['name'],
2307
                        'required'  => $attr['required'],
2308
                        'allowEmpty'=> !$attr['required'],
2309
                        'class'     => $attr['class'],
2310
                        'id'        => $attr['id']
2311
                    )
2312
                );
2313
                $values = array();
2314
                foreach ($attr['innerData'] as $value) {
2315
                    $values[] = $value->label;
2316
                }
2317
                $element->setValueOptions($values);
2318
        
2319
                $options = array();
2320
                $options['encoding'] = 'UTF-8';
2321
                $options['disable_inarray_validator'] = true;
2322
        
2323
                $element->setOptions($options);
2324
        
2325
                $form->add($element);
2326
        
2327
                $inputFilter->add($factory->createInput(array(
2328
                    'name'     => $attr['name'],
2329
                    'required' => $attr['required'],
2330
                    'allowEmpty' => !$attr['required'],
2331
                )));
2332
            }
2333 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...
2334
                $attr = $this->getAttributes($element->line_checkbox[0]);
2335
                $element = new Element\MultiCheckbox($attr['name']);
2336
        
2337
                $element->setLabel($attr['label']);
2338
                $element->setAttributes(
2339
                    array(
2340
                        'name'      => $attr['name'],
2341
                        'required'  => $attr['required'],
2342
                        'allowEmpty'=> !$attr['required'],
2343
                        'class'     => $attr['class'],
2344
                        'id'        => $attr['id']
2345
                    )
2346
                );
2347
2348
                $values = array();
2349
                foreach ($attr['innerData'] as $value) {
2350
                    $values[] = $value->label;
2351
                }
2352
                $element->setValueOptions($values);
2353
                $form->add($element);
2354
        
2355
                $options = array();
2356
                $options['encoding'] = 'UTF-8';
2357
                $options['disable_inarray_validator'] = true;
2358
        
2359
                $element->setOptions($options);
2360
        
2361
                $inputFilter->add($factory->createInput(array(
2362
                    'name'      => $attr['name'],
2363
                    'required'  => $attr['required'],
2364
                    'allowEmpty'=> !$attr['required'],
2365
                )));
2366
            }
2367 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...
2368
                $attr = $this->getAttributes($element->line_dropdown[0]);
2369
                $element = new Element\Select($attr['name']);
2370
2371
                $element->setLabel($attr['label']);
2372
                $element->setAttributes(
2373
                    array(
2374
                        'name'      => $attr['name'],
2375
                        'required'  => $attr['required'],
2376
                        'allowEmpty'=> !$attr['required'],
2377
                        'class'     => $attr['class'],
2378
                        'id'        => $attr['id']
2379
                    )
2380
                );
2381
                $values = array();
2382
                foreach ($attr['dropdownValues'] as $value) {
2383
                    $values[] = $value->dropdown_label;
2384
                }
2385
                $element->setValueOptions($values);
2386
                $form->add($element);
2387
        
2388
                $options = array();
2389
                $options['encoding'] = 'UTF-8';
2390
                $options['disable_inarray_validator'] = true;
2391
        
2392
                $element->setOptions($options);
2393
        
2394
                $inputFilter->add($factory->createInput(array(
2395
                    'name'     => $attr['name'],
2396
                    'required' => $attr['required'],
2397
                    'allowEmpty' => !$attr['required'],
2398
                )));
2399
            }
2400 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...
2401
                $attr = $this->getAttributes($element->line_paragraph[0]);
2402
                $element = new Element\Textarea($attr['name']);
2403
                $element = $this->decorate($element, $attr, $inputFilter);
2404
                $form->add($element);
2405
            }
2406
            if (isset($element->line_upload)) {
2407
                $attr = $this->getAttributes($element->line_upload[0]);
2408
                $element = new Element\File($attr['name']);
2409
2410
                $element->setLabel($attr['label']);
2411
                $element->setAttributes(
2412
                    array(
2413
                        'name'      => $attr['name'],
2414
                        'required'  => $attr['required'],
2415
                        'class'     => $attr['class'],
2416
                        'id'        => $attr['id']
2417
                    )
2418
                );
2419
                $form->add($element);
2420
2421
                $inputFilter->add($factory->createInput(array(
2422
                    'name'     => $attr['name'],
2423
                    'required' => $attr['required'],
2424
                    'validators' => array(
2425
                        array(
2426
                            'name' => '\Zend\Validator\File\Size',
2427
                            'options' => array('min' => $attr['filesizeMin'], 'max' => $attr['filesizeMax'])
2428
                        ),
2429
                        array(
2430
                            'name' => '\Zend\Validator\File\Extension',
2431
                            'options'  => array(
2432
                                $attr['fileextension'],
2433
                                'messages' => array(
2434
                                    \Zend\Validator\File\Extension::FALSE_EXTENSION =>'Veuillez télécharger un fichier avec la bonne extension'
2435
                                )
2436
                            )
2437
                        ),
2438
                    ),
2439
                )));
2440
            }
2441
        }
2442
        
2443
        $form->setInputFilter($inputFilter);
2444
        
2445
        return $form;
2446
    }
2447
2448
    /**
2449
     * Send mail for winner and/or loser
2450
     * @param \PlaygroundGame\Entity\Game $game
2451
     * @param \PlaygroundUser\Entity\User $user
2452
     * @param \PlaygroundGame\Entity\Entry $lastEntry
2453
     * @param \PlaygroundGame\Entity\Prize $prize
2454
     */
2455
    public function sendMail($game, $user, $lastEntry, $prize = null)
2456
    {
2457 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...
2458
            $game->getMailWinner() &&
2459
            $lastEntry->getWinner()
2460
        ) {
2461
            $this->sendResultMail($game, $user, $lastEntry, 'winner', $prize);
2462
        }
2463
2464 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...
2465
            $game->getMailLooser() &&
2466
            !$lastEntry->getWinner()
2467
        ) {
2468
            $this->sendResultMail($game, $user, $lastEntry, 'looser');
2469
        }
2470
2471
        if (($user || ($game->getAnonymousAllowed() && $game->getAnonymousIdentifier())) &&
2472
            $game->getMailEntry()
2473
        ) {
2474
            $this->sendResultMail($game, $user, $lastEntry);
2475
        }
2476
    }
2477
2478
    public function getPlayerFormMapper()
2479
    {
2480
        if (null === $this->playerformMapper) {
2481
            $this->playerformMapper = $this->serviceLocator->get('playgroundgame_playerform_mapper');
2482
        }
2483
2484
        return $this->playerformMapper;
2485
    }
2486
2487
    public function setPlayerFormMapper($playerformMapper)
2488
    {
2489
        $this->playerformMapper = $playerformMapper;
2490
2491
        return $this;
2492
    }
2493
2494
    public function getInvitationMapper()
2495
    {
2496
        if (null === $this->invitationMapper) {
2497
            $this->invitationMapper = $this->serviceLocator->get('playgroundgame_invitation_mapper');
2498
        }
2499
2500
        return $this->invitationMapper;
2501
    }
2502
2503
    public function setInvitationMapper($invitationMapper)
2504
    {
2505
        $this->invitationMapper = $invitationMapper;
2506
2507
        return $this;
2508
    }
2509
2510
    /**
2511
     * getUserMapper
2512
     *
2513
     * @return UserMapperInterface
2514
     */
2515
    public function getUserMapper()
2516
    {
2517
        if (null === $this->userMapper) {
2518
            $this->userMapper = $this->serviceLocator->get('zfcuser_user_mapper');
2519
        }
2520
2521
        return $this->userMapper;
2522
    }
2523
2524
    /**
2525
     * getUserMapper
2526
     *
2527
     * @return ServiceManager
2528
     */
2529
    public function getServiceManager()
2530
    {
2531
        return $this->serviceLocator;
2532
    }
2533
}
2534