Completed
Push — master ( 6e2d8e...315e5f )
by greg
03:16
created

Game::sendGameMail()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 20
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 20
rs 9.4286
cc 1
eloc 15
nc 1
nop 4
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->isAllowed('game', 'edit')) {
804
            $game->setActive(true);
805
            $game->setStartDate(null);
806
            $game->setEndDate(null);
807
            $game->setPublicationDate(null);
808
            $game->setBroadcastPlatform(true);
809
810
            // I don't want the game to be updated through any update during the preview mode.
811
            // I mark it as readonly for Doctrine
812
            $this->getServiceManager()
813
                ->get('doctrine.entitymanager.orm_default')
814
                ->getUnitOfWork()
815
                ->markReadOnly($game);
816
            return $game;
817
        }
818
819
        // The game is inactive
820
        if (! $game->getActive()) {
821
            return false;
822
        }
823
824
        // the game has not begun yet
825
        if (! $game->isOpen()) {
826
            return false;
827
        }
828
829
        // the game is finished and closed
830
        if (! $game->isStarted() && $checkIfStarted) {
831
            return false;
832
        }
833
834
        return $game;
835
    }
836
837
    /**
838
     * Return the last entry of the user on this game, if it exists.
839
     * An entry can be associated to :
840
     * - A user account (a real one, linked to PlaygroundUser
841
     * - An anonymous Identifier (based on one value of playerData (generally email))
842
     * - A cookie set on the player device (the less secure)
843
     * If the active param is set, it can check if the entry is active or not.
844
     * If the bonus param is set, it can check if the entry is a bonus or not.
845
     *
846
     * @param unknown $game
847
     * @param string $user
848
     * @param boolean $active
849
     * @param boolean $bonus
850
     * @return boolean
851
     */
852
    public function checkExistingEntry($game, $user = null, $active = null, $bonus = null)
853
    {
854
        $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...
855
        $search = array('game'  => $game);
856
857
        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...
858
            $search['user'] = $user;
859
        } elseif ($this->getAnonymousIdentifier()) {
860
            $search['anonymousIdentifier'] = $this->getAnonymousIdentifier();
861
            $search['user'] = null;
862
        } else {
863
            $search['anonymousId'] = $this->getAnonymousId();
864
            $search['user'] = null;
865
        }
866
        
867
        if (! is_null($active)) {
868
            $search['active'] = $active;
869
        }
870
        if (! is_null($bonus)) {
871
            $search['bonus'] = $bonus;
872
        }
873
874
        $entry = $this->getEntryMapper()->findOneBy($search, array('updated_at' => 'desc'));
875
876
        return $entry;
877
    }
878
879
    /*
880
    * This function updates the entry with the player data after checking 
881
    * that the data are compliant with the formUser Game attribute
882
    *
883
    * The $data has to be a json object
884
    */
885
    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...
886
    {
887
        $form = $this->createFormFromJson($game->getPlayerForm()->getForm(), 'playerForm');
888
        $form->setData($data);
889
890
        if (!$mandatory) {
891
            $filter = $form->getInputFilter();
892
            foreach ($form->getElements() as $element) {
893
                try {
894
                    $elementInput = $filter->get($element->getName());
895
                    $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...
896
                    $form->get($element->getName())->setAttribute('required', false);
897
                } 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...
898
                }
899
            }
900
        }
901
902
        if ($form->isValid()) {
903
            $dataJson = json_encode($form->getData());
904
905
            if ($game->getAnonymousAllowed() &&
906
                $game->getAnonymousIdentifier() &&
907
                isset($data[$game->getAnonymousIdentifier()])
908
            ) {
909
                $session = new \Zend\Session\Container('anonymous_identifier');
910
                if (empty($session->offsetGet('anonymous_identifier'))) {
911
                    $anonymousIdentifier = $data[$game->getAnonymousIdentifier()];
912
                
913
                    $entry->setAnonymousIdentifier($anonymousIdentifier);
914
                
915
                    // I must transmit this info during the whole game workflow
916
                    $session->offsetSet('anonymous_identifier', $anonymousIdentifier);
917
                }
918
            }
919
920
            $entry->setPlayerData($dataJson);
921
            $this->getEntryMapper()->update($entry);
922
        } else {
923
            return false;
924
        }
925
926
        return true;
927
    }
928
929
930
    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...
931
    {
932
        // If on Facebook, check if you have to be a FB fan to play the game
933
        $session = new Container('facebook');
934
935
        if ($session->offsetExists('signed_request')) {
936
            // I'm on Facebook
937
            $sr = $session->offsetGet('signed_request');
938
            if ($sr['page']['liked'] == 1) {
939
                return true;
940
            }
941
        } else {
942
            // I'm not on Facebook
943
            return true;
944
        }
945
946
        return false;
947
    }
948
    
949
    public function getAnonymousIdentifier()
950
    {
951
        if (is_null($this->anonymousIdentifier)) {
952
            // If on Facebook, check if you have to be a FB fan to play the game
953
            $session = new Container('anonymous_identifier');
954
            
955
            if ($session->offsetExists('anonymous_identifier')) {
956
                $this->anonymousIdentifier = $session->offsetGet('anonymous_identifier');
957
            } else {
958
                $this->anonymousIdentifier = false;
959
            }
960
        }
961
    
962
        return $this->anonymousIdentifier;
963
    }
964
965
    /**
966
     * errors :
967
     * -1 : user not connected
968
     * -2 : limit entry games for this user reached
969
     *
970
     * @param \PlaygroundGame\Entity\Game $game
971
     * @param \PlaygroundUser\Entity\UserInterface $user
972
     * @return number unknown
973
     */
974
    public function play($game, $user)
975
    {
976
977
        // certaines participations peuvent rester ouvertes.
978
        // On autorise alors le joueur à reprendre là ou il en était
979
        // par exemple les postvote...
980
        $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...
981
982
        if (! $entry) {
983
            if ($this->hasReachedPlayLimit($game, $user)) {
984
                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...
985
            }
986
987
            $entry = new Entry();
988
            $entry->setGame($game);
989
            $entry->setUser($user);
990
            $entry->setPoints(0);
991
            $entry->setIp($this->getIp());
992
            $entry->setAnonymousId($this->getAnonymousId());
993
            if ($this->getAnonymousIdentifier()) {
994
                $entry->setAnonymousIdentifier($this->getAnonymousIdentifier());
995
            }
996
997
            $entry = $this->getEntryMapper()->insert($entry);
998
            $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
999
                'user' => $user,
1000
                'game' => $game,
1001
                'entry' => $entry
1002
            ));
1003
        }
1004
1005
        return $entry;
1006
    }
1007
1008
    /**
1009
     * @param \PlaygroundGame\Entity\Game $game
1010
     * @param \PlaygroundUser\Entity\UserInterface $user
1011
     */
1012
    public function hasReachedPlayLimit($game, $user)
1013
    {
1014
        // Is there a limitation on the game ?
1015
        $limitAmount = $game->getPlayLimit();
1016
        if ($limitAmount) {
1017
            $limitScale = $game->getPlayLimitScale();
1018
            $userEntries = $this->findLastEntries($game, $user, $limitScale);
1019
1020
            // player has reached the game limit
1021
            if ($userEntries >= $limitAmount) {
1022
                return true;
1023
            }
1024
        }
1025
        return false;
1026
    }
1027
    
