Completed
Pull Request — master (#254)
by greg
03:06
created

Game::findLastInactiveEntry()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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

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

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

Loading history...
129
            if (isset($data['publicationDate']) && $data['publicationDate']) {
130
                $tmpDate = \DateTime::createFromFormat('Y-m-d', $data['publicationDate']);
131
                $data['publicationDate'] = $tmpDate->format('d/m/Y');
132
                $form->setData(array(
133
                    'publicationDate' => $data['publicationDate']
134
                ));
135
            }
136
            if (isset($data['startDate']) && $data['startDate']) {
137
                $tmpDate = \DateTime::createFromFormat('Y-m-d', $data['startDate']);
138
                $data['startDate'] = $tmpDate->format('d/m/Y');
139
                $form->setData(array(
140
                    'startDate' => $data['startDate']
141
                ));
142
            }
143
            if (isset($data['endDate']) && $data['endDate']) {
144
                $tmpDate = \DateTime::createFromFormat('Y-m-d', $data['endDate']);
145
                $data['endDate'] = $tmpDate->format('d/m/Y');
146
                $form->setData(array(
147
                    'endDate' => $data['endDate']
148
                ));
149
            }
150
            if (isset($data['closeDate']) && $data['closeDate']) {
151
                $tmpDate = \DateTime::createFromFormat('Y-m-d', $data['closeDate']);
152
                $data['closeDate'] = $tmpDate->format('d/m/Y');
153
                $form->setData(array(
154
                    'closeDate' => $data['closeDate']
155
                ));
156
            }
157
            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::create 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...
158
        }
159
160
        $game = $form->getData();
161
        $game = $this->getGameMapper()->insert($game);
162
163
        // If I receive false, it means that the FB Id was not available anymore
164
        $result = $this->getEventManager()->trigger(__FUNCTION__, $this, array(
165
            'game' => $game
166
        ));
167
        if (! $result) {
168
            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::create 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...
169
        }
170
171
            // I wait for the game to be saved to obtain its ID.
172 View Code Duplication
        if (! empty($data['uploadStylesheet']['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...
173
            ErrorHandler::start();
174
            move_uploaded_file($data['uploadStylesheet']['tmp_name'], $path . 'stylesheet_' . $game->getId() . '.css');
175
            $game->setStylesheet($media_url . 'stylesheet_' . $game->getId() . '.css');
176
            ErrorHandler::stop(true);
177
        }
178
179 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...
180
            ErrorHandler::start();
181
            $data['uploadMainImage']['name'] = $this->fileNewname(
182
                $path,
183
                $game->getId() . "-" . $data['uploadMainImage']['name']
184
            );
185
            move_uploaded_file($data['uploadMainImage']['tmp_name'], $path . $data['uploadMainImage']['name']);
186
            $game->setMainImage($media_url . $data['uploadMainImage']['name']);
187
            ErrorHandler::stop(true);
188
        }
189
190 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...
191
            ErrorHandler::start();
192
            $data['uploadSecondImage']['name'] = $this->fileNewname(
193
                $path,
194
                $game->getId() . "-" . $data['uploadSecondImage']['name']
195
            );
196
            move_uploaded_file($data['uploadSecondImage']['tmp_name'], $path . $data['uploadSecondImage']['name']);
197
            $game->setSecondImage($media_url . $data['uploadSecondImage']['name']);
198
            ErrorHandler::stop(true);
199
        }
200
201 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...
202
            ErrorHandler::start();
203
            $data['uploadFbShareImage']['name'] = $this->fileNewname(
204
                $path,
205
                $game->getId() . "-" . $data['uploadFbShareImage']['name']
206
            );
207
            move_uploaded_file($data['uploadFbShareImage']['tmp_name'], $path . $data['uploadFbShareImage']['name']);
208
            $game->setFbShareImage($media_url . $data['uploadFbShareImage']['name']);
209
            ErrorHandler::stop(true);
210
        }
211
212 View Code Duplication
        if (! empty($data['uploadFbPageTabImage']['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...
213
            ErrorHandler::start();
214
            $extension = $this->getExtension(strtolower($data['uploadFbPageTabImage']['name']));
215
            $src = $this->getSrc($extension, $data['uploadFbPageTabImage']['tmp_name']);
216
            $this->resize(
217
                $data['uploadFbPageTabImage']['tmp_name'],
218
                $extension,
219
                $path . $game->getId() . "-" . $data['uploadFbPageTabImage']['name'],
220
                $src,
221
                111,
222
                74
223
            );
224
225
            $game->setFbPageTabImage($media_url . $game->getId() . "-" . $data['uploadFbPageTabImage']['name']);
226
            ErrorHandler::stop(true);
227
        }
228
        $game = $this->getGameMapper()->update($game);
229
230
        $prize_mapper = $this->getServiceManager()->get('playgroundgame_prize_mapper');
231
        if (isset($data['prizes'])) {
232
            foreach ($data['prizes'] as $prize_data) {
233
                if (! empty($prize_data['picture']['tmp_name'])) {
234 View Code Duplication
                    if ($prize_data['id']) {
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...
235
                        $prize = $prize_mapper->findById($prize_data['id']);
236
                    } else {
237
                        $some_prizes = $prize_mapper->findBy(array(
238
                            'game' => $game,
239
                            'title' => $prize_data['title']
240
                        ));
241
                        if (count($some_prizes) == 1) {
242
                            $prize = $some_prizes[0];
243
                        } else {
244
                            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::create 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...
245
                        }
246
                    }
247
                    ErrorHandler::start();
248
                    $filename = "game-" . $game->getId() . "-prize-";
249
                    $filename .= $prize->getId() . "-" . $prize_data['picture']['name'];
250
                    move_uploaded_file($prize_data['picture']['tmp_name'], $path . $filename);
251
                    $prize->setPicture($media_url . $filename);
252
                    ErrorHandler::stop(true);
253
                    $prize = $prize_mapper->update($prize);
0 ignored issues
show
Unused Code introduced by
$prize 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...
254
                }
255
            }
256
        }
257
258
        return $game;
259
    }
260
261
    /**
262
     *
263
     *
264
     * This service is ready for all types of games
265
     *
266
     * @param array $data
267
     * @param string $formClass
268
     * @return \PlaygroundGame\Entity\Game
269
     */
270
    public function edit(array $data, $game, $formClass)
271
    {
272
        $entityManager = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
273
        $form = $this->getServiceManager()->get($formClass);
274
        $form->get('publicationDate')->setOptions(array(
275
            'format' => 'Y-m-d'
276
        ));
277
        $form->get('startDate')->setOptions(array(
278
            'format' => 'Y-m-d'
279
        ));
280
        $form->get('endDate')->setOptions(array(
281
            'format' => 'Y-m-d'
282
        ));
283
        $form->get('closeDate')->setOptions(array(
284
            'format' => 'Y-m-d'
285
        ));
286
287
        $form->bind($game);
288
289
        $path = $this->getOptions()->getMediaPath() . '/';
290
        $media_url = $this->getOptions()->getMediaUrl() . '/';
291
292
        $identifierInput = $form->getInputFilter()->get('identifier');
293
        $noObjectExistsValidator = new NoObjectExistsValidator(array(
294
            'object_repository' => $entityManager->getRepository('PlaygroundGame\Entity\Game'),
295
            'fields' => 'identifier',
296
            'messages' => array(
297
                'objectFound' => 'This url already exists !'
298
            )
299
        ));
300
301
        if ($game->getIdentifier() != $data['identifier']) {
302
            $identifierInput->getValidatorChain()->addValidator($noObjectExistsValidator);
303
        }
304
305
        // I must switch from original format to the Y-m-d format because
306
        // this is the only one accepted by new DateTime($value)
307 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...
308
            $tmpDate = \DateTime::createFromFormat('d/m/Y', $data['publicationDate']);
309
            $data['publicationDate'] = $tmpDate->format('Y-m-d');
310
        }
311 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...
312
            $tmpDate = \DateTime::createFromFormat('d/m/Y', $data['startDate']);
313
            $data['startDate'] = $tmpDate->format('Y-m-d');
314
        }
315 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...
316
            $tmpDate = \DateTime::createFromFormat('d/m/Y', $data['endDate']);
317
            $data['endDate'] = $tmpDate->format('Y-m-d');
318
        }
319 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...
320
            $tmpDate = \DateTime::createFromFormat('d/m/Y', $data['closeDate']);
321
            $data['closeDate'] = $tmpDate->format('Y-m-d');
322
        }
323
324
        // If publicationDate is null, I update it with the startDate if not nul neither
325
        if ((! isset($data['publicationDate']) || $data['publicationDate'] == '') &&
326
            (isset($data['startDate']) && $data['startDate'] != '')
327
        ) {
328
            $data['publicationDate'] = $data['startDate'];
329
        }
330
331 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...
332
            $data['identifier'] = $data['title'];
333
        }
334
335
        $form->setData($data);
336
337
        // If someone want to claim... It's time to do it ! used for exemple by PlaygroundFacebook Module
338
        $result = $this->getEventManager()->trigger(__FUNCTION__ . '.validate', $this, array(
339
            'game' => $game,
340
            'data' => $data
341
        ));
342
        if (is_array($result) && ! $result[0]) {
343
            $form->get('fbAppId')->setMessages(array(
344
                'Vous devez d\'abord désinstaller l\'appli Facebook'
345
            ));
346
347
            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::edit 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...
348
        }
349
350 View Code Duplication
        if (! $form->isValid()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
351
            if (isset($data['publicationDate']) && $data['publicationDate']) {
352
                $tmpDate = \DateTime::createFromFormat('Y-m-d', $data['publicationDate']);
353
                $data['publicationDate'] = $tmpDate->format('d/m/Y');
354
                $form->setData(array(
355
                    'publicationDate' => $data['publicationDate']
356
                ));
357
            }
358
            if (isset($data['startDate']) && $data['startDate']) {
359
                $tmpDate = \DateTime::createFromFormat('Y-m-d', $data['startDate']);
360
                $data['startDate'] = $tmpDate->format('d/m/Y');
361
                $form->setData(array(
362
                    'startDate' => $data['startDate']
363
                ));
364
            }
365
            if (isset($data['endDate']) && $data['endDate']) {
366
                $tmpDate = \DateTime::createFromFormat('Y-m-d', $data['endDate']);
367
                $data['endDate'] = $tmpDate->format('d/m/Y');
368
                $form->setData(array(
369
                    'endDate' => $data['endDate']
370
                ));
371
            }
372
            if (isset($data['closeDate']) && $data['closeDate']) {
373
                $tmpDate = \DateTime::createFromFormat('Y-m-d', $data['closeDate']);
374
                $data['closeDate'] = $tmpDate->format('d/m/Y');
375
                $form->setData(array(
376
                    'closeDate' => $data['closeDate']
377
                ));
378
            }
379
            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::edit 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...
380
        }
381
382 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...
383
            ErrorHandler::start();
384
            $data['uploadMainImage']['name'] = $this->fileNewname(
385
                $path,
386
                $game->getId() . "-" . $data['uploadMainImage']['name']
387
            );