1028
    /**
1029
     * @param \PlaygroundGame\Entity\Game $game
1030
     * @param \PlaygroundUser\Entity\UserInterface $user
1031
     */
1032
    public function findLastEntries($game, $user, $limitScale)
1033
    {
1034
        $limitDate = $this->getLimitDate($limitScale);
1035
1036
        if ($user) {
1037
            return $this->getEntryMapper()->findLastEntriesByUser($game, $user, $limitDate);
1038
        } elseif ($this->getAnonymousIdentifier()) {
1039
            return $this->getEntryMapper()->findLastEntriesByAnonymousIdentifier(
1040
                $game,
1041
                $this->getAnonymousIdentifier(),
1042
                $limitDate
1043
            );
1044
        } else {
1045
            return $this->getEntryMapper()->findLastEntriesByIp($game, $this->getIp(), $limitDate);
1046
        }
1047
    }
1048
1049
    /**
1050
    *
1051
    *
1052
    */
1053
    public function getLimitDate($limitScale)
1054
    {
1055
        $now = new \DateTime("now");
1056
        switch ($limitScale) {
1057
            case 'always':
1058
                $interval = 'P100Y';
1059
                $now->sub(new \DateInterval($interval));
1060
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
1061
                break;
1062
            case 'day':
1063
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
1064
                break;
1065
            case 'week':
1066
                $interval = 'P7D';
1067
                $now->sub(new \DateInterval($interval));
1068
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
1069
                break;
1070
            case 'month':
1071
                $interval = 'P1M';
1072
                $now->sub(new \DateInterval($interval));
1073
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
1074
                break;
1075
            case 'year':
1076
                $interval = 'P1Y';
1077
                $now->sub(new \DateInterval($interval));
1078
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
1079
                break;
1080
            default:
1081
                $interval = 'P100Y';
1082
                $now->sub(new \DateInterval($interval));
1083
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
1084
        }
1085
1086
        return $dateLimit;
1087
    }
1088
1089
    public function findLastActiveEntry($game, $user)
1090
    {
1091
        return $this->checkExistingEntry($game, $user, true);
1092
    }
1093
1094
    public function findLastInactiveEntry($game, $user)
1095
    {
1096
        return $this->checkExistingEntry($game, $user, false, false);
1097
    }
1098
1099
    public function findLastEntry($game, $user)
1100
    {
1101
        return $this->checkExistingEntry($game, $user, null, false);
1102
    }
1103
1104
    public function sendShareMail(
1105
        $data,
1106
        $game,
1107
        $user,
1108
        $entry,
1109
        $template = 'share_game',
1110
        $topic = null,
1111
        $userTimer = array()
1112
    ) {
1113
    
1114
        $mailService = $this->getServiceManager()->get('playgroundgame_message');
1115
        $mailSent = false;
1116
        $from = $this->getOptions()->getEmailFromAddress();
1117
        $subject = $this->getOptions()->getShareSubjectLine();
1118
        $renderer = $this->getServiceManager()->get('Zend\View\Renderer\RendererInterface');
1119
        if ($user) {
1120
            $email = $user->getEmail();
1121
        } elseif ($entry->getAnonymousIdentifier()) {
1122
            $email = $entry->getAnonymousIdentifier();
1123
        } else {
1124
            $email = $from;
1125
        }
1126
        $skinUrl = $renderer->url(
1127
            'frontend',
1128
            array(),
1129
            array('force_canonical' => true)
1130
        );
1131
        $secretKey = strtoupper(substr(sha1(uniqid('pg_', true) . '####' . time()), 0, 15));
1132
1133
        if (! $topic) {
1134
            $topic = $game->getTitle();
1135
        }
1136
1137
        $shares = json_decode($entry->getSocialShares(), true);
1138
        
1139
        if ($data['email1']) {
1140
            $mailSent = true;
1141
            $message = $mailService->createHtmlMessage(
1142
                $from,
1143
                $data['email1'],
1144
                $subject,
1145
                'playground-game/email/' . $template,
1146
                array(
1147
                    'game' => $game,
1148
                    'email' => $email,
1149
                    'secretKey' => $secretKey,
1150
                    'skinUrl' => $skinUrl,
1151
                    'userTimer' => $userTimer
1152
                )
1153
            );
1154
            $mailService->send($message);
1155
            
1156
            if (!isset($shares['mail'])) {
1157
                $shares['mail'] = 1;
1158
            } else {
1159
                $shares['mail'] += 1;
1160
            }
1161
        }
1162
        if ($data['email2'] && $data['email2'] != $data['email1']) {
1163
            $mailSent = true;
1164
            $message = $mailService->createHtmlMessage(
1165
                $from,
1166
                $data['email2'],
1167
                $subject,
1168
                'playground-game/email/' . $template,
1169
                array(
1170
                    'game' => $game,
1171
                    'email' => $email,
1172
                    'secretKey' => $secretKey,
1173
                    'skinUrl' => $skinUrl,
1174
                    'userTimer' => $userTimer
1175
                )
1176
            );
1177
            $mailService->send($message);
1178
            
1179
            if (!isset($shares['mail'])) {
1180
                $shares['mail'] = 1;
1181
            } else {
1182
                $shares['mail'] += 1;
1183
            }
1184
        }
1185
        if ($data['email3'] && $data['email3'] != $data['email2'] && $data['email3'] != $data['email1']) {
1186
            $mailSent = true;
1187
            $message = $mailService->createHtmlMessage(
1188
                $from,
1189
                $data['email3'],
1190
                $subject,
1191
                'playground-game/email/' . $template,
1192
                array(
1193
                    'game' => $game,
1194
                    'email' => $email,
1195
                    'secretKey' => $secretKey,
1196
                    'skinUrl' => $skinUrl,
1197
                    'userTimer' => $userTimer
1198
                )
1199
            );
1200
            $mailService->send($message);
1201
            
1202
            if (!isset($shares['mail'])) {
1203
                $shares['mail'] = 1;
1204
            } else {
1205
                $shares['mail'] += 1;
1206
            }
1207
        }
1208
        if ($data['email4'] &&
1209
            $data['email4'] != $data['email3'] &&
1210
            $data['email4'] != $data['email2'] &&
1211
            $data['email4'] != $data['email1']
1212
        ) {
1213
            $mailSent = true;
1214
            $message = $mailService->createHtmlMessage(
1215
                $from,
1216
                $data['email4'],
1217
                $subject,
1218
                'playground-game/email/' . $template,
1219
                array(
1220
                    'game' => $game,
1221
                    'email' => $email,
1222
                    'secretKey' => $secretKey,
1223
                    'skinUrl' => $skinUrl,
1224
                    'userTimer' => $userTimer
1225
                )
1226
            );
1227
            $mailService->send($message);
1228
        
1229
            if (!isset($shares['mail'])) {
1230
                $shares['mail'] = 1;
1231
            } else {
1232
                $shares['mail'] += 1;
1233
            }
1234
        }
1235
        if ($data['email5'] &&
1236
            $data['email5'] != $data['email4'] &&
1237
            $data['email5'] != $data['email3'] &&
1238
            $data['email5'] != $data['email2'] &&
1239
            $data['email5'] != $data['email1']
1240
        ) {
1241
            $mailSent = true;
1242
            $message = $mailService->createHtmlMessage(
1243
                $from,
1244
                $data['email5'],
1245
                $subject,
1246
                'playground-game/email/' . $template,
1247
                array(
1248
                    'game' => $game,
1249
                    'email' => $email,
1250
                    'secretKey' => $secretKey,
1251
                    'skinUrl' => $skinUrl,
1252
                    'userTimer' => $userTimer
1253
                )
1254
            );
1255
            $mailService->send($message);
1256
        
1257
            if (!isset($shares['mail'])) {
1258
                $shares['mail'] = 1;
1259
            } else {
1260
                $shares['mail'] += 1;
1261
            }
1262
        }
1263
        if ($mailSent) {
1264
            $sharesJson = json_encode($shares);
1265
            $entry->setSocialShares($sharesJson);
1266
            $entry = $this->getEntryMapper()->update($entry);
1267
            
1268
            $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1269
                'user' => $user,
1270
                'topic' => $topic,
1271
                'secretKey' => $secretKey,
1272
                'game' => $game,
1273
                'entry' => $entry
1274
            ));