388
            move_uploaded_file($data['uploadMainImage']['tmp_name'], $path . $data['uploadMainImage']['name']);
389
            $game->setMainImage($media_url . $data['uploadMainImage']['name']);
390
            ErrorHandler::stop(true);
391
        }
392
393 View Code Duplication
        if (isset($data['deleteMainImage']) &&
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
394
            $data['deleteMainImage'] &&
395
            empty($data['uploadMainImage']['tmp_name'])
396
        ) {
397
            ErrorHandler::start();
398
            $image = $game->getMainImage();
399
            $image = str_replace($media_url, '', $image);
400
            unlink($path . $image);
401
            $game->setMainImage(null);
402
            ErrorHandler::stop(true);
403
        }
404
405 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...
406
            ErrorHandler::start();
407
            $data['uploadSecondImage']['name'] = $this->fileNewname(
408
                $path,
409
                $game->getId() . "-" . $data['uploadSecondImage']['name']
410
            );
411
            move_uploaded_file($data['uploadSecondImage']['tmp_name'], $path . $data['uploadSecondImage']['name']);
412
            $game->setSecondImage($media_url . $data['uploadSecondImage']['name']);
413
            ErrorHandler::stop(true);
414
        }
415
416 View Code Duplication
        if (isset($data['deleteSecondImage']) &&
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
417
            $data['deleteSecondImage'] &&
418
            empty($data['uploadSecondImage']['tmp_name'])
419
        ) {
420
            ErrorHandler::start();
421
            $image = $game->getSecondImage();
422
            $image = str_replace($media_url, '', $image);
423
            unlink($path . $image);
424
            $game->setSecondImage(null);
425
            ErrorHandler::stop(true);
426
        }
427
428 View Code Duplication
        if (! empty($data['uploadStylesheet']['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...
429
            ErrorHandler::start();
430
            move_uploaded_file($data['uploadStylesheet']['tmp_name'], $path . 'stylesheet_' . $game->getId() . '.css');
431
            $game->setStylesheet($media_url . 'stylesheet_' . $game->getId() . '.css');
432
            ErrorHandler::stop(true);
433
        }
434
435 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...
436
            ErrorHandler::start();
437
            $data['uploadFbShareImage']['name'] = $this->fileNewname(
438
                $path,
439
                $game->getId() . "-" . $data['uploadFbShareImage']['name']
440
            );
441
            move_uploaded_file($data['uploadFbShareImage']['tmp_name'], $path . $data['uploadFbShareImage']['name']);
442
            $game->setFbShareImage($media_url . $data['uploadFbShareImage']['name']);
443
            ErrorHandler::stop(true);
444
        }
445
446 View Code Duplication
        if (isset($data['deleteFbShareImage']) &&
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
447
            $data['deleteFbShareImage'] &&
448
            empty($data['uploadFbShareImage']['tmp_name'])
449
        ) {
450
            ErrorHandler::start();
451
            $image = $game->getFbShareImage();
452
            $image = str_replace($media_url, '', $image);
453
            unlink($path . $image);
454
            $game->setFbShareImage(null);
455
            ErrorHandler::stop(true);
456
        }
457
458 View Code Duplication
        if (! empty($data['uploadFbPageTabImage']['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...
459
            ErrorHandler::start();
460
461
            $extension = $this->getExtension(strtolower($data['uploadFbPageTabImage']['name']));
462
            $src = $this->getSrc($extension, $data['uploadFbPageTabImage']['tmp_name']);
463
            $this->resize(
464
                $data['uploadFbPageTabImage']['tmp_name'],
465
                $extension,
466
                $path . $game->getId() . "-" . $data['uploadFbPageTabImage']['name'],
467
                $src,
468
                111,
469
                74
470
            );
471
472
            $game->setFbPageTabImage($media_url . $game->getId() . "-" . $data['uploadFbPageTabImage']['name']);
473
            ErrorHandler::stop(true);
474
        }
475
476 View Code Duplication
        if (isset($data['deleteFbPageTabImage']) &&
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
477
            $data['deleteFbPageTabImage'] &&
478
            empty($data['uploadFbPageTabImage']['tmp_name'])
479
        ) {
480
            ErrorHandler::start();
481
            $image = $game->getFbPageTabImage();
482
            $image = str_replace($media_url, '', $image);
483
            unlink($path . $image);
484
            $game->setFbPageTabImage(null);
485
            ErrorHandler::stop(true);
486
        }
487
488
        $game = $this->getGameMapper()->update($game);
489
490
        $prize_mapper = $this->getServiceManager()->get('playgroundgame_prize_mapper');
491
        if (isset($data['prizes'])) {
492
            foreach ($data['prizes'] as $prize_data) {
493
                if (! empty($prize_data['picture_file']['tmp_name']) && ! $prize_data['picture_file']['error']) {
494 View Code Duplication
                    if ($prize_data['id']) {
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...
495
                        $prize = $prize_mapper->findById($prize_data['id']);
496
                    } else {
497
                        $some_prizes = $prize_mapper->findBy(array(
498
                            'game' => $game,
499
                            'title' => $prize_data['title']
500
                        ));
501
                        if (count($some_prizes) == 1) {
502
                            $prize = $some_prizes[0];
503
                        } else {
504
                            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::edit 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...
505
                        }
506
                    }
507
                    // Remove if existing image
508
                    if ($prize->getPicture() && file_exists($prize->getPicture())) {
509
                        unlink($prize->getPicture());
510
                        $prize->getPicture(null);
511
                    }
512
                    // Upload and set new
513
                    ErrorHandler::start();
514
                    $filename = "game-" . $game->getId() . "-prize-";
515
                    $filename .= $prize->getId() . "-" . $prize_data['picture_file']['name'];
516
                    move_uploaded_file($prize_data['picture_file']['tmp_name'], $path . $filename);
517
                    $prize->setPicture($media_url . $filename);
518
                    ErrorHandler::stop(true);
519
                    $prize = $prize_mapper->update($prize);
0 ignored issues
show
Unused Code introduced by
$prize 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...
520
                }
521
            }
522
        }
523
        // If I receive false, it means that the FB Id was not available anymore
524
        $result = $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
0 ignored issues
show
Unused Code introduced by
$result 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...
525
            'game' => $game
526
        ));
527
528
        return $game;
529
    }
530
531
    /**
532
     * getActiveGames
533
     *
534
     * @return Array of PlaygroundGame\Entity\Game
535
     */
536
    public function getActiveGames($displayHome = true, $classType = '', $order = '')
537
    {
538
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
539
        $today = new \DateTime("now");
540
        $today = $today->format('Y-m-d') . ' 23:59:59';
541
        $orderBy = 'g.publicationDate';
542
        if ($order != '') {
543
            $orderBy = 'g.'.$order;
544
        }
545
546
        $qb = $em->createQueryBuilder();
547
        $and = $qb->expr()->andx();
548
        $and->add(
549
            $qb->expr()->orX(
550
                $qb->expr()->lte('g.publicationDate', ':date'),
551
                $qb->expr()->isNull('g.publicationDate')
552
            )
553
        );
554
        $and->add(
555
            $qb->expr()->orX(
556
                $qb->expr()->gte('g.closeDate', ':date'),
557
                $qb->expr()->isNull('g.closeDate')
558
            )
559
        );
560
        $qb->setParameter('date', $today);
561
        
562
        $and->add($qb->expr()->eq('g.active', '1'));
563
        $and->add($qb->expr()->eq('g.broadcastPlatform', '1'));
564
        
565
        if ($classType != '') {
566
            $and->add($qb->expr()->eq('g.classType', ':classType'));
567
            $qb->setParameter('classType', $classType);
568
        }
569
        
570
        if ($displayHome) {
571
            $and->add($qb->expr()->eq('g.displayHome', true));
572
        }
573
        
574
        $qb->select('g')
575
        ->from('PlaygroundGame\Entity\Game', 'g')
576
        ->where($and)
577
        ->orderBy($orderBy, 'DESC');
578
        
579
        $query = $qb->getQuery();
580
        $games = $query->getResult();
581
        
582
        // je les classe par date de publication (date comme clé dans le tableau afin de pouvoir merger les objets
583
        // de type article avec le même procédé en les classant naturellement par date asc ou desc
584
        $arrayGames = array();
585 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...
586
            if ($game->getPublicationDate()) {
587
                $key = $game->getPublicationDate()->format('Ymd');
588
            } elseif ($game->getStartDate()) {
589
                $key = $game->getStartDate()->format('Ymd');
590
            } else {
591
                $key = $game->getUpdatedAt()->format('Ymd');
592
            }
593
            $key .= $game->getUpdatedAt()->format('Ymd') . '-' . $game->getId();
594
            $arrayGames[$key] = $game;
595
        }
596
597
        return $arrayGames;
598
    }
599
600
    /**
601
     * getAvailableGames : Games OnLine and not already played by $user
602
     *
603
     * @return Array of PlaygroundGame\Entity\Game
604
     */
605
    public function getAvailableGames($user, $maxResults = 2)
606
    {
607
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
608
        $today = new \DateTime("now");
609
        $today = $today->format('Y-m-d') . ' 23:59:59';
610
611
        // Game active with a start_date before today (or without start_date)
612
        // and end_date after today (or without end-date)
613
        $query = $em->createQuery('SELECT g FROM PlaygroundGame\Entity\Game g
614
                WHERE NOT EXISTS (SELECT l FROM PlaygroundGame\Entity\Entry l WHERE l.game = g AND l.user = :user)
615
                AND (g.startDate <= :date OR g.startDate IS NULL)
616
                AND (g.endDate >= :date OR g.endDate IS NULL)
617
                AND g.active = 1 AND g.broadcastPlatform = 1
618
                ORDER BY g.startDate ASC');
619
        $query->setParameter('date', $today);
620
        $query->setParameter('user', $user);
621
        $query->setMaxResults($maxResults);
622
        $games = $query->getResult();
623
624
        return $games;
625
    }
626
627 View Code Duplication
    public function getEntriesQuery($game)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
628
    {
629
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
630
631
        $qb = $em->createQueryBuilder();
632
        $qb->select('
633
            e.id,
634
            u.username,
635
            u.title,
636
            u.firstname,
637
            u.lastname,
638
            u.email,
639
            u.optin,
640
            u.optinPartner,
641
            u.address,
642
            u.address2,
643
            u.postalCode,
644
            u.city,
645
            u.telephone,
646
            u.mobile,
647
            u.created_at,
648
            u.dob,
649
            e.winner,
650
            e.socialShares,
651
            e.playerData,
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->getQuery();
661
    }
662
663
    public function getEntriesHeader($game)
664
    {
665
        if ($game->getPlayerForm()) {
666
            $formPV = json_decode($game->getPlayerForm()->getForm(), true);
667
            $header = array('id'=> 1);
668 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...
669
                foreach ($element as $k => $v) {
670
                    if ($k !== 'form_properties') {
671
                        $header[$v[0]['name']] = 1;
672
                    }
673
                }
674
            }
675
        } else {
676
            $header = array(
677
                'id' => 1,
678
                'username' => 1,
679
                'title' => 1,
680
                'firstname' => 1,
681
                'lastname' => 1,
682
                'email' => 1,
683
                'optin' => 1,
684
                'optinPartner' => 1,
685
                'address' => 1,
686
                'address2' => 1,
687
                'postalCode' => 1,
688
                'city' => 1,
689
                'telephone' => 1,
690
                'mobile' => 1,
691
                'created_at' => 1,
692
                'dob' => 1,
693
                'winner' => 1
694
            );
695
        }
696
        $header['winner'] = 1;
697
        $header['socialShares'] = 1;
698
        $header['updated_at'] = 1;
699
700
        return $header;
701
    }
702
703
    /**
704
    * getGameEntries : I create an array of entries based on playerData + header
705
    *
706
    * @return Array of PlaygroundGame\Entity\Game
707
    */
708
    public function getGameEntries($header, $entries, $game)
709
    {
710
        $header = $this->getEntriesHeader($game);
711
712
        $results = array();
713
714
        foreach ($entries as $k => $entry) {
715
            $entryData = json_decode($entry['playerData'], true);
716 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...
717
                if (isset($entryData[$key])) {
718
                    $results[$k][$key] = (is_array($entryData[$key]))?implode(', ', $entryData[$key]):$entryData[$key];
719
                } elseif (array_key_exists($key, $entry)) {
720
                    $results[$k][$key] = ($entry[$key] instanceof \DateTime)?
721
                        $entry[$key]->format('Y-m-d'):
722
                        $entry[$key];
723
                } else {
724
                    $results[$k][$key] = '';
725
                }
726
            }
727
        }
728
729
        return $results;
730
    }
731
732
    /**
733
     * getActiveSliderGames
734
     *
735
     * @return Array of PlaygroundGame\Entity\Game
736
     */
737
    public function getActiveSliderGames()
738
    {
739
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
740
        $today = new \DateTime("now");
741
        $today = $today->format('Y-m-d') . ' 23:59:59';
742
743
        // Game active with a start_date before today (or without start_date)
744
        // and end_date after today (or without end-date)
745
        $query = $em->createQuery('SELECT g FROM PlaygroundGame\Entity\Game g
746
            WHERE (g.publicationDate <= :date OR g.publicationDate IS NULL)
747
            AND (g.closeDate >= :date OR g.closeDate IS NULL)
748
            AND g.active = true AND g.broadcastPlatform = 1 AND g.pushHome = true');
749
        $query->setParameter('date', $today);
750
        $games = $query->getResult();
751
752
        // je les classe par date de publication (date comme clé dans le tableau afin de pouvoir merger les objets
753
        // de type article avec le même procédé en les classant naturellement par date asc ou desc
754
        $arrayGames = array();
755 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...
756
            if ($game->getPublicationDate()) {
757
                $key = $game->getPublicationDate()->format('Ymd');
758
            } elseif ($game->getStartDate()) {
759
                $key = $game->getStartDate()->format('Ymd');
760
            } else {
761
                $key = $game->getUpdatedAt()->format('Ymd');
762
            }
763
            $key .= $game->getUpdatedAt()->format('Ymd') . '-' . $game->getId();
764
            $arrayGames[$key] = $game;
765
        }
766
767
        return $arrayGames;
768
    }
769
770
    /**
771
     * getPrizeCategoryGames
772
     *
773
     * @return Array of PlaygroundGame\Entity\Game
774
     */
775 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...
776
    {
777
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
778
779
        $query = $em->createQuery('SELECT g FROM PlaygroundGame\Entity\Game g
780
            WHERE (g.prizeCategory = :categoryid AND g.broadcastPlatform = 1)
781
            ORDER BY g.publicationDate DESC');
782
        $query->setParameter('categoryid', $categoryid);
783
        $games = $query->getResult();
784
785
        return $games;
786
    }
787
788
    public function checkGame($identifier, $checkIfStarted = true)
789
    {
790
        $gameMapper = $this->getGameMapper();
791
792
        if (! $identifier) {
793
            return false;
794
        }
795
796
        $game = $gameMapper->findByIdentifier($identifier);
797
798
        // the game has not been found
799
        if (! $game) {
800
            return false;
801
        }
802
803
        if ($this->getServiceManager()
804
            ->get('Application')
805
            ->getMvcEvent()
806
            ->getRouteMatch()
807
            ->getParam('channel') === 'preview' && $this->isAllowed('game', 'edit')) {
808
            $game->setActive(true);
809
            $game->setStartDate(null);
810
            $game->setEndDate(null);
811
            $game->setPublicationDate(null);
812
            $game->setBroadcastPlatform(true);
813
814
            // I don't want the game to be updated through any update during the preview mode.
815
            // I mark it as readonly for Doctrine
816
            $this->getServiceManager()
817
                ->get('doctrine.entitymanager.orm_default')
818
                ->getUnitOfWork()
819
                ->markReadOnly($game);
820
            return $game;
821
        }
822
823
        // The game is inactive
824
        if (! $game->getActive()) {
825
            return false;
826
        }
827
828
        // the game has not begun yet
829
        if (! $game->isOpen()) {
830
            return false;
831
        }
832
833
        // the game is finished and closed
834
        if (! $game->isStarted() && $checkIfStarted) {
835
            return false;
836
        }
837
838
        return $game;
839
    }
840
841
    /**
842
     * Return the last entry of the user on this game, if it exists.
843
     * An entry can be associated to :
844
     * - A user account (a real one, linked to PlaygroundUser
845
     * - An anonymous Identifier (based on one value of playerData (generally email))
846
     * - A cookie set on the player device (the less secure)
847
     * If the active param is set, it can check if the entry is active or not.
848
     * If the bonus param is set, it can check if the entry is a bonus or not.
849
     *
850
     * @param unknown $game
851
     * @param string $user
852
     * @param boolean $active
853
     * @param boolean $bonus
854
     * @return boolean
855
     */
856
    public function checkExistingEntry($game, $user = null, $active = null, $bonus = null)
857
    {
858
        $entry = false;
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...
859
        $search = array('game'  => $game);
860
861
        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...
862
            $search['user'] = $user;
863
        } elseif ($this->getAnonymousIdentifier()) {
864
            $search['anonymousIdentifier'] = $this->getAnonymousIdentifier();
865
            $search['user'] = null;
866
        } else {
867
            $search['anonymousId'] = $this->getAnonymousId();
868
            $search['user'] = null;
869
        }
870
        
871
        if (! is_null($active)) {
872
            $search['active'] = $active;
873
        }
874
        if (! is_null($bonus)) {
875
            $search['bonus'] = $bonus;
876
        }
877
878
        $entry = $this->getEntryMapper()->findOneBy($search, array('updated_at' => 'desc'));
879
880
        return $entry;
881
    }
882
883
    /*
884
    * This function updates the entry with the player data after checking 
885
    * that the data are compliant with the formUser Game attribute
886
    *
887
    * The $data has to be a json object
888
    */
889
    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...
890
    {
891
        $form = $this->createFormFromJson($game->getPlayerForm()->getForm(), 'playerForm');
892
        $form->setData($data);
893
894
        if (!$mandatory) {
895
            $filter = $form->getInputFilter();
896
            foreach ($form->getElements() as $element) {
897
                try {
898
                    $elementInput = $filter->get($element->getName());
899
                    $elementInput->setRequired(false);
0 ignored issues
show
Bug introduced by
The method setRequired does only exist in Zend\InputFilter\InputInterface, but not in Zend\InputFilter\InputFilterInterface.

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

Let’s take a look at an example:

class A
{
    public function foo() { }
}

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

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

Available Fixes

  1. Add an additional type-check:

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

    function someFunction(B $x) { /** ... */ }
    
Loading history...
900
                    $form->get($element->getName())->setAttribute('required', false);
901
                } 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...
902
                }
903
            }
904
        }
905
906
        if ($form->isValid()) {
907
            $dataJson = json_encode($form->getData());
908
909
            if ($game->getAnonymousAllowed() &&
910
                $game->getAnonymousIdentifier() &&
911
                isset($data[$game->getAnonymousIdentifier()])
912
            ) {
913
                $session = new \Zend\Session\Container('anonymous_identifier');
914
                if (empty($session->offsetGet('anonymous_identifier'))) {
915
                    $anonymousIdentifier = $data[$game->getAnonymousIdentifier()];
916
                
917
                    $entry->setAnonymousIdentifier($anonymousIdentifier);
918
                
919
                    // I must transmit this info during the whole game workflow
920
                    $session->offsetSet('anonymous_identifier', $anonymousIdentifier);
921
                }
922
            }
923
924
            $entry->setPlayerData($dataJson);
925
            $this->getEntryMapper()->update($entry);
926
        } else {
927
            return false;
928
        }
929
930
        return true;
931
    }
932
933
934
    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...
935
    {
936
        // If on Facebook, check if you have to be a FB fan to play the game
937
        $session = new Container('facebook');
938
939
        if ($session->offsetExists('signed_request')) {
940
            // I'm on Facebook
941
            $sr = $session->offsetGet('signed_request');
942
            if ($sr['page']['liked'] == 1) {
943
                return true;
944
            }
945
        } else {
946
            // I'm not on Facebook
947
            return true;
948
        }
949
950
        return false;
951
    }
952
    
953
    public function getAnonymousIdentifier()
954
    {
955
        if (is_null($this->anonymousIdentifier)) {
956
            // If on Facebook, check if you have to be a FB fan to play the game
957
            $session = new Container('anonymous_identifier');
958
            
959
            if ($session->offsetExists('anonymous_identifier')) {
960
                $this->anonymousIdentifier = $session->offsetGet('anonymous_identifier');
961
            } else {
962
                $this->anonymousIdentifier = false;
963
            }
964
        }
965
    
966
        return $this->anonymousIdentifier;
967
    }
968
969
    /**
970
     * errors :
971
     * -1 : user not connected
972
     * -2 : limit entry games for this user reached
973
     *
974
     * @param \PlaygroundGame\Entity\Game $game
975
     * @param \PlaygroundUser\Entity\UserInterface $user
976
     * @return number unknown
977
     */
978
    public function play($game, $user)
979
    {
980
981
        // certaines participations peuvent rester ouvertes.
982
        // On autorise alors le joueur à reprendre là ou il en était
983
        // par exemple les postvote...
984
        $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...
985
986
        if (! $entry) {
987
            if ($this->hasReachedPlayLimit($game, $user)) {
988
                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...
989
            }
990
991
            $entry = new Entry();
992
            $entry->setGame($game);
993
            $entry->setUser($user);
994
            $entry->setPoints(0);
995
            $entry->setIp($this->getIp());
996
            $entry->setAnonymousId($this->getAnonymousId());
997
            if ($this->getAnonymousIdentifier()) {
998
                $entry->setAnonymousIdentifier($this->getAnonymousIdentifier());
999
            }
1000
1001
            $entry = $this->getEntryMapper()->insert($entry);
1002
            $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1003
                'user' => $user,
1004
                'game' => $game,
1005
                'entry' => $entry
1006
            ));
1007
        }
1008
1009
        return $entry;
1010
    }
1011
1012
    /**
1013
     * @param \PlaygroundGame\Entity\Game $game
1014
     * @param \PlaygroundUser\Entity\UserInterface $user
1015
     */