1275
1276
            return true;
1277
        }
1278
1279
        return false;
1280
    }
1281
1282
    /**
1283
     * @param \PlaygroundGame\Entity\Game $game
1284
     * @param \PlaygroundUser\Entity\User $user
1285
     * @param Entry $entry
1286
     * @param \PlaygroundGame\Entity\Prize $prize
1287
     */
1288
    public function sendResultMail($game, $user, $entry, $template = 'entry', $prize = null)
1289
    {
1290
        $mailService = $this->getServiceManager()->get('playgroundgame_message');
1291
        $from = $this->getOptions()->getEmailFromAddress();
1292
        if ($user) {
1293
            $to = $user->getEmail();
1294
        } elseif ($entry->getAnonymousIdentifier()) {
1295
            $to = $entry->getAnonymousIdentifier();
1296
        } else {
1297
            return false;
1298
        }
1299
        $subject = $game->getTitle();
1300
        $renderer = $this->getServiceManager()->get('Zend\View\Renderer\RendererInterface');
1301
        $skinUrl = $renderer->url(
1302
            'frontend',
1303
            array(),
1304
            array('force_canonical' => true)
1305
        );
1306
        $message = $mailService->createHtmlMessage($from, $to, $subject, 'playground-game/email/' . $template, array(
1307
            'game' => $game,
1308
            'entry' => $entry,
1309
            'skinUrl' => $skinUrl,
1310
            'prize' => $prize
1311
        ));
1312
        $mailService->send($message);
1313
    }
1314
1315
    public function sendGameMail($game, $user, $post, $template = 'postvote')
1316
    {
1317
        $mailService = $this->getServiceManager()->get('playgroundgame_message');
1318
        $from = $this->getOptions()->getEmailFromAddress();
1319
        $to = $user->getEmail();
1320
        $subject = $this->getOptions()->getParticipationSubjectLine();
1321
        $renderer = $this->getServiceManager()->get('Zend\View\Renderer\RendererInterface');
1322
        $skinUrl = $renderer->url(
1323
            'frontend',
1324
            array(),
1325
            array('force_canonical' => true)
1326
        );
1327
1328
        $message = $mailService->createHtmlMessage($from, $to, $subject, 'playground-game/email/' . $template, array(
1329
            'game' => $game,
1330
            'post' => $post,
1331
            'skinUrl' => $skinUrl
1332
        ));
1333
        $mailService->send($message);
1334
    }
1335
1336 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...
1337
    {
1338
        $topic = $game->getTitle();
1339
        
1340
        $shares = json_decode($entry->getSocialShares(), true);
1341
        if (!isset($shares['fbwall'])) {
1342
            $shares['fbwall'] = 1;
1343
        } else {
1344
            $shares['fbwall'] += 1;
1345
        }
1346
        $sharesJson = json_encode($shares);
1347
        $entry->setSocialShares($sharesJson);
1348
        $entry = $this->getEntryMapper()->update($entry);
1349
        
1350
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1351
            'user' => $user,
1352
            'game' => $game,
1353
            'secretKey' => $secretKey,
1354
            'topic' => $topic,
1355
            'entry' => $entry
1356
        ));
1357
1358
        return true;
1359
    }
1360
1361
    public function postFbRequest($secretKey, $game, $user, $entry, $to)
1362
    {
1363
        $shares = json_decode($entry->getSocialShares(), true);
1364
        $to = explode(',', $to);
1365
        if (!isset($shares['fbrequest'])) {
1366
            $shares['fbrequest'] = count($to);
1367
        } else {
1368
            $shares['fbrequest'] += count($to);
1369
        }
1370
        $sharesJson = json_encode($shares);
1371
        $entry->setSocialShares($sharesJson);
1372
        $entry = $this->getEntryMapper()->update($entry);
1373
        
1374
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1375
            'user' => $user,
1376
            'game' => $game,
1377
            'secretKey' => $secretKey,
1378
            'entry' => $entry,
1379
            'invites' => count($to)
1380
        ));
1381
1382
        return true;
1383
    }
1384
1385 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...
1386
    {
1387
        $topic = $game->getTitle();
1388
1389
        $shares = json_decode($entry->getSocialShares(), true);
1390
        if (!isset($shares['fbrequest'])) {
1391
            $shares['tweet'] = 1;
1392
        } else {
1393
            $shares['tweet'] += 1;
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
            'topic' => $topic,
1404
            'entry' => $entry
1405
        ));
1406
1407
        return true;
1408
    }