1016
    public function hasReachedPlayLimit($game, $user)
1017
    {
1018
        // Is there a limitation on the game ?
1019
        $limitAmount = $game->getPlayLimit();
1020
        if ($limitAmount) {
1021
            $limitScale = $game->getPlayLimitScale();
1022
            $userEntries = $this->findLastEntries($game, $user, $limitScale);
1023
1024
            // player has reached the game limit
1025
            if ($userEntries >= $limitAmount) {
1026
                return true;
1027
            }
1028
        }
1029
        return false;
1030
    }
1031
    
1032
    /**
1033
     * @param \PlaygroundGame\Entity\Game $game
1034
     * @param \PlaygroundUser\Entity\UserInterface $user
1035
     */
1036
    public function findLastEntries($game, $user, $limitScale)
1037
    {
1038
        $limitDate = $this->getLimitDate($limitScale);
1039
1040
        if ($user) {
1041
            return $this->getEntryMapper()->findLastEntriesByUser($game, $user, $limitDate);
1042
        } elseif ($this->getAnonymousIdentifier()) {
1043
            return $this->getEntryMapper()->findLastEntriesByAnonymousIdentifier(
1044
                $game,
1045
                $this->getAnonymousIdentifier(),
1046
                $limitDate
1047
            );
1048
        } else {
1049
            return $this->getEntryMapper()->findLastEntriesByIp($game, $this->getIp(), $limitDate);
1050
        }
1051
    }
1052
1053
    /**
1054
    *
1055
    *
1056
    */
1057
    public function getLimitDate($limitScale)
1058
    {
1059
        $now = new \DateTime("now");
1060
        switch ($limitScale) {
1061
            case 'always':
1062
                $interval = 'P100Y';
1063
                $now->sub(new \DateInterval($interval));
1064
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
1065
                break;
1066
            case 'day':
1067
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
1068
                break;
1069
            case 'week':
1070
                $interval = 'P7D';
1071
                $now->sub(new \DateInterval($interval));
1072
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
1073
                break;
1074
            case 'month':
1075
                $interval = 'P1M';
1076
                $now->sub(new \DateInterval($interval));
1077
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
1078
                break;
1079
            case 'year':
1080
                $interval = 'P1Y';
1081
                $now->sub(new \DateInterval($interval));
1082
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
1083
                break;
1084
            default:
1085
                $interval = 'P100Y';
1086
                $now->sub(new \DateInterval($interval));
1087
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
1088
        }
1089
1090
        return $dateLimit;
1091
    }
1092
1093
    public function findLastActiveEntry($game, $user)
1094
    {
1095
        return $this->checkExistingEntry($game, $user, true);
1096
    }
1097
1098
    public function findLastInactiveEntry($game, $user)
1099
    {
1100
        return $this->checkExistingEntry($game, $user, false, false);
1101
    }
1102
1103
    public function findLastEntry($game, $user)
1104
    {
1105
        return $this->checkExistingEntry($game, $user, null, false);
1106
    }
1107
1108
    public function sendShareMail(
1109
        $data,
1110
        $game,
1111
        $user,
1112
        $entry,
1113
        $template = 'share_game',
1114
        $topic = null,
1115
        $userTimer = array()
1116
    ) {
1117
    
1118
        $mailService = $this->getServiceManager()->get('playgroundgame_message');
1119
        $mailSent = false;
1120
        $from = $this->getOptions()->getEmailFromAddress();
1121
        $subject = $this->getOptions()->getShareSubjectLine();
1122
        $renderer = $this->getServiceManager()->get('Zend\View\Renderer\RendererInterface');
1123
        if ($user) {
1124
            $email = $user->getEmail();
1125
        } elseif ($entry->getAnonymousIdentifier()) {
1126
            $email = $entry->getAnonymousIdentifier();
1127
        } else {
1128
            $email = $from;
1129
        }
1130
        $skinUrl = $renderer->url(
1131
            'frontend',
1132
            array('channel' => $this->getServiceManager()
1133
                ->get('Application')
1134
                ->getMvcEvent()
1135
                ->getRouteMatch()
1136
                ->getParam('channel')
1137
            ),
1138
            array(
1139
                'force_canonical' => true
1140
            )
1141
        );
1142
        $secretKey = strtoupper(substr(sha1(uniqid('pg_', true) . '####' . time()), 0, 15));
1143
1144
        if (! $topic) {
1145
            $topic = $game->getTitle();
1146
        }
1147
1148
        $shares = json_decode($entry->getSocialShares(), true);
1149
        
1150
        if ($data['email1']) {
1151
            $mailSent = true;
1152
            $message = $mailService->createHtmlMessage(
1153
                $from,
1154
                $data['email1'],
1155
                $subject,
1156
                'playground-game/email/' . $template,
1157
                array(
1158
                    'game' => $game,
1159
                    'email' => $email,
1160
                    'secretKey' => $secretKey,
1161
                    'skinUrl' => $skinUrl,
1162
                    'userTimer' => $userTimer
1163
                )
1164
            );
1165
            $mailService->send($message);
1166
            
1167
            if (!isset($shares['mail'])) {
1168
                $shares['mail'] = 1;
1169
            } else {
1170
                $shares['mail'] += 1;
1171
            }
1172
        }
1173
        if ($data['email2'] && $data['email2'] != $data['email1']) {
1174
            $mailSent = true;
1175
            $message = $mailService->createHtmlMessage(
1176
                $from,
1177
                $data['email2'],
1178
                $subject,
1179
                'playground-game/email/' . $template,
1180
                array(
1181
                    'game' => $game,
1182
                    'email' => $email,
1183
                    'secretKey' => $secretKey,
1184
                    'skinUrl' => $skinUrl,
1185
                    'userTimer' => $userTimer
1186
                )
1187
            );
1188
            $mailService->send($message);
1189
            
1190
            if (!isset($shares['mail'])) {
1191
                $shares['mail'] = 1;
1192
            } else {
1193
                $shares['mail'] += 1;
1194
            }
1195
        }
1196
        if ($data['email3'] && $data['email3'] != $data['email2'] && $data['email3'] != $data['email1']) {
1197
            $mailSent = true;
1198
            $message = $mailService->createHtmlMessage(
1199
                $from,
1200
                $data['email3'],
1201
                $subject,
1202
                'playground-game/email/' . $template,
1203
                array(
1204
                    'game' => $game,
1205
                    'email' => $email,
1206
                    'secretKey' => $secretKey,
1207
                    'skinUrl' => $skinUrl,
1208
                    'userTimer' => $userTimer
1209
                )
1210
            );
1211
            $mailService->send($message);
1212
            
1213
            if (!isset($shares['mail'])) {
1214
                $shares['mail'] = 1;
1215
            } else {
1216
                $shares['mail'] += 1;
1217
            }
1218
        }
1219
        if ($data['email4'] &&
1220
            $data['email4'] != $data['email3'] &&
1221
            $data['email4'] != $data['email2'] &&
1222
            $data['email4'] != $data['email1']
1223
        ) {
1224
            $mailSent = true;
1225
            $message = $mailService->createHtmlMessage(
1226
                $from,
1227
                $data['email4'],
1228
                $subject,
1229
                'playground-game/email/' . $template,
1230
                array(
1231
                    'game' => $game,
1232
                    'email' => $email,
1233
                    'secretKey' => $secretKey,
1234
                    'skinUrl' => $skinUrl,
1235
                    'userTimer' => $userTimer
1236
                )
1237
            );
1238
            $mailService->send($message);
1239
        
1240
            if (!isset($shares['mail'])) {
1241
                $shares['mail'] = 1;
1242
            } else {
1243
                $shares['mail'] += 1;
1244
            }
1245
        }
1246
        if ($data['email5'] &&
1247
            $data['email5'] != $data['email4'] &&
1248
            $data['email5'] != $data['email3'] &&
1249
            $data['email5'] != $data['email2'] &&
1250
            $data['email5'] != $data['email1']
1251
        ) {
1252
            $mailSent = true;
1253
            $message = $mailService->createHtmlMessage(
1254
                $from,
1255
                $data['email5'],
1256
                $subject,
1257
                'playground-game/email/' . $template,
1258
                array(
1259
                    'game' => $game,
1260
                    'email' => $email,
1261
                    'secretKey' => $secretKey,
1262
                    'skinUrl' => $skinUrl,
1263
                    'userTimer' => $userTimer
1264
                )
1265
            );
1266
            $mailService->send($message);
1267
        
1268
            if (!isset($shares['mail'])) {
1269
                $shares['mail'] = 1;
1270
            } else {
1271
                $shares['mail'] += 1;
1272
            }
1273
        }
1274
        if ($mailSent) {
1275
            $sharesJson = json_encode($shares);
1276
            $entry->setSocialShares($sharesJson);
1277
            $entry = $this->getEntryMapper()->update($entry);
1278
            
1279
            $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1280
                'user' => $user,
1281
                'topic' => $topic,
1282
                'secretKey' => $secretKey,
1283
                'game' => $game,
1284
                'entry' => $entry
1285
            ));
1286
1287
            return true;
1288
        }
1289
1290
        return false;
1291
    }
1292
1293
    /**
1294
     * @param \PlaygroundGame\Entity\Game $game
1295
     * @param \PlaygroundUser\Entity\User $user
1296
     * @param Entry $entry
1297
     * @param \PlaygroundGame\Entity\Prize $prize
1298
     */
1299
    public function sendResultMail($game, $user, $entry, $template = 'entry', $prize = null)
1300
    {
1301
        $mailService = $this->getServiceManager()->get('playgroundgame_message');
1302
        $from = $this->getOptions()->getEmailFromAddress();
1303
        if ($user) {
1304
            $to = $user->getEmail();
1305
        } elseif ($entry->getAnonymousIdentifier()) {
1306
            $to = $entry->getAnonymousIdentifier();
1307
        } else {
1308
            return false;
1309
        }
1310
        $subject = $game->getTitle();
1311
        $renderer = $this->getServiceManager()->get('Zend\View\Renderer\RendererInterface');
1312
        $skinUrl = $renderer->url(
1313
            'frontend',
1314
            array('channel' => $this->getServiceManager()
1315
                ->get('Application')
1316
                ->getMvcEvent()
1317
                ->getRouteMatch()
1318
                ->getParam('channel')
1319
            ),
1320
            array(
1321
                'force_canonical' => true
1322
            )
1323
        );
1324
        $message = $mailService->createHtmlMessage($from, $to, $subject, 'playground-game/email/' . $template, array(
1325
            'game' => $game,
1326
            'entry' => $entry,
1327
            'skinUrl' => $skinUrl,
1328
            'prize' => $prize
1329
        ));
1330
        $mailService->send($message);
1331
    }
1332
1333
    public function sendGameMail($game, $user, $post, $template = 'postvote')
1334
    {
1335
        $mailService = $this->getServiceManager()->get('playgroundgame_message');
1336
        $from = $this->getOptions()->getEmailFromAddress();
1337
        $to = $user->getEmail();
1338
        $subject = $this->getOptions()->getParticipationSubjectLine();
1339
        $renderer = $this->getServiceManager()->get('Zend\View\Renderer\RendererInterface');
1340
        $skinUrl = $renderer->url(
1341
            'frontend',
1342
            array('channel' => $this->getServiceManager()
1343
                ->get('Application')
1344
                ->getMvcEvent()
1345
                ->getRouteMatch()
1346
                ->getParam('channel')
1347
            ),
1348
            array(
1349
                'force_canonical' => true
1350
            )
1351
        );
1352
1353
        $message = $mailService->createHtmlMessage($from, $to, $subject, 'playground-game/email/' . $template, array(
1354
            'game' => $game,
1355
            'post' => $post,
1356
            'skinUrl' => $skinUrl
1357
        ));
1358
        $mailService->send($message);
1359
    }
1360
1361 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...
1362
    {
1363
        $topic = $game->getTitle();
1364
        
1365
        $shares = json_decode($entry->getSocialShares(), true);
1366
        if (!isset($shares['fbwall'])) {
1367
            $shares['fbwall'] = 1;
1368
        } else {
1369
            $shares['fbwall'] += 1;
1370
        }
1371
        $sharesJson = json_encode($shares);
1372
        $entry->setSocialShares($sharesJson);
1373
        $entry = $this->getEntryMapper()->update($entry);
1374
        
1375
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1376
            'user' => $user,
1377
            'game' => $game,
1378
            'secretKey' => $secretKey,
1379
            'topic' => $topic,
1380
            'entry' => $entry
1381
        ));
1382
1383
        return true;
1384
    }
1385
1386
    public function postFbRequest($secretKey, $game, $user, $entry, $to)
1387
    {
1388
        $shares = json_decode($entry->getSocialShares(), true);
1389
        $to = explode(',', $to);
1390
        if (!isset($shares['fbrequest'])) {
1391
            $shares['fbrequest'] = count($to);
1392
        } else {
1393
            $shares['fbrequest'] += count($to);
1394
        }
1395
        $sharesJson = json_encode($shares);
1396
        $entry->setSocialShares($sharesJson);
1397
        $entry = $this->getEntryMapper()->update($entry);
1398
        
1399
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1400
            'user' => $user,
1401
            'game' => $game,
1402
            'secretKey' => $secretKey,
1403
            'entry' => $entry,
1404
            'invites' => count($to)
1405
        ));
1406
1407
        return true;
1408
    }
1409
1410 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...
1411
    {
1412
        $topic = $game->getTitle();
1413
1414
        $shares = json_decode($entry->getSocialShares(), true);
1415
        if (!isset($shares['fbrequest'])) {
1416
            $shares['tweet'] = 1;
1417
        } else {
1418
            $shares['tweet'] += 1;
1419
        }
1420
        $sharesJson = json_encode($shares);
1421
        $entry->setSocialShares($sharesJson);
1422
        $entry = $this->getEntryMapper()->update($entry);
1423
        
1424
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1425
            'user' => $user,
1426
            'game' => $game,
1427
            'secretKey' => $secretKey,
1428
            'topic' => $topic,
1429
            'entry' => $entry
1430
        ));
1431
1432
        return true;
1433
    }
1434
1435 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...
1436
    {
1437
        $topic = $game->getTitle();
1438
        
1439
        $shares = json_decode($entry->getSocialShares(), true);
1440
        if (!isset($shares['fbrequest'])) {
1441
            $shares['google'] = 1;
1442
        } else {
1443
            $shares['google'] += 1;
1444
        }
1445
        $sharesJson = json_encode($shares);
1446
        $entry->setSocialShares($sharesJson);
1447
        $entry = $this->getEntryMapper()->update($entry);
1448
1449
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1450
            'user' => $user,
1451
            'game' => $game,
1452
            'secretKey' => $secretKey,
1453
            'topic' => $topic,
1454
            'entry' => $entry
1455
        ));
1456
1457
        return true;
1458
    }
1459
1460
    /**
1461
     * Is it possible to trigger a bonus entry ?
1462
     *
1463
     * @param unknown_type $game
1464
     * @param unknown_type $user
1465
     */
1466
    public function allowBonus($game, $user)
1467
    {
1468
        if (! $game->getPlayBonus() || $game->getPlayBonus() == 'none') {
1469
            return false;
1470
        } elseif ($game->getPlayBonus() == 'one') {
1471
            if ($this->getEntryMapper()->findOneBy(array(
1472
                'game' => $game,
1473
                'user' => $user,
1474
                'bonus' => 1
1475
            ))) {
1476
                return false;
1477
            } else {
1478
                return true;
1479
            }
1480
        } elseif ($game->getPlayBonus() == 'per_entry') {
1481
            return $this->getEntryMapper()->checkBonusEntry($game, $user);
1482
        }
1483
1484
        return false;
1485
    }
1486
1487
    public function addAnotherEntry($game, $user, $winner = 0)
1488
    {
1489
        $entry = new Entry();
1490
        $entry->setGame($game);
1491
        $entry->setUser($user);
1492
        $entry->setPoints(0);
1493
        $entry->setIp($this->getIp());
1494
        $entry->setActive(0);
1495
        $entry->setBonus(1);
1496
        $entry->setWinner($winner);
1497
        $entry = $this->getEntryMapper()->insert($entry);
1498
1499
        return $entry;
1500
    }
1501
1502
    /**
1503
     * This bonus entry doesn't give points nor badges
1504
     * It's just there to increase the chances during the Draw
1505
     * Old Name playBonus
1506
     *
1507
     * @param PlaygroundGame\Entity\Game $game
1508
     * @param unknown $user
1509
     * @return boolean unknown
1510
     */
1511
    public function addAnotherChance($game, $user, $winner = 0)
1512
    {
1513
        if ($this->allowBonus($game, $user)) {
1514
            $this->addAnotherEntry($game, $user, $winner);
1515
1516
            return true;
1517
        }
1518
1519
        return false;
1520
    }
1521
1522
    /**
1523
     * This bonus entry doesn't give points nor badges but can play again
1524
     *
1525
     * @param PlaygroundGame\Entity\Game $game
1526
     * @param user $user
1527
     * @return boolean unknown
1528
     */
1529
    public function playAgain($game, $user, $winner = 0)
1530
    {
1531
        if ($this->allowBonus($game, $user)) {
1532
            $entry = $this->addAnotherEntry($game, $user, $winner);
1533
            $entry->setActive(1);
1534
            $entry = $this->getEntryMapper()->update($entry);
1535
            if ($entry->getActive() == 1) {
1536
                return true;
1537
            }
1538
        }
1539
1540
        return false;
1541
    }
1542
1543 View Code Duplication
    public static function cronMail()
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...
1544
    {
1545
        $configuration = require 'config/application.config.php';
1546
        $smConfig = isset($configuration['service_manager']) ? $configuration['service_manager'] : array();
1547
        $sm = new \Zend\ServiceManager\ServiceManager(new \Zend\Mvc\Service\ServiceManagerConfig($smConfig));
1548
        $sm->setService('ApplicationConfig', $configuration);
1549
        $sm->get('ModuleManager')->loadModules();
1550
        $sm->get('Application')->bootstrap();
1551
1552
        $mailService = $sm->get('playgrounduser_message');
1553
        $gameService = $sm->get('playgroundgame_quiz_service');
1554
1555
        $from = "[email protected]";
1556
        $subject = "sujet game";
1557
1558
        $to = "[email protected]";
1559
1560
        $game = $gameService->checkGame('qooqo');
1561
1562
        $message = $mailService->createTextMessage($from, $to, $subject, 'playground-game/email/share_reminder', array(
1563
            'game' => $game
1564
        ));
1565
1566
        $mailService->send($message);
1567
    }
1568
1569
    /**
1570
     * @param string $path
1571
     */
1572
    public function uploadFile($path, $file)
1573
    {
1574
        $err = $file["error"];
1575
        $message = '';
1576
        if ($err > 0) {
1577
            switch ($err) {
1578
                case '1':
1579
                    $message .= 'Max file size exceeded. (php.ini)';
1580
                    break;
1581
                case '2':
1582
                    $message .= 'Max file size exceeded.';
1583
                    break;
1584
                case '3':
1585
                    $message .= 'File upload was only partial.';
1586
                    break;
1587
                case '4':
1588
                    $message .= 'No file was attached.';
1589
                    break;
1590
                case '7':
1591
                    $message .= 'File permission denied.';
1592
                    break;
1593
                default:
1594
                    $message .= 'Unexpected error occurs.';
1595
            }
1596
1597
            return $err;
1598
        } else {
1599
            $fileNewname = $this->fileNewname($path, $file['name'], true);
1600
1601
            if (isset($file["base64"])) {
1602
                list(, $img) = explode(',', $file["base64"]);
1603
                $img = str_replace(' ', '+', $img);
1604
                $im = base64_decode($img);
1605
                if ($im !== false) {
1606
                    // getimagesizefromstring
1607
                    file_put_contents($path . $fileNewname, $im);
1608
                } else {
1609
                    return 1;
1610
                }
1611
1612
                return $fileNewname;
1613
            } else {
1614
                $adapter = new \Zend\File\Transfer\Adapter\Http();
1615
                // 1Mo
1616
                $size = new Size(array(
1617
                    'max' => 1024000
1618
                ));
1619
                $is_image = new IsImage('jpeg,png,gif,jpg');
1620
                $adapter->setValidators(array(
1621
                    $size,
1622
                    $is_image
1623
                ), $fileNewname);
1624
1625
                if (! $adapter->isValid()) {
1626
                    return false;
1627
                }
1628
1629
                @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...
1630
            }
1631
1632
            
1633
            if (class_exists("Imagick")) {
1634
                $ext = pathinfo($fileNewname, PATHINFO_EXTENSION);
1635
                $img = new \Imagick($path . $fileNewname);
1636
                $img->cropThumbnailImage(100, 100);
1637
                $img->setImageCompression(\Imagick::COMPRESSION_JPEG);
1638
                $img->setImageCompressionQuality(75);
1639
                // Strip out unneeded meta data
1640
                $img->stripImage();
1641
                $img->writeImage($path . str_replace('.'.$ext, '-thumbnail.'.$ext, $fileNewname));
1642
                ErrorHandler::stop(true);
1643
            }
1644
        }
1645
1646
        return $fileNewname;
1647
    }
1648
1649
    /**
1650
     * @param string $path
1651
     */
1652
    public function fileNewname($path, $filename, $generate = false)
1653
    {
1654
        $sanitize = new Sanitize();
1655
        $name = $sanitize->filter($filename);
1656
        $newpath = $path . $name;
1657
1658
        if ($generate) {
1659
            if (file_exists($newpath)) {
1660
                $filename = pathinfo($name, PATHINFO_FILENAME);
1661
                $ext = pathinfo($name, PATHINFO_EXTENSION);
1662
1663
                $name = $filename . '_' . rand(0, 99) . '.' . $ext;
1664
            }
1665
        }
1666
1667
        unset($sanitize);
1668
1669
        return $name;
1670
    }
1671
1672
    /**
1673
     * This function returns the list of games, order by $type
1674
     */
1675
    public function getQueryGamesOrderBy($type = 'createdAt', $order = 'DESC')