1409
1410 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...
1411
    {
1412
        $topic = $game->getTitle();
1413
        
1414
        $shares = json_decode($entry->getSocialShares(), true);
1415
        if (!isset($shares['fbrequest'])) {
1416
            $shares['google'] = 1;
1417
        } else {
1418
            $shares['google'] += 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
    /**
1436
     * Is it possible to trigger a bonus entry ?
1437
     *
1438
     * @param unknown_type $game
1439
     * @param unknown_type $user
1440
     */
1441
    public function allowBonus($game, $user)
1442
    {
1443
        if (! $game->getPlayBonus() || $game->getPlayBonus() == 'none') {
1444
            return false;
1445
        } elseif ($game->getPlayBonus() == 'one') {
1446
            if ($this->getEntryMapper()->findOneBy(array(
1447
                'game' => $game,
1448
                'user' => $user,
1449
                'bonus' => 1
1450
            ))) {
1451
                return false;
1452
            } else {
1453
                return true;
1454
            }
1455
        } elseif ($game->getPlayBonus() == 'per_entry') {
1456
            return $this->getEntryMapper()->checkBonusEntry($game, $user);
1457
        }
1458
1459
        return false;
1460
    }
1461
1462
    public function addAnotherEntry($game, $user, $winner = 0)
1463
    {
1464
        $entry = new Entry();
1465
        $entry->setGame($game);
1466
        $entry->setUser($user);
1467
        $entry->setPoints(0);
1468
        $entry->setIp($this->getIp());
1469
        $entry->setActive(0);
1470
        $entry->setBonus(1);
1471
        $entry->setWinner($winner);
1472
        $entry = $this->getEntryMapper()->insert($entry);
1473
1474
        return $entry;
1475
    }
1476
1477
    /**
1478
     * This bonus entry doesn't give points nor badges
1479
     * It's just there to increase the chances during the Draw
1480
     * Old Name playBonus
1481
     *
1482
     * @param PlaygroundGame\Entity\Game $game
1483
     * @param unknown $user
1484
     * @return boolean unknown
1485
     */
1486
    public function addAnotherChance($game, $user, $winner = 0)
1487
    {
1488
        if ($this->allowBonus($game, $user)) {
1489
            $this->addAnotherEntry($game, $user, $winner);
1490
1491
            return true;
1492
        }
1493
1494
        return false;
1495
    }
1496
1497
    /**
1498
     * This bonus entry doesn't give points nor badges but can play again
1499
     *
1500
     * @param PlaygroundGame\Entity\Game $game
1501
     * @param user $user
1502
     * @return boolean unknown
1503
     */
1504
    public function playAgain($game, $user, $winner = 0)
1505
    {
1506
        if ($this->allowBonus($game, $user)) {
1507
            $entry = $this->addAnotherEntry($game, $user, $winner);
1508
            $entry->setActive(1);
1509
            $entry = $this->getEntryMapper()->update($entry);
1510
            if ($entry->getActive() == 1) {
1511
                return true;
1512
            }
1513
        }
1514
1515
        return false;
1516
    }
1517
1518 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...
1519
    {
1520
        $configuration = require 'config/application.config.php';
1521
        $smConfig = isset($configuration['service_manager']) ? $configuration['service_manager'] : array();
1522
        $sm = new \Zend\ServiceManager\ServiceManager(new \Zend\Mvc\Service\ServiceManagerConfig($smConfig));
1523
        $sm->setService('ApplicationConfig', $configuration);
1524
        $sm->get('ModuleManager')->loadModules();
1525
        $sm->get('Application')->bootstrap();
1526
1527
        $mailService = $sm->get('playgrounduser_message');
1528
        $gameService = $sm->get('playgroundgame_quiz_service');
1529
1530
        $from = "[email protected]";
1531
        $subject = "sujet game";
1532
1533
        $to = "[email protected]";
1534
1535
        $game = $gameService->checkGame('qooqo');
1536
1537
        $message = $mailService->createTextMessage($from, $to, $subject, 'playground-game/email/share_reminder', array(
1538
            'game' => $game
1539
        ));
1540
1541
        $mailService->send($message);
1542
    }
1543
1544
    /**
1545
     * @param string $path
1546
     */
1547
    public function uploadFile($path, $file)
1548
    {
1549
        $err = $file["error"];
1550
        $message = '';
1551
        if ($err > 0) {
1552
            switch ($err) {
1553
                case '1':
1554
                    $message .= 'Max file size exceeded. (php.ini)';
1555
                    break;
1556
                case '2':
1557
                    $message .= 'Max file size exceeded.';
1558
                    break;
1559
                case '3':
1560
                    $message .= 'File upload was only partial.';
1561
                    break;
1562
                case '4':
1563
                    $message .= 'No file was attached.';
1564
                    break;
1565
                case '7':
1566
                    $message .= 'File permission denied.';
1567
                    break;
1568
                default:
1569
                    $message .= 'Unexpected error occurs.';
1570
            }
1571
1572
            return $err;
1573
        } else {
1574
            $fileNewname = $this->fileNewname($path, $file['name'], true);
1575
1576
            if (isset($file["base64"])) {
1577
                list(, $img) = explode(',', $file["base64"]);
1578
                $img = str_replace(' ', '+', $img);
1579
                $im = base64_decode($img);
1580
                if ($im !== false) {
1581
                    // getimagesizefromstring
1582
                    file_put_contents($path . $fileNewname, $im);
1583
                } else {
1584
                    return 1;
1585
                }
1586
1587
                return $fileNewname;
1588
            } else {
1589
                $adapter = new \Zend\File\Transfer\Adapter\Http();
1590
                // 1Mo
1591
                $size = new Size(array(
1592
                    'max' => 1024000
1593
                ));
1594
                $is_image = new IsImage('jpeg,png,gif,jpg');
1595
                $adapter->setValidators(array(
1596
                    $size,
1597
                    $is_image
1598
                ), $fileNewname);
1599
1600
                if (! $adapter->isValid()) {
1601
                    return false;
1602
                }
1603
1604
                @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...
1605
            }
1606
1607
            
1608
            if (class_exists("Imagick")) {
1609
                $ext = pathinfo($fileNewname, PATHINFO_EXTENSION);
1610
                $img = new \Imagick($path . $fileNewname);
1611
                $img->cropThumbnailImage(100, 100);
1612
                $img->setImageCompression(\Imagick::COMPRESSION_JPEG);
1613
                $img->setImageCompressionQuality(75);
1614
                // Strip out unneeded meta data
1615
                $img->stripImage();
1616
                $img->writeImage($path . str_replace('.'.$ext, '-thumbnail.'.$ext, $fileNewname));
1617
                ErrorHandler::stop(true);
1618
            }
1619
        }
1620
1621
        return $fileNewname;
1622
    }
1623
1624
    /**
1625
     * @param string $path
1626
     */
1627
    public function fileNewname($path, $filename, $generate = false)
1628
    {
1629
        $sanitize = new Sanitize();
1630
        $name = $sanitize->filter($filename);
1631
        $newpath = $path . $name;
1632
1633
        if ($generate) {
1634
            if (file_exists($newpath)) {
1635
                $filename = pathinfo($name, PATHINFO_FILENAME);
1636
                $ext = pathinfo($name, PATHINFO_EXTENSION);
1637
1638
                $name = $filename . '_' . rand(0, 99) . '.' . $ext;
1639
            }
1640
        }
1641
1642
        unset($sanitize);
1643
1644
        return $name;
1645
    }
1646
1647
    /**
1648
     * This function returns the list of games, order by $type
1649
     */
1650
    public function getQueryGamesOrderBy($type = 'createdAt', $order = 'DESC')
1651
    {
1652
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
1653
        $today = new \DateTime("now");
1654
        $today = $today->format('Y-m-d') . ' 23:59:59';
1655
1656
        $onlineGames = '(
1657
            (
1658
                CASE WHEN (
1659
                    g.active = 1
1660
                    AND g.broadcastPlatform = 1
1661
                    AND (g.startDate <= :date OR g.startDate IS NULL)
1662
                    AND (g.closeDate >= :date OR g.closeDate IS NULL)
1663
                ) THEN 1 ELSE 0 END
1664
            ) +
1665
            (
1666
                CASE WHEN (
1667
                    g.active = 0
1668
                    AND (g.broadcastPlatform = 0 OR g.broadcastPlatform IS NULL)
1669
                    AND g.startDate > :date
1670
                    AND g.closeDate < :date
1671
                ) THEN 1 ELSE 0 END
1672
            )
1673
        )';
1674
1675
        $qb = $em->createQueryBuilder();
1676
        $qb->select('g')->from('PlaygroundGame\Entity\Game', 'g');
1677
        
1678
        switch ($type) {
1679
            case 'startDate':
1680
                $qb->orderBy('g.startDate', $order);
1681
                break;
1682
            case 'activeGames':
1683
                $qb->orderBy('g.active', $order);
1684
                break;
1685
            case 'onlineGames':
1686
                $qb->orderBy($onlineGames, $order);
1687
                $qb->setParameter('date', $today);
1688
                break;
1689
            case 'createdAt':
1690
                $qb->orderBy('g.createdAt', $order);
1691
                break;
1692
        }
1693
1694
        $query = $qb->getQuery();
1695
1696
        return $query;
1697
    }
1698
1699
    public function draw($game)
1700
    {
1701
        $total = $game->getWinners();
1702
1703
        // I Have to know what is the User Class used
1704
        $zfcUserOptions = $this->getServiceManager()->get('zfcuser_module_options');
1705
        $userClass = $zfcUserOptions->getUserEntityClass();
1706
1707
        $result = $this->getEntryMapper()->draw($game, $userClass, $total);
1708
1709
        foreach ($result as $e) {
1710
            $e->setWinner(1);
1711
            $e = $this->getEntryMapper()->update($e);
1712
            $this->getEventManager()->trigger('win_lottery.post', $this, array(
1713
                'user' => $e->getUser(),
1714
                'game' => $game,
1715
                'entry' => $e
1716
            ));
1717
        }
1718
1719
        return $result;
1720
    }
1721
1722
    /**
1723
     * getGameMapper
1724
     *
1725
     * @return GameMapperInterface
1726
     */
1727 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...
1728
    {
1729
        if (null === $this->gameMapper) {
1730
            $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...
1731
        }
1732
1733
        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 1733 which is incompatible with the return type documented by PlaygroundGame\Service\Game::getGameMapper of type PlaygroundGame\Mapper\GameInterface.
Loading history...
1734
    }
1735
1736
    /**
1737
     * setGameMapper
1738
     *
1739
     * @param GameMapperInterface $gameMapper
1740
     * @return Game
1741
     */
1742
    public function setGameMapper(GameMapperInterface $gameMapper)
1743
    {
1744
        $this->gameMapper = $gameMapper;
1745
1746
        return $this;
1747
    }
1748
1749
    /**
1750
     * getEntryMapper
1751
     *
1752
     * @return EntryMapperInterface
1753
     */
1754 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...
1755
    {
1756
        if (null === $this->entryMapper) {
1757
            $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...
1758
        }
1759
1760
        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 1760 which is incompatible with the return type documented by PlaygroundGame\Service\Game::getEntryMapper of type PlaygroundGame\Service\EntryMapperInterface.
Loading history...
1761
    }
1762
1763
    /**
1764
     * setEntryMapper
1765
     *
1766
     * @param EntryMapperInterface $entryMapper
1767
     * @return Game
1768
     */
1769
    public function setEntryMapper($entryMapper)
1770
    {
1771
        $this->entryMapper = $entryMapper;
1772
1773
        return $this;
1774
    }
1775
1776
    public function setOptions(ModuleOptions $options)
1777
    {
1778
        $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...
1779
1780
        return $this;
1781
    }
1782
1783
    public function getOptions()
1784
    {
1785
        if (! $this->options instanceof ModuleOptions) {
1786
            $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...
1787
                ->get('playgroundgame_module_options'));
1788
        }
1789
1790
        return $this->options;
1791
    }