1676
    {
1677
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
1678
        $today = new \DateTime("now");
1679
        $today = $today->format('Y-m-d') . ' 23:59:59';
1680
1681
        $onlineGames = '(
1682
            (
1683
                CASE WHEN (
1684
                    g.active = 1
1685
                    AND g.broadcastPlatform = 1
1686
                    AND (g.startDate <= :date OR g.startDate IS NULL)
1687
                    AND (g.closeDate >= :date OR g.closeDate IS NULL)
1688
                ) THEN 1 ELSE 0 END
1689
            ) +
1690
            (
1691
                CASE WHEN (
1692
                    g.active = 0
1693
                    AND (g.broadcastPlatform = 0 OR g.broadcastPlatform IS NULL)
1694
                    AND g.startDate > :date
1695
                    AND g.closeDate < :date
1696
                ) THEN 1 ELSE 0 END
1697
            )
1698
        )';
1699
1700
        $qb = $em->createQueryBuilder();
1701
        $qb->select('g')->from('PlaygroundGame\Entity\Game', 'g');
1702
        
1703
        switch ($type) {
1704
            case 'startDate':
1705
                $qb->orderBy('g.startDate', $order);
1706
                break;
1707
            case 'activeGames':
1708
                $qb->orderBy('g.active', $order);
1709
                break;
1710
            case 'onlineGames':
1711
                $qb->orderBy($onlineGames, $order);
1712
                $qb->setParameter('date', $today);
1713
                break;
1714
            case 'createdAt':
1715
                $qb->orderBy('g.createdAt', $order);
1716
                break;
1717
        }
1718
1719
        $query = $qb->getQuery();
1720
1721
        return $query;
1722
    }
1723
1724
    public function draw($game)
1725
    {
1726
        $total = $game->getWinners();
1727
1728
        // I Have to know what is the User Class used
1729
        $zfcUserOptions = $this->getServiceManager()->get('zfcuser_module_options');
1730
        $userClass = $zfcUserOptions->getUserEntityClass();
1731
1732
        $result = $this->getEntryMapper()->draw($game, $userClass, $total);
1733
1734
        foreach ($result as $e) {
1735
            $e->setWinner(1);
1736
            $e = $this->getEntryMapper()->update($e);
1737
            $this->getEventManager()->trigger('win_lottery.post', $this, array(
1738
                'user' => $e->getUser(),
1739
                'game' => $game,
1740
                'entry' => $e
1741
            ));
1742
        }
1743
1744
        return $result;
1745
    }
1746
1747
    /**
1748
     * getGameMapper
1749
     *
1750
     * @return GameMapperInterface
1751
     */
1752 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...
1753
    {
1754
        if (null === $this->gameMapper) {
1755
            $this->gameMapper = $this->getServiceManager()->get('playgroundgame_game_mapper');
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->getServiceManager...roundgame_game_mapper') can also be of type array. However, the property $gameMapper is declared as type object<PlaygroundGame\Mapper\GameInterface>. Maybe add an additional type check?

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

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

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

class Id
{
    public $id;

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

}

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

$account_id = false;

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

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
1756
        }
1757
1758
        return $this->gameMapper;
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->gameMapper; of type object|array adds the type array to the return on line 1758 which is incompatible with the return type documented by PlaygroundGame\Service\Game::getGameMapper of type PlaygroundGame\Mapper\GameInterface.
Loading history...
1759
    }
1760
1761
    /**
1762
     * setGameMapper
1763
     *
1764
     * @param GameMapperInterface $gameMapper
1765
     * @return Game
1766
     */
1767
    public function setGameMapper(GameMapperInterface $gameMapper)
1768
    {
1769
        $this->gameMapper = $gameMapper;
1770
1771
        return $this;
1772
    }
1773
1774
    /**
1775
     * getEntryMapper
1776
     *
1777
     * @return EntryMapperInterface
1778
     */
1779 View Code Duplication
    public function getEntryMapper()
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...
1780
    {
1781
        if (null === $this->entryMapper) {
1782
            $this->entryMapper = $this->getServiceManager()->get('playgroundgame_entry_mapper');
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->getServiceManager...oundgame_entry_mapper') can also be of type array. However, the property $entryMapper is declared as type object<PlaygroundGame\Se...e\EntryMapperInterface>. Maybe add an additional type check?

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

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

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

class Id
{
    public $id;

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

}

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

$account_id = false;

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

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
1783
        }
1784
1785
        return $this->entryMapper;
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->entryMapper; of type object|array adds the type array to the return on line 1785 which is incompatible with the return type documented by PlaygroundGame\Service\Game::getEntryMapper of type PlaygroundGame\Service\EntryMapperInterface.
Loading history...
1786
    }
1787
1788
    /**
1789
     * setEntryMapper
1790
     *
1791
     * @param EntryMapperInterface $entryMapper
1792
     * @return Game
1793
     */
1794
    public function setEntryMapper($entryMapper)
1795
    {
1796
        $this->entryMapper = $entryMapper;
1797
1798
        return $this;
1799
    }
1800
1801
    public function setOptions(ModuleOptions $options)
1802
    {
1803
        $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...
1804
1805
        return $this;
1806
    }
1807
1808
    public function getOptions()
1809
    {
1810
        if (! $this->options instanceof ModuleOptions) {
1811
            $this->setOptions($this->getServiceManager()
0 ignored issues
show
Documentation introduced by
$this->getServiceManager...ndgame_module_options') is of type object|array, but the function expects a object<PlaygroundGame\Options\ModuleOptions>.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1812
                ->get('playgroundgame_module_options'));
1813
        }
1814
1815
        return $this->options;
1816
    }
1817
1818
    /**
1819
     * Retrieve service manager instance
1820
     *
1821
     * @return ServiceManager
1822
     */
1823
    public function getServiceManager()
1824
    {
1825
        return $this->serviceManager;
1826
    }
1827
1828
    /**
1829
     * Set service manager instance
1830
     *
1831
     * @param ServiceManager $serviceManager
1832
     * @return Game
1833
     */
1834
    public function setServiceManager(ServiceManager $serviceManager)
1835
    {
1836
        $this->serviceManager = $serviceManager;
1837
1838
        return $this;
1839
    }
1840
1841
    /**
1842
     * @param string $str
1843
     */
1844
    public function getExtension($str)
1845
    {
1846
        $i = strrpos($str, '.');
1847
1848
        $l = strlen($str) - $i;
1849
        $ext = substr($str, $i + 1, $l);
1850
1851
        return $ext;
1852
    }
1853
1854
    /**
1855
     * @param string $extension
1856
     */
1857
    public function getSrc($extension, $temp_path)
1858
    {
1859
        $image_src = '';
1860
        switch ($extension) {
1861
            case 'jpg':
1862
                $image_src = imagecreatefromjpeg($temp_path);
1863
                break;
1864
            case 'jpeg':
1865
                $image_src = imagecreatefromjpeg($temp_path);
1866
                break;
1867
            case 'png':
1868
                $image_src = imagecreatefrompng($temp_path);
1869
                break;
1870
            case 'gif':
1871
                $image_src = imagecreatefromgif($temp_path);
1872
                break;
1873
        }
1874
1875
        return $image_src;
1876
    }
1877
1878
    /**
1879
     * @param string $extension
1880
     * @param string $rep
1881
     * @param integer $mini_width
1882
     * @param integer $mini_height
1883
     */
1884
    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...
1885
    {
1886
        list($src_width, $src_height) = getimagesize($tmp_file);
1887
1888
        $ratio_src = $src_width / $src_height;
1889
        $ratio_mini = $mini_width / $mini_height;
1890
1891
        if ($ratio_src >= $ratio_mini) {
1892
            $new_height_mini = $mini_height;
1893
            $new_width_mini = $src_width / ($src_height / $mini_height);
1894
        } else {
1895
            $new_width_mini = $mini_width;
1896
            $new_height_mini = $src_height / ($src_width / $mini_width);
1897
        }
1898
1899
        $new_image_mini = imagecreatetruecolor($mini_width, $mini_height);
1900
1901
        imagecopyresampled(
1902
            $new_image_mini,
1903
            $src,
1904
            0 - ($new_width_mini - $mini_width) / 2,
1905
            0 - ($new_height_mini - $mini_height) / 2,
1906
            0,
1907
            0,
1908
            $new_width_mini,
1909
            $new_height_mini,
1910
            $src_width,
1911
            $src_height
1912
        );
1913
        imagejpeg($new_image_mini, $rep);
1914
1915
        imagedestroy($new_image_mini);
1916
    }
1917
1918
    public function getGameEntity()
1919
    {
1920
        return new \PlaygroundGame\Entity\Game();
1921
    }
1922
1923
    /**
1924
     * @param string $resource
1925
     * @param string $privilege
1926
     */
1927
    public function isAllowed($resource, $privilege = null)
1928
    {
1929
        $auth = $this->getServiceManager()->get('BjyAuthorize\Service\Authorize');
1930
1931
        return $auth->isAllowed($resource, $privilege);
1932
    }
1933
1934
    public function getIp()
1935
    {
1936
        $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...
1937
        if (isset($_SERVER['HTTP_CLIENT_IP'])) {
1938
            $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
1939
        } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1940
            $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
1941
        } elseif (isset($_SERVER['HTTP_X_FORWARDED'])) {
1942
            $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
1943
        } elseif (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
1944
            $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
1945
        } elseif (isset($_SERVER['HTTP_FORWARDED'])) {
1946
            $ipaddress = $_SERVER['HTTP_FORWARDED'];
1947
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
1948
            $ipaddress = $_SERVER['REMOTE_ADDR'];
1949
        } else {
1950
            $ipaddress = 'UNKNOWN';
1951
        }
1952
1953
        return $ipaddress;
1954
    }
1955
1956
    public function getAnonymousId()
1957
    {
1958
        $anonymousId = '';
1959
        if ($_COOKIE && array_key_exists('pg_anonymous', $_COOKIE)) {
1960
            $anonymousId = $_COOKIE['pg_anonymous'];
1961
        }
1962
1963
        return $anonymousId;
1964
    }
1965
1966
    /**
1967
     *
1968
     *
1969
     * This service is ready for all types of games
1970
     *
1971
     * @param array $data
1972
     * @return \PlaygroundGame\Entity\Game
1973
     */
1974 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...
1975
    {
1976
        $title = '';
1977
        $description = '';
1978
1979
        if ($data['form_jsonified']) {
1980
            $jsonPV = json_decode($data['form_jsonified']);
1981
            foreach ($jsonPV as $element) {
1982
                if ($element->form_properties) {
1983
                    $attributes = $element->form_properties[0];
1984
                    $title = $attributes->title;
1985
                    $description = $attributes->description;
1986
1987
                    break;
1988
                }
1989
            }
1990
        }
1991
        if (! $form) {
1992
            $form = new \PlaygroundGame\Entity\PlayerForm();
1993
        }
1994
        $form->setGame($game);
1995
        $form->setTitle($title);
1996
        $form->setDescription($description);
1997
        $form->setForm($data['form_jsonified']);
1998
        $form->setFormTemplate($data['form_template']);
1999
2000
        $form = $this->getPlayerFormMapper()->insert($form);
2001
2002
        return $form;
2003
    }