1792
1793
    /**
1794
     * Retrieve service manager instance
1795
     *
1796
     * @return ServiceManager
1797
     */
1798
    public function getServiceManager()
1799
    {
1800
        return $this->serviceManager;
1801
    }
1802
1803
    /**
1804
     * Set service manager instance
1805
     *
1806
     * @param ServiceManager $serviceManager
1807
     * @return Game
1808
     */
1809
    public function setServiceManager(ServiceManager $serviceManager)
1810
    {
1811
        $this->serviceManager = $serviceManager;
1812
1813
        return $this;
1814
    }
1815
1816
    /**
1817
     * @param string $str
1818
     */
1819
    public function getExtension($str)
1820
    {
1821
        $i = strrpos($str, '.');
1822
1823
        $l = strlen($str) - $i;
1824
        $ext = substr($str, $i + 1, $l);
1825
1826
        return $ext;
1827
    }
1828
1829
    /**
1830
     * @param string $extension
1831
     */
1832
    public function getSrc($extension, $temp_path)
1833
    {
1834
        $image_src = '';
1835
        switch ($extension) {
1836
            case 'jpg':
1837
                $image_src = imagecreatefromjpeg($temp_path);
1838
                break;
1839
            case 'jpeg':
1840
                $image_src = imagecreatefromjpeg($temp_path);
1841
                break;
1842
            case 'png':
1843
                $image_src = imagecreatefrompng($temp_path);
1844
                break;
1845
            case 'gif':
1846
                $image_src = imagecreatefromgif($temp_path);
1847
                break;
1848
        }
1849
1850
        return $image_src;
1851
    }
1852
1853
    /**
1854
     * @param string $extension
1855
     * @param string $rep
1856
     * @param integer $mini_width
1857
     * @param integer $mini_height
1858
     */
1859
    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...
1860
    {
1861
        list($src_width, $src_height) = getimagesize($tmp_file);
1862
1863
        $ratio_src = $src_width / $src_height;
1864
        $ratio_mini = $mini_width / $mini_height;
1865
1866
        if ($ratio_src >= $ratio_mini) {
1867
            $new_height_mini = $mini_height;
1868
            $new_width_mini = $src_width / ($src_height / $mini_height);
1869
        } else {
1870
            $new_width_mini = $mini_width;
1871
            $new_height_mini = $src_height / ($src_width / $mini_width);
1872
        }
1873
1874
        $new_image_mini = imagecreatetruecolor($mini_width, $mini_height);
1875
1876
        imagecopyresampled(
1877
            $new_image_mini,
1878
            $src,
1879
            0 - ($new_width_mini - $mini_width) / 2,
1880
            0 - ($new_height_mini - $mini_height) / 2,
1881
            0,
1882
            0,
1883
            $new_width_mini,
1884
            $new_height_mini,
1885
            $src_width,
1886
            $src_height
1887
        );
1888
        imagejpeg($new_image_mini, $rep);
1889
1890
        imagedestroy($new_image_mini);
1891
    }
1892
1893
    public function getGameEntity()
1894
    {
1895
        return new \PlaygroundGame\Entity\Game();
1896
    }
1897
1898
    /**
1899
     * @param string $resource
1900
     * @param string $privilege
1901
     */
1902
    public function isAllowed($resource, $privilege = null)
1903
    {
1904
        $auth = $this->getServiceManager()->get('BjyAuthorize\Service\Authorize');
1905
1906
        return $auth->isAllowed($resource, $privilege);
1907
    }
1908
1909
    public function getIp()
1910
    {
1911
        $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...
1912
        if (isset($_SERVER['HTTP_CLIENT_IP'])) {
1913
            $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
1914
        } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1915
            $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
1916
        } elseif (isset($_SERVER['HTTP_X_FORWARDED'])) {
1917
            $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
1918
        } elseif (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
1919
            $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
1920
        } elseif (isset($_SERVER['HTTP_FORWARDED'])) {
1921
            $ipaddress = $_SERVER['HTTP_FORWARDED'];
1922
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
1923
            $ipaddress = $_SERVER['REMOTE_ADDR'];
1924
        } else {
1925
            $ipaddress = 'UNKNOWN';
1926
        }
1927
1928
        return $ipaddress;
1929
    }
1930
1931
    public function getAnonymousId()
1932
    {
1933
        $anonymousId = '';
1934
        if ($_COOKIE && array_key_exists('pg_anonymous', $_COOKIE)) {
1935
            $anonymousId = $_COOKIE['pg_anonymous'];
1936
        }
1937
1938
        return $anonymousId;
1939
    }