2004
2005
    /**
2006
     *  getCSV creates lines of CSV and returns it.
2007
     */
2008
    public function getCSV($array)
2009
    {
2010
        ob_start(); // buffer the output ...
2011
        $out = fopen('php://output', 'w');
2012
        fputcsv($out, array_keys($array[0]), ";");
2013
        foreach ($array as $line) {
2014
            fputcsv($out, $line, ";");
2015
        }
2016
        fclose($out);
2017
        return ob_get_clean(); // ... then return it as a string!
2018
    }
2019
    
2020
    /**
2021
     * Create a ZF2 Form from json data
2022
     * @return Form
2023
     */
2024
    public function createFormFromJson($jsonForm, $id = 'jsonForm')
2025
    {
2026
        $formPV = json_decode($jsonForm);
2027
        
2028
        $form = new Form();
2029
        $form->setAttribute('id', $id);
2030
        $form->setAttribute('enctype', 'multipart/form-data');
2031
        
2032
        $inputFilter = new \Zend\InputFilter\InputFilter();
2033
        $factory = new InputFactory();
2034
        
2035
        foreach ($formPV as $element) {
2036
            if (isset($element->line_text)) {
2037
                $attributes  = $element->line_text[0];
2038
                $name        = isset($attributes->name)? $attributes->name : '';
2039
                $placeholder = isset($attributes->data->placeholder)? $attributes->data->placeholder : '';
2040
                $label       = isset($attributes->data->label)? $attributes->data->label : '';
2041
                $required    = ($attributes->data->required == 'true') ? true : false ;
2042
                $class       = isset($attributes->data->class)? $attributes->data->class : '';
2043
                $id          = isset($attributes->data->id)? $attributes->data->id : '';
2044
                $lengthMin   = isset($attributes->data->length)? $attributes->data->length->min : '';
2045
                $lengthMax   = isset($attributes->data->length)? $attributes->data->length->max : '';
2046
                $validator   = isset($attributes->data->validator)? $attributes->data->validator : '';
2047
        
2048
                $element = new Element\Text($name);
2049
                $element->setLabel($label);
2050
                $element->setAttributes(
2051
                    array(
2052
                        'placeholder'    => $placeholder,
2053
                        'required'        => $required,
2054
                        'class'        => $class,
2055
                        'id'            => $id
2056
                    )
2057
                );
2058
                $form->add($element);
2059
        
2060
                $options = array();
2061
                $options['encoding'] = 'UTF-8';
2062
                if ($lengthMin && $lengthMin > 0) {
2063
                    $options['min'] = $lengthMin;
2064
                }
2065 View Code Duplication
                if ($lengthMax && $lengthMax > $lengthMin) {
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...
2066
                    $options['max'] = $lengthMax;
2067
                    $element->setAttribute('maxlength', $lengthMax);
2068
                    $options['messages'] = array(
2069
                        \Zend\Validator\StringLength::TOO_LONG => sprintf(
2070
                            $this->getServiceLocator()->get('translator')->translate(
0 ignored issues
show
Bug introduced by
The method getServiceLocator() does not seem to exist on object<PlaygroundGame\Service\Game>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
2071
                                'This field contains more than %s characters',
2072
                                'playgroundgame'
2073
                            ),
2074
                            $lengthMax
2075
                        )
2076
                    );
2077
                }
2078
2079
                $validators = array(
2080
                    array(
2081
                        'name'    => 'StringLength',
2082
                        'options' => $options,
2083
                    ),
2084
                );
2085
                if ($validator) {
2086
                    $regex = "/.*\(([^)]*)\)/";
2087
                    preg_match($regex, $validator, $matches);
2088
                    $valArray = array(
2089
                        'name' => str_replace(
2090
                            '('.$matches[1].')',
2091
                            '',
2092
                            $validator
2093
                        ),
2094
                        'options' => array($matches[1])
2095
                    );
2096
                    $validators[] = $valArray;
2097
                }
2098
2099
                $inputFilter->add($factory->createInput(array(
2100
                    'name'     => $name,
2101
                    'required' => $required,
2102
                    'filters'  => array(
2103
                        array('name' => 'StripTags'),
2104
                        array('name' => 'StringTrim'),
2105
                    ),
2106
                    'validators' => $validators,
2107
                )));
2108
            }
2109
            if (isset($element->line_password)) {
2110
                $attributes  = $element->line_password[0];
2111
                $name        = isset($attributes->name)? $attributes->name : '';
2112
                $placeholder = isset($attributes->data->placeholder)? $attributes->data->placeholder : '';
2113
                $label       = isset($attributes->data->label)? $attributes->data->label : '';
2114
                $required    = (
2115
                    isset($attributes->data->required) &&
2116
                    $attributes->data->required == 'true'
2117
                ) ? true : false ;
2118
                $class       = isset($attributes->data->class)? $attributes->data->class : '';
2119
                $id          = isset($attributes->data->id)? $attributes->data->id : '';
2120
                $lengthMin   = isset($attributes->data->length)? $attributes->data->length->min : '';
2121
                $lengthMax   = isset($attributes->data->length)? $attributes->data->length->max : '';
2122
        
2123
                $element = new Element\Password($name);
2124
                $element->setLabel($label);
2125
                $element->setAttributes(
2126
                    array(
2127
                        'placeholder'   => $placeholder,
2128
                        'required'      => $required,
2129
                        'class'         => $class,
2130
                        'id'            => $id
2131
                    )
2132
                );
2133
                $form->add($element);
2134
        
2135
                $options = array();
2136
                $options['encoding'] = 'UTF-8';
2137
                if ($lengthMin && $lengthMin > 0) {
2138
                    $options['min'] = $lengthMin;
2139
                }
2140 View Code Duplication
                if ($lengthMax && $lengthMax > $lengthMin) {
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...
2141
                    $options['max'] = $lengthMax;
2142
                    $element->setAttribute('maxlength', $lengthMax);
2143
                    $options['messages'] = array(
2144
                        \Zend\Validator\StringLength::TOO_LONG => sprintf(
2145
                            $this->getServiceLocator()->get('translator')->translate(
0 ignored issues
show
Bug introduced by
The method getServiceLocator() does not seem to exist on object<PlaygroundGame\Service\Game>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
2146
                                'This field contains more than %s characters',
2147
                                'playgroundgame'
2148
                            ),
2149
                            $lengthMax
2150
                        )
2151
                    );
2152
                }
2153
                $inputFilter->add($factory->createInput(array(
2154
                    'name'     => $name,
2155
                    'required' => $required,
2156
                    'filters'  => array(
2157
                        array('name' => 'StripTags'),
2158
                        array('name' => 'StringTrim'),
2159
                    ),
2160
                    'validators' => array(
2161
                        array(
2162
                            'name'    => 'StringLength',
2163
                            'options' => $options,
2164
                        ),
2165
                    ),
2166
                )));
2167
            }
2168
            if (isset($element->line_hidden)) {
2169
                $attributes  = $element->line_hidden[0];
2170
                $name        = isset($attributes->name)? $attributes->name : '';
2171
                $label       = isset($attributes->data->label)? $attributes->data->label : '';
2172
                $required    = ($attributes->data->required == 'true') ? true : false ;
2173
                $class       = isset($attributes->data->class)? $attributes->data->class : '';
2174
                $id          = isset($attributes->data->id)? $attributes->data->id : '';
2175
                $lengthMin   = isset($attributes->data->length)? $attributes->data->length->min : '';
2176
                $lengthMax   = isset($attributes->data->length)? $attributes->data->length->max : '';
2177
        
2178
                $element = new Element\Hidden($name);
2179
                $element->setLabel($label);
2180
                $element->setAttributes(
2181
                    array(
2182
                        'required'      => $required,
2183
                        'class'         => $class,
2184
                        'id'            => $id
2185
                    )
2186
                );
2187
                $form->add($element);
2188
        
2189
                $options = array();
2190
                $options['encoding'] = 'UTF-8';
2191
                if ($lengthMin && $lengthMin > 0) {
2192
                    $options['min'] = $lengthMin;
2193
                }
2194 View Code Duplication
                if ($lengthMax && $lengthMax > $lengthMin) {
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...
2195
                    $options['max'] = $lengthMax;
2196
                    $element->setAttribute('maxlength', $lengthMax);
2197
                    $options['messages'] = array(
2198
                        \Zend\Validator\StringLength::TOO_LONG => sprintf(
2199
                            $this->getServiceLocator()->get('translator')->translate(
0 ignored issues
show
Bug introduced by
The method getServiceLocator() does not seem to exist on object<PlaygroundGame\Service\Game>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
2200
                                'This field contains more than %s characters',
2201
                                'playgroundgame'
2202
                            ),
2203
                            $lengthMax
2204
                        )
2205
                    );
2206
                }
2207
                $inputFilter->add($factory->createInput(array(
2208
                    'name'     => $name,
2209
                    'required' => $required,
2210
                    'filters'  => array(
2211
                        array('name' => 'StripTags'),
2212
                        array('name' => 'StringTrim'),
2213
                    ),
2214
                    'validators' => array(
2215
                        array(
2216
                            'name'    => 'StringLength',
2217
                            'options' => $options,
2218
                        ),
2219
                    ),
2220
                )));
2221
            }
2222
            if (isset($element->line_email)) {
2223
                $attributes  = $element->line_email[0];
2224
                $name        = isset($attributes->name)? $attributes->name : '';
2225
                $placeholder = isset($attributes->data->placeholder)? $attributes->data->placeholder : '';
2226
                $label       = isset($attributes->data->label)? $attributes->data->label : '';
2227
                $class       = isset($attributes->data->class)? $attributes->data->class : '';
2228
                $id          = isset($attributes->data->id)? $attributes->data->id : '';
2229
                $lengthMin   = isset($attributes->data->length)? $attributes->data->length->min : '';
2230
                $lengthMax   = isset($attributes->data->length)? $attributes->data->length->max : '';
2231
        
2232
                $element = new Element\Email($name);
2233
                $element->setLabel($label);
2234
                $element->setAttributes(
2235
                    array(
2236
                        'placeholder'    => $placeholder,
2237
                        'required'        => $required,
0 ignored issues
show
Bug introduced by
The variable $required 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...
2238
                        'class'        => $class,
2239
                        'id'            => $id
2240
                    )
2241
                );
2242
                $form->add($element);
2243
        
2244
                $options = array();
2245
                $options['encoding'] = 'UTF-8';
2246
                if ($lengthMin && $lengthMin > 0) {
2247
                    $options['min'] = $lengthMin;
2248
                }
2249 View Code Duplication
                if ($lengthMax && $lengthMax > $lengthMin) {
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...
2250
                    $options['max'] = $lengthMax;
2251
                    $element->setAttribute('maxlength', $lengthMax);
2252
                    $options['messages'] = array(
2253
                        \Zend\Validator\StringLength::TOO_LONG => sprintf(
2254
                            $this->getServiceLocator()->get('translator')->translate(
0 ignored issues
show
Bug introduced by
The method getServiceLocator() does not seem to exist on object<PlaygroundGame\Service\Game>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
2255
                                'This field contains more than %s characters',
2256
                                'playgroundgame'
2257
                            ),
2258
                            $lengthMax
2259
                        )
2260
                    );
2261
                }
2262
                $inputFilter->add($factory->createInput(array(
2263
                    'name'     => $name,
2264
                    'required' => $required,
2265
                    'filters'  => array(
2266
                        array('name' => 'StripTags'),
2267
                        array('name' => 'StringTrim'),
2268
                    ),
2269
                    'validators' => array(
2270
                        array(
2271
                            'name'    => 'StringLength',
2272
                            'options' => $options,
2273
                        ),
2274
                    ),
2275
                )));
2276
            }
2277 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...
2278
                $attributes  = $element->line_radio[0];
2279
                $name        = isset($attributes->name)? $attributes->name : '';
2280
                $label       = isset($attributes->data->label)? $attributes->data->label : '';
2281
        
2282
                $required = false;
2283
                $class       = isset($attributes->data->class)? $attributes->data->class : '';
2284
                $id          = isset($attributes->data->id)? $attributes->data->id : '';
2285
                $lengthMin   = isset($attributes->data->length)? $attributes->data->length->min : '';
2286
                $lengthMax   = isset($attributes->data->length)? $attributes->data->length->max : '';
2287
                $innerData   = isset($attributes->data->innerData)? $attributes->data->innerData : array();
2288
        
2289
                $element = new Element\Radio($name);
2290
                $element->setLabel($label);
2291
                $element->setAttributes(
2292
                    array(
2293
                        'name'          => $name,
2294
                        'required'        => $required,
2295
                        'allowEmpty'    => !$required,
2296
                        'class'        => $class,
2297
                        'id'            => $id
2298
                    )
2299
                );
2300
                $values = array();
2301
                foreach ($innerData as $value) {
2302
                    $values[] = $value->label;
2303
                }
2304
                $element->setValueOptions($values);
2305
        
2306
                $options = array();
2307
                $options['encoding'] = 'UTF-8';
2308
                $options['disable_inarray_validator'] = true;
2309
        
2310
                $element->setOptions($options);
2311
        
2312
                $form->add($element);
2313
        
2314
                $inputFilter->add($factory->createInput(array(
2315
                    'name'     => $name,
2316
                    'required' => $required,
2317
                    'allowEmpty' => !$required,
2318
                )));
2319
            }
2320 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...
2321
                $attributes  = $element->line_checkbox[0];
2322
                $name        = isset($attributes->name)? $attributes->name : '';
2323
                $label       = isset($attributes->data->label)? $attributes->data->label : '';
2324
        
2325
                $required = false;
2326
                $class       = isset($attributes->data->class)? $attributes->data->class : '';
2327
                $id          = isset($attributes->data->id)? $attributes->data->id : '';
2328
                $lengthMin   = isset($attributes->data->length)? $attributes->data->length->min : '';
2329
                $lengthMax   = isset($attributes->data->length)? $attributes->data->length->max : '';
2330
                $innerData   = isset($attributes->data->innerData)? $attributes->data->innerData : array();
2331
        
2332
                $element = new Element\MultiCheckbox($name);
2333
                $element->setLabel($label);
2334
                $element->setAttributes(
2335
                    array(
2336
                        'name'     => $name,
2337
                        'required'        => $required,
2338
                        'allowEmpty'    => !$required,
2339
                        'class'        => $class,
2340
                        'id'            => $id
2341
                    )
2342
                );
2343
                $values = array();
2344
                foreach ($innerData as $value) {
2345
                    $values[] = $value->label;
2346
                }
2347
                $element->setValueOptions($values);
2348
                $form->add($element);
2349
        
2350
                $options = array();
2351
                $options['encoding'] = 'UTF-8';
2352
                $options['disable_inarray_validator'] = true;
2353
        
2354
                $element->setOptions($options);
2355
        
2356
                $inputFilter->add($factory->createInput(array(
2357
                    'name'     => $name,
2358
                    'required' => $required,
2359
                    'allowEmpty' => !$required,
2360
                )));
2361
            }