1940
1941
    /**
1942
     *
1943
     *
1944
     * This service is ready for all types of games
1945
     *
1946
     * @param array $data
1947
     * @return \PlaygroundGame\Entity\Game
1948
     */
1949 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...
1950
    {
1951
        $title = '';
1952
        $description = '';
1953
1954
        if ($data['form_jsonified']) {
1955
            $jsonPV = json_decode($data['form_jsonified']);
1956
            foreach ($jsonPV as $element) {
1957
                if ($element->form_properties) {
1958
                    $attributes = $element->form_properties[0];
1959
                    $title = $attributes->title;
1960
                    $description = $attributes->description;
1961
1962
                    break;
1963
                }
1964
            }
1965
        }
1966
        if (! $form) {
1967
            $form = new \PlaygroundGame\Entity\PlayerForm();
1968
        }
1969
        $form->setGame($game);
1970
        $form->setTitle($title);
1971
        $form->setDescription($description);
1972
        $form->setForm($data['form_jsonified']);
1973
        $form->setFormTemplate($data['form_template']);
1974
1975
        $form = $this->getPlayerFormMapper()->insert($form);
1976
1977
        return $form;
1978
    }
1979
1980
    /**
1981
     *  getCSV creates lines of CSV and returns it.
1982
     */
1983
    public function getCSV($array)
1984
    {
1985
        ob_start(); // buffer the output ...
1986
        $out = fopen('php://output', 'w');
1987
        fputcsv($out, array_keys($array[0]), ";");
1988
        foreach ($array as $line) {
1989
            fputcsv($out, $line, ";");
1990
        }
1991
        fclose($out);
1992
        return ob_get_clean(); // ... then return it as a string!
1993
    }
1994
    
1995
    /**
1996
     * Create a ZF2 Form from json data
1997
     * @return Form
1998
     */
1999
    public function createFormFromJson($jsonForm, $id = 'jsonForm')
2000
    {
2001
        $formPV = json_decode($jsonForm);
2002
        
2003
        $form = new Form();
2004
        $form->setAttribute('id', $id);
2005
        $form->setAttribute('enctype', 'multipart/form-data');
2006
        
2007
        $inputFilter = new \Zend\InputFilter\InputFilter();
2008
        $factory = new InputFactory();
2009
        
2010
        foreach ($formPV as $element) {
2011
            if (isset($element->line_text)) {
2012
                $attributes  = $element->line_text[0];
2013
                $name        = isset($attributes->name)? $attributes->name : '';
2014
                $placeholder = isset($attributes->data->placeholder)? $attributes->data->placeholder : '';
2015
                $label       = isset($attributes->data->label)? $attributes->data->label : '';
2016
                $required    = ($attributes->data->required == 'true') ? true : false ;
2017
                $class       = isset($attributes->data->class)? $attributes->data->class : '';
2018
                $id          = isset($attributes->data->id)? $attributes->data->id : '';
2019
                $lengthMin   = isset($attributes->data->length)? $attributes->data->length->min : '';
2020
                $lengthMax   = isset($attributes->data->length)? $attributes->data->length->max : '';
2021
                $validator   = isset($attributes->data->validator)? $attributes->data->validator : '';
2022
        
2023
                $element = new Element\Text($name);
2024
                $element->setLabel($label);
2025
                $element->setAttributes(
2026
                    array(
2027
                        'placeholder'    => $placeholder,
2028
                        'required'        => $required,
2029
                        'class'        => $class,
2030
                        'id'            => $id
2031
                    )
2032
                );
2033
                $form->add($element);
2034
        
2035
                $options = array();
2036
                $options['encoding'] = 'UTF-8';
2037
                if ($lengthMin && $lengthMin > 0) {
2038
                    $options['min'] = $lengthMin;
2039
                }
2040 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...
2041
                    $options['max'] = $lengthMax;
2042
                    $element->setAttribute('maxlength', $lengthMax);
2043
                    $options['messages'] = array(
2044
                        \Zend\Validator\StringLength::TOO_LONG => sprintf(
2045
                            $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...
2046
                                'This field contains more than %s characters',
2047
                                'playgroundgame'
2048
                            ),
2049
                            $lengthMax
2050
                        )
2051
                    );
2052
                }
2053
2054
                $validators = array(
2055
                    array(
2056
                        'name'    => 'StringLength',
2057
                        'options' => $options,
2058
                    ),
2059
                );
2060
                if ($validator) {
2061
                    $regex = "/.*\(([^)]*)\)/";
2062
                    preg_match($regex, $validator, $matches);
2063
                    $valArray = array(
2064
                        'name' => str_replace(
2065
                            '('.$matches[1].')',
2066
                            '',
2067
                            $validator
2068
                        ),
2069
                        'options' => array($matches[1])
2070
                    );
2071
                    $validators[] = $valArray;
2072
                }
2073
2074
                $inputFilter->add($factory->createInput(array(
2075
                    'name'     => $name,
2076
                    'required' => $required,
2077
                    'filters'  => array(
2078
                        array('name' => 'StripTags'),
2079
                        array('name' => 'StringTrim'),
2080
                    ),
2081
                    'validators' => $validators,
2082
                )));
2083
            }
2084
            if (isset($element->line_password)) {
2085
                $attributes  = $element->line_password[0];
2086
                $name        = isset($attributes->name)? $attributes->name : '';
2087
                $placeholder = isset($attributes->data->placeholder)? $attributes->data->placeholder : '';
2088
                $label       = isset($attributes->data->label)? $attributes->data->label : '';
2089
                $required    = (
2090
                    isset($attributes->data->required) &&
2091
                    $attributes->data->required == 'true'
2092
                ) ? true : false ;
2093
                $class       = isset($attributes->data->class)? $attributes->data->class : '';
2094
                $id          = isset($attributes->data->id)? $attributes->data->id : '';
2095
                $lengthMin   = isset($attributes->data->length)? $attributes->data->length->min : '';
2096
                $lengthMax   = isset($attributes->data->length)? $attributes->data->length->max : '';
2097
        
2098
                $element = new Element\Password($name);
2099
                $element->setLabel($label);
2100
                $element->setAttributes(
2101
                    array(
2102
                        'placeholder'   => $placeholder,
2103
                        'required'      => $required,
2104
                        'class'         => $class,
2105
                        'id'            => $id
2106
                    )
2107
                );
2108
                $form->add($element);
2109
        
2110
                $options = array();
2111
                $options['encoding'] = 'UTF-8';
2112
                if ($lengthMin && $lengthMin > 0) {
2113
                    $options['min'] = $lengthMin;
2114
                }
2115 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...
2116
                    $options['max'] = $lengthMax;
2117
                    $element->setAttribute('maxlength', $lengthMax);
2118
                    $options['messages'] = array(
2119
                        \Zend\Validator\StringLength::TOO_LONG => sprintf(
2120
                            $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...
2121
                                'This field contains more than %s characters',
2122
                                'playgroundgame'
2123
                            ),
2124
                            $lengthMax
2125
                        )
2126
                    );
2127
                }
2128
                $inputFilter->add($factory->createInput(array(
2129
                    'name'     => $name,
2130
                    'required' => $required,
2131
                    'filters'  => array(
2132
                        array('name' => 'StripTags'),
2133
                        array('name' => 'StringTrim'),
2134
                    ),
2135
                    'validators' => array(
2136
                        array(
2137
                            'name'    => 'StringLength',
2138
                            'options' => $options,
2139
                        ),
2140
                    ),
2141
                )));
2142
            }
2143
            if (isset($element->line_hidden)) {
2144
                $attributes  = $element->line_hidden[0];
2145
                $name        = isset($attributes->name)? $attributes->name : '';
2146
                $label       = isset($attributes->data->label)? $attributes->data->label : '';
2147
                $required    = ($attributes->data->required == 'true') ? true : false ;
2148
                $class       = isset($attributes->data->class)? $attributes->data->class : '';
2149
                $id          = isset($attributes->data->id)? $attributes->data->id : '';
2150
                $lengthMin   = isset($attributes->data->length)? $attributes->data->length->min : '';
2151
                $lengthMax   = isset($attributes->data->length)? $attributes->data->length->max : '';
2152
        
2153
                $element = new Element\Hidden($name);
2154
                $element->setLabel($label);
2155
                $element->setAttributes(
2156
                    array(
2157
                        'required'      => $required,
2158
                        'class'         => $class,
2159
                        'id'            => $id
2160
                    )
2161
                );
2162
                $form->add($element);
2163
        
2164
                $options = array();
2165
                $options['encoding'] = 'UTF-8';
2166
                if ($lengthMin && $lengthMin > 0) {
2167
                    $options['min'] = $lengthMin;
2168
                }
2169 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...
2170
                    $options['max'] = $lengthMax;
2171
                    $element->setAttribute('maxlength', $lengthMax);
2172
                    $options['messages'] = array(
2173
                        \Zend\Validator\StringLength::TOO_LONG => sprintf(
2174
                            $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...
2175
                                'This field contains more than %s characters',
2176
                                'playgroundgame'
2177
                            ),
2178
                            $lengthMax
2179
                        )
2180
                    );
2181
                }
2182
                $inputFilter->add($factory->createInput(array(
2183
                    'name'     => $name,
2184
                    'required' => $required,
2185
                    'filters'  => array(
2186
                        array('name' => 'StripTags'),
2187
                        array('name' => 'StringTrim'),
2188
                    ),
2189
                    'validators' => array(
2190
                        array(
2191
                            'name'    => 'StringLength',
2192
                            'options' => $options,
2193
                        ),
2194
                    ),
2195
                )));
2196
            }
2197
            if (isset($element->line_email)) {
2198
                $attributes  = $element->line_email[0];
2199
                $name        = isset($attributes->name)? $attributes->name : '';
2200
                $placeholder = isset($attributes->data->placeholder)? $attributes->data->placeholder : '';
2201
                $label       = isset($attributes->data->label)? $attributes->data->label : '';
2202
                $class       = isset($attributes->data->class)? $attributes->data->class : '';
2203
                $id          = isset($attributes->data->id)? $attributes->data->id : '';
2204
                $lengthMin   = isset($attributes->data->length)? $attributes->data->length->min : '';
2205
                $lengthMax   = isset($attributes->data->length)? $attributes->data->length->max : '';
2206
        
2207
                $element = new Element\Email($name);
2208
                $element->setLabel($label);
2209
                $element->setAttributes(
2210
                    array(
2211
                        'placeholder'    => $placeholder,
2212
                        '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...
2213
                        'class'        => $class,
2214
                        'id'            => $id
2215
                    )
2216
                );
2217
                $form->add($element);
2218
        
2219
                $options = array();
2220
                $options['encoding'] = 'UTF-8';
2221
                if ($lengthMin && $lengthMin > 0) {
2222
                    $options['min'] = $lengthMin;
2223
                }
2224 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...
2225
                    $options['max'] = $lengthMax;
2226
                    $element->setAttribute('maxlength', $lengthMax);
2227
                    $options['messages'] = array(
2228
                        \Zend\Validator\StringLength::TOO_LONG => sprintf(
2229
                            $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...
2230
                                'This field contains more than %s characters',
2231
                                'playgroundgame'
2232
                            ),
2233
                            $lengthMax
2234
                        )
2235
                    );
2236
                }
2237
                $inputFilter->add($factory->createInput(array(
2238
                    'name'     => $name,
2239
                    'required' => $required,
2240
                    'filters'  => array(
2241
                        array('name' => 'StripTags'),
2242
                        array('name' => 'StringTrim'),
2243
                    ),
2244
                    'validators' => array(
2245
                        array(
2246
                            'name'    => 'StringLength',
2247
                            'options' => $options,
2248
                        ),
2249
                    ),
2250
                )));
2251
            }
2252 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...
2253
                $attributes  = $element->line_radio[0];
2254
                $name        = isset($attributes->name)? $attributes->name : '';
2255
                $label       = isset($attributes->data->label)? $attributes->data->label : '';
2256
        
2257
                $required = false;
2258
                $class       = isset($attributes->data->class)? $attributes->data->class : '';
2259
                $id          = isset($attributes->data->id)? $attributes->data->id : '';
2260
                $lengthMin   = isset($attributes->data->length)? $attributes->data->length->min : '';
2261
                $lengthMax   = isset($attributes->data->length)? $attributes->data->length->max : '';
2262
                $innerData   = isset($attributes->data->innerData)? $attributes->data->innerData : array();
2263
        
2264
                $element = new Element\Radio($name);
2265
                $element->setLabel($label);
2266
                $element->setAttributes(
2267
                    array(
2268
                        'name'          => $name,
2269
                        'required'        => $required,
2270
                        'allowEmpty'    => !$required,
2271
                        'class'        => $class,
2272
                        'id'            => $id
2273
                    )
2274
                );
2275
                $values = array();
2276
                foreach ($innerData as $value) {
2277
                    $values[] = $value->label;
2278
                }
2279
                $element->setValueOptions($values);
2280
        
2281
                $options = array();
2282
                $options['encoding'] = 'UTF-8';
2283
                $options['disable_inarray_validator'] = true;
2284
        
2285
                $element->setOptions($options);
2286
        
2287
                $form->add($element);
2288
        
2289
                $inputFilter->add($factory->createInput(array(
2290
                    'name'     => $name,
2291
                    'required' => $required,
2292
                    'allowEmpty' => !$required,
2293
                )));
2294
            }
2295 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...
2296
                $attributes  = $element->line_checkbox[0];
2297
                $name        = isset($attributes->name)? $attributes->name : '';
2298
                $label       = isset($attributes->data->label)? $attributes->data->label : '';
2299
        
2300
                $required = false;
2301
                $class       = isset($attributes->data->class)? $attributes->data->class : '';
2302
                $id          = isset($attributes->data->id)? $attributes->data->id : '';
2303
                $lengthMin   = isset($attributes->data->length)? $attributes->data->length->min : '';
2304
                $lengthMax   = isset($attributes->data->length)? $attributes->data->length->max : '';
2305
                $innerData   = isset($attributes->data->innerData)? $attributes->data->innerData : array();
2306
        
2307
                $element = new Element\MultiCheckbox($name);
2308
                $element->setLabel($label);
2309
                $element->setAttributes(
2310
                    array(
2311
                        'name'     => $name,
2312
                        'required'        => $required,
2313
                        'allowEmpty'    => !$required,
2314
                        'class'        => $class,
2315
                        'id'            => $id
2316
                    )
2317
                );
2318
                $values = array();
2319
                foreach ($innerData as $value) {
2320
                    $values[] = $value->label;
2321
                }
2322
                $element->setValueOptions($values);
2323
                $form->add($element);