2362 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...
2363
                $attributes  = $element->line_dropdown[0];
2364
                $name        = isset($attributes->name)? $attributes->name : '';
2365
                $label       = isset($attributes->data->label)? $attributes->data->label : '';
2366
        
2367
                $required = false;
2368
                $class       = isset($attributes->data->class)? $attributes->data->class : '';
2369
                $id          = isset($attributes->data->id)? $attributes->data->id : '';
2370
                $lengthMin   = isset($attributes->data->length)? $attributes->data->length->min : '';
2371
                $lengthMax   = isset($attributes->data->length)? $attributes->data->length->max : '';
2372
                $dropdownValues   = isset($attributes->data->dropdownValues)?
2373
                    $attributes->data->dropdownValues :
2374
                    array();
2375
        
2376
                $element = new Element\Select($name);
2377
                $element->setLabel($label);
2378
                $element->setAttributes(
2379
                    array(
2380
                        'name'     => $name,
2381
                        'required'      => $required,
2382
                        'allowEmpty'    => !$required,
2383
                        'class'         => $class,
2384
                        'id'            => $id
2385
                    )
2386
                );
2387
                $values = array();
2388
                foreach ($dropdownValues as $value) {
2389
                    $values[] = $value->dropdown_label;
2390
                }
2391
                $element->setValueOptions($values);
2392
                $form->add($element);
2393
        
2394
                $options = array();
2395
                $options['encoding'] = 'UTF-8';
2396
                $options['disable_inarray_validator'] = true;
2397
        
2398
                $element->setOptions($options);
2399
        
2400
                $inputFilter->add($factory->createInput(array(
2401
                    'name'     => $name,
2402
                    'required' => $required,
2403
                    'allowEmpty' => !$required,
2404
                )));
2405
            }
2406
            if (isset($element->line_paragraph)) {
2407
                $attributes  = $element->line_paragraph[0];
2408
                $name        = isset($attributes->name)? $attributes->name : '';
2409
                $placeholder = isset($attributes->data->placeholder)? $attributes->data->placeholder : '';
2410
                $label       = isset($attributes->data->label)? $attributes->data->label : '';
2411
                $required    = ($attributes->data->required == 'true') ? true : false ;
2412
                $class       = isset($attributes->data->class)? $attributes->data->class : '';
2413
                $id          = isset($attributes->data->id)? $attributes->data->id : '';
2414
        
2415
                $element = new Element\Textarea($name);
2416
                $element->setLabel($label);
2417
                $element->setAttributes(
2418
                    array(
2419
                        'placeholder'    => $placeholder,
2420
                        'required'        => $required,
2421
                        'class'        => $class,
2422
                        'id'            => $id
2423
                    )
2424
                );
2425
                $form->add($element);
2426
        
2427
                $options = array();
2428
                $options['encoding'] = 'UTF-8';
2429
                if ($lengthMin && $lengthMin > 0) {
2430
                    $options['min'] = $lengthMin;
0 ignored issues
show
Bug introduced by
The variable $lengthMin 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...
2431
                }
2432
                if ($lengthMax && $lengthMax > $lengthMin) {
2433
                    $options['max'] = $lengthMax;
0 ignored issues
show
Bug introduced by
The variable $lengthMax 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...
2434
                    $element->setAttribute('maxlength', $lengthMax);
2435
                }
2436
                $inputFilter->add($factory->createInput(array(
2437
                    'name'     => $name,
2438
                    'required' => $required,
2439
                    'filters'  => array(
2440
                        array('name' => 'StripTags'),
2441
                        array('name' => 'StringTrim'),
2442
                    ),
2443
                    'validators' => array(
2444
                        array(
2445
                            'name'    => 'StringLength',
2446
                            'options' => $options,
2447
                        ),
2448
                    ),
2449
                )));
2450
            }
2451
            if (isset($element->line_upload)) {
2452
                $attributes  = $element->line_upload[0];
2453
                $name        = isset($attributes->name)? $attributes->name : '';
2454
                $label       = isset($attributes->data->label)? $attributes->data->label : '';
2455
                $required    = ($attributes->data->required == 'true') ? true : false ;
2456
                $class       = isset($attributes->data->class)? $attributes->data->class : '';
2457
                $id          = isset($attributes->data->id)? $attributes->data->id : '';
2458
                $filesizeMin = isset($attributes->data->filesize)? $attributes->data->filesize->min : 0;
2459
                $filesizeMax = isset($attributes->data->filesize)? $attributes->data->filesize->max : 10*1024*1024;
2460
                $element = new Element\File($name);
2461
                $element->setLabel($label);
2462
                $element->setAttributes(
2463
                    array(
2464
                        'required'    => $required,
2465
                        'class'    => $class,
2466
                        'id'        => $id
2467
                    )
2468
                );
2469
                $form->add($element);
2470
        
2471
                $inputFilter->add($factory->createInput(array(
2472
                    'name'     => $name,
2473
                    'required' => $required,
2474
                    'validators' => array(
2475
                        array(
2476
                            'name' => '\Zend\Validator\File\Size',
2477
                            'options' => array('min' => $filesizeMin, 'max' => $filesizeMax)
2478
                        ),
2479
                        array(
2480
                            'name' => '\Zend\Validator\File\Extension',
2481
                            'options'  => array(
2482
                                'png,PNG,jpg,JPG,jpeg,JPEG,gif,GIF',
2483
                                'messages' => array(
2484
                                    \Zend\Validator\File\Extension::FALSE_EXTENSION =>'Veuillez télécharger une image'
2485
                                )
2486
                            )
2487
                        ),
2488
                    ),
2489
                )));
2490
            }
2491
        }
2492
        
2493
        $form->setInputFilter($inputFilter);
2494
        
2495
        return $form;
2496
    }
2497
2498
    /**
2499
     * Send mail for winner and/or loser
2500
     * @param \PlaygroundGame\Entity\Game $game
2501
     * @param \PlaygroundUser\Entity\User $user
2502
     * @param \PlaygroundGame\Entity\Entry $lastEntry
2503
     * @param \PlaygroundGame\Entity\Prize $prize
2504
     */
2505
    public function sendMail($game, $user, $lastEntry, $prize = null)
2506
    {
2507 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...
2508
            $game->getMailWinner() &&
2509
            $lastEntry->getWinner()
2510
        ) {
2511
            $this->sendResultMail($game, $user, $lastEntry, 'winner', $prize);
2512
        }
2513
2514 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...
2515
            $game->getMailLooser() &&
2516
            !$lastEntry->getWinner()
2517
        ) {
2518
            $this->sendResultMail($game, $user, $lastEntry, 'looser');
2519
        }
2520
    }
2521
2522
    public function getPlayerFormMapper()
2523
    {
2524
        if (null === $this->playerformMapper) {
2525
            $this->playerformMapper = $this->getServiceManager()->get('playgroundgame_playerform_mapper');
2526
        }
2527
2528
        return $this->playerformMapper;
2529
    }
2530
2531
    public function setPlayerFormMapper($playerformMapper)
2532
    {
2533
        $this->playerformMapper = $playerformMapper;
2534
2535
        return $this;
2536
    }
2537
}
2538