2324
        
2325
                $options = array();
2326
                $options['encoding'] = 'UTF-8';
2327
                $options['disable_inarray_validator'] = true;
2328
        
2329
                $element->setOptions($options);
2330
        
2331
                $inputFilter->add($factory->createInput(array(
2332
                    'name'     => $name,
2333
                    'required' => $required,
2334
                    'allowEmpty' => !$required,
2335
                )));
2336
            }
2337 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...
2338
                $attributes  = $element->line_dropdown[0];
2339
                $name        = isset($attributes->name)? $attributes->name : '';
2340
                $label       = isset($attributes->data->label)? $attributes->data->label : '';
2341
        
2342
                $required = false;
2343
                $class       = isset($attributes->data->class)? $attributes->data->class : '';
2344
                $id          = isset($attributes->data->id)? $attributes->data->id : '';
2345
                $lengthMin   = isset($attributes->data->length)? $attributes->data->length->min : '';
2346
                $lengthMax   = isset($attributes->data->length)? $attributes->data->length->max : '';
2347
                $dropdownValues   = isset($attributes->data->dropdownValues)?
2348
                    $attributes->data->dropdownValues :
2349
                    array();
2350
        
2351
                $element = new Element\Select($name);
2352
                $element->setLabel($label);
2353
                $element->setAttributes(
2354
                    array(
2355
                        'name'     => $name,
2356
                        'required'      => $required,
2357
                        'allowEmpty'    => !$required,
2358
                        'class'         => $class,
2359
                        'id'            => $id
2360
                    )
2361
                );
2362
                $values = array();
2363
                foreach ($dropdownValues as $value) {
2364
                    $values[] = $value->dropdown_label;
2365
                }
2366
                $element->setValueOptions($values);
2367
                $form->add($element);
2368
        
2369
                $options = array();
2370
                $options['encoding'] = 'UTF-8';
2371
                $options['disable_inarray_validator'] = true;
2372
        
2373
                $element->setOptions($options);
2374
        
2375
                $inputFilter->add($factory->createInput(array(
2376
                    'name'     => $name,
2377
                    'required' => $required,
2378
                    'allowEmpty' => !$required,
2379
                )));
2380
            }
2381
            if (isset($element->line_paragraph)) {
2382
                $attributes  = $element->line_paragraph[0];
2383
                $name        = isset($attributes->name)? $attributes->name : '';
2384
                $placeholder = isset($attributes->data->placeholder)? $attributes->data->placeholder : '';
2385
                $label       = isset($attributes->data->label)? $attributes->data->label : '';
2386
                $required    = ($attributes->data->required == 'true') ? true : false ;
2387
                $class       = isset($attributes->data->class)? $attributes->data->class : '';
2388
                $id          = isset($attributes->data->id)? $attributes->data->id : '';
2389
        
2390
                $element = new Element\Textarea($name);
2391
                $element->setLabel($label);
2392
                $element->setAttributes(
2393
                    array(
2394
                        'placeholder'    => $placeholder,
2395
                        'required'        => $required,
2396
                        'class'        => $class,
2397
                        'id'            => $id
2398
                    )
2399
                );
2400
                $form->add($element);
2401
        
2402
                $options = array();
2403
                $options['encoding'] = 'UTF-8';
2404
                if ($lengthMin && $lengthMin > 0) {
2405
                    $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...
2406
                }
2407
                if ($lengthMax && $lengthMax > $lengthMin) {
2408
                    $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...
2409
                    $element->setAttribute('maxlength', $lengthMax);
2410
                }
2411
                $inputFilter->add($factory->createInput(array(
2412
                    'name'     => $name,
2413
                    'required' => $required,
2414
                    'filters'  => array(
2415
                        array('name' => 'StripTags'),
2416
                        array('name' => 'StringTrim'),
2417
                    ),
2418
                    'validators' => array(
2419
                        array(
2420
                            'name'    => 'StringLength',
2421
                            'options' => $options,
2422
                        ),
2423
                    ),
2424
                )));
2425
            }
2426
            if (isset($element->line_upload)) {
2427
                $attributes  = $element->line_upload[0];
2428
                $name        = isset($attributes->name)? $attributes->name : '';
2429
                $label       = isset($attributes->data->label)? $attributes->data->label : '';
2430
                $required    = ($attributes->data->required == 'true') ? true : false ;
2431
                $class       = isset($attributes->data->class)? $attributes->data->class : '';
2432
                $id          = isset($attributes->data->id)? $attributes->data->id : '';
2433
                $filesizeMin = isset($attributes->data->filesize)? $attributes->data->filesize->min : 0;
2434
                $filesizeMax = isset($attributes->data->filesize)? $attributes->data->filesize->max : 10*1024*1024;
2435
                $element = new Element\File($name);
2436
                $element->setLabel($label);
2437
                $element->setAttributes(
2438
                    array(
2439
                        'required'    => $required,
2440
                        'class'    => $class,
2441
                        'id'        => $id
2442
                    )
2443
                );
2444
                $form->add($element);
2445
        
2446
                $inputFilter->add($factory->createInput(array(
2447
                    'name'     => $name,
2448
                    'required' => $required,
2449
                    'validators' => array(
2450
                        array(
2451
                            'name' => '\Zend\Validator\File\Size',
2452
                            'options' => array('min' => $filesizeMin, 'max' => $filesizeMax)
2453
                        ),
2454
                        array(
2455
                            'name' => '\Zend\Validator\File\Extension',
2456
                            'options'  => array(
2457
                                'png,PNG,jpg,JPG,jpeg,JPEG,gif,GIF',
2458
                                'messages' => array(
2459
                                    \Zend\Validator\File\Extension::FALSE_EXTENSION =>'Veuillez télécharger une image'
2460
                                )
2461
                            )
2462
                        ),
2463
                    ),
2464
                )));
2465
            }
2466
        }
2467
        
2468
        $form->setInputFilter($inputFilter);
2469
        
2470
        return $form;
2471
    }
2472
2473
    /**
2474
     * Send mail for winner and/or loser
2475
     * @param \PlaygroundGame\Entity\Game $game
2476
     * @param \PlaygroundUser\Entity\User $user
2477
     * @param \PlaygroundGame\Entity\Entry $lastEntry
2478
     * @param \PlaygroundGame\Entity\Prize $prize
2479
     */
2480
    public function sendMail($game, $user, $lastEntry, $prize = null)
2481
    {
2482 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...
2483
            $game->getMailWinner() &&
2484
            $lastEntry->getWinner()
2485
        ) {
2486
            $this->sendResultMail($game, $user, $lastEntry, 'winner', $prize);
2487
        }
2488
2489 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...
2490
            $game->getMailLooser() &&
2491
            !$lastEntry->getWinner()
2492
        ) {
2493
            $this->sendResultMail($game, $user, $lastEntry, 'looser');
2494
        }
2495
    }
2496
2497
    public function getPlayerFormMapper()
2498
    {
2499
        if (null === $this->playerformMapper) {
2500
            $this->playerformMapper = $this->getServiceManager()->get('playgroundgame_playerform_mapper');
2501
        }
2502
2503
        return $this->playerformMapper;
2504
    }
2505
2506
    public function setPlayerFormMapper($playerformMapper)
2507
    {
2508
        $this->playerformMapper = $playerformMapper;
2509
2510
        return $this;
2511
    }
2512
}
2513