Completed
Push — develop ( 7bb4ed...37ee4f )
by greg
07:05
created

Game::resize()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 33
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

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

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

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

Loading history...
100
            $tmpDate = \DateTime::createFromFormat('d/m/Y', $data['publicationDate']);
101
            $data['publicationDate'] = $tmpDate->format('Y-m-d');
102
        }
103 View Code Duplication
        if (isset($data['startDate']) && $data['startDate']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
104
            $tmpDate = \DateTime::createFromFormat('d/m/Y', $data['startDate']);
105
            $data['startDate'] = $tmpDate->format('Y-m-d');
106
        }
107 View Code Duplication
        if (isset($data['endDate']) && $data['endDate']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
108
            $tmpDate = \DateTime::createFromFormat('d/m/Y', $data['endDate']);
109
            $data['endDate'] = $tmpDate->format('Y-m-d');
110
        }
111 View Code Duplication
        if (isset($data['closeDate']) && $data['closeDate']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
112
            $tmpDate = \DateTime::createFromFormat('d/m/Y', $data['closeDate']);
113
            $data['closeDate'] = $tmpDate->format('Y-m-d');
114
        }
115
116
        // If publicationDate is null, I update it with the startDate if not null neither
117
        if (! isset($data['publicationDate']) && isset($data['startDate'])) {
118
            $data['publicationDate'] = $data['startDate'];
119
        }
120
121
        // If the identifier has not been set, I use the title to create one.
122 View Code Duplication
        if (empty($data['identifier']) && ! empty($data['title'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
123
            $data['identifier'] = $data['title'];
124
        }
125
126
        $form->setData($data);
127
128 View Code Duplication
        if (! $form->isValid()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
129
            if (isset($data['publicationDate']) && $data['publicationDate']) {
130
                $tmpDate = \DateTime::createFromFormat('Y-m-d', $data['publicationDate']);
131
                $data['publicationDate'] = $tmpDate->format('d/m/Y');
132
                $form->setData(array(
133
                    'publicationDate' => $data['publicationDate']
134
                ));
135
            }
136
            if (isset($data['startDate']) && $data['startDate']) {
137
                $tmpDate = \DateTime::createFromFormat('Y-m-d', $data['startDate']);
138
                $data['startDate'] = $tmpDate->format('d/m/Y');
139
                $form->setData(array(
140
                    'startDate' => $data['startDate']
141
                ));
142
            }
143
            if (isset($data['endDate']) && $data['endDate']) {
144
                $tmpDate = \DateTime::createFromFormat('Y-m-d', $data['endDate']);
145
                $data['endDate'] = $tmpDate->format('d/m/Y');
146
                $form->setData(array(
147
                    'endDate' => $data['endDate']
148
                ));
149
            }
150
            if (isset($data['closeDate']) && $data['closeDate']) {
151
                $tmpDate = \DateTime::createFromFormat('Y-m-d', $data['closeDate']);
152
                $data['closeDate'] = $tmpDate->format('d/m/Y');
153
                $form->setData(array(
154
                    'closeDate' => $data['closeDate']
155
                ));
156
            }
157
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by PlaygroundGame\Service\Game::create of type PlaygroundGame\Entity\Game.

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

Let’s take a look at an example:

class Author {
    private $name;

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

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

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

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

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

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

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

Loading history...
158
        }
159
160
        $game = $form->getData();
161
        $game = $this->getGameMapper()->insert($game);
162
163
        // If I receive false, it means that the FB Id was not available anymore
164
        $result = $this->getEventManager()->trigger(__FUNCTION__, $this, array(
165
            'game' => $game
166
        ));
167
        if (! $result) {
168
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by PlaygroundGame\Service\Game::create of type PlaygroundGame\Entity\Game.

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

Let’s take a look at an example:

class Author {
    private $name;

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

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

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

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

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

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

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

Loading history...
169
        }
170
171
            // I wait for the game to be saved to obtain its ID.
172 View Code Duplication
        if (! empty($data['uploadStylesheet']['tmp_name'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
173
            ErrorHandler::start();
174
            move_uploaded_file($data['uploadStylesheet']['tmp_name'], $path . 'stylesheet_' . $game->getId() . '.css');
175
            $game->setStylesheet($media_url . 'stylesheet_' . $game->getId() . '.css');
176
            ErrorHandler::stop(true);
177
        }
178
179 View Code Duplication
        if (! empty($data['uploadMainImage']['tmp_name'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
180
            ErrorHandler::start();
181
            $data['uploadMainImage']['name'] = $this->fileNewname(
182
                $path,
183
                $game->getId() . "-" . $data['uploadMainImage']['name']
184
            );
185
            move_uploaded_file($data['uploadMainImage']['tmp_name'], $path . $data['uploadMainImage']['name']);
186
            $game->setMainImage($media_url . $data['uploadMainImage']['name']);
187
            ErrorHandler::stop(true);
188
        }
189
190 View Code Duplication
        if (! empty($data['uploadSecondImage']['tmp_name'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
191
            ErrorHandler::start();
192
            $data['uploadSecondImage']['name'] = $this->fileNewname(
193
                $path,
194
                $game->getId() . "-" . $data['uploadSecondImage']['name']
195
            );
196
            move_uploaded_file($data['uploadSecondImage']['tmp_name'], $path . $data['uploadSecondImage']['name']);
197
            $game->setSecondImage($media_url . $data['uploadSecondImage']['name']);
198
            ErrorHandler::stop(true);
199
        }
200
201 View Code Duplication
        if (! empty($data['uploadFbShareImage']['tmp_name'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
202
            ErrorHandler::start();
203
            $data['uploadFbShareImage']['name'] = $this->fileNewname(
204
                $path,
205
                $game->getId() . "-" . $data['uploadFbShareImage']['name']
206
            );
207
            move_uploaded_file($data['uploadFbShareImage']['tmp_name'], $path . $data['uploadFbShareImage']['name']);
208
            $game->setFbShareImage($media_url . $data['uploadFbShareImage']['name']);
209
            ErrorHandler::stop(true);
210
        }
211
212 View Code Duplication
        if (! empty($data['uploadFbPageTabImage']['tmp_name'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
213
            ErrorHandler::start();
214
            $extension = $this->getExtension(strtolower($data['uploadFbPageTabImage']['name']));
215
            $src = $this->getSrc($extension, $data['uploadFbPageTabImage']['tmp_name']);
216
            $this->resize(
217
                $data['uploadFbPageTabImage']['tmp_name'],
218
                $extension,
219
                $path . $game->getId() . "-" . $data['uploadFbPageTabImage']['name'],
220
                $src,
221
                111,
222
                74
223
            );
224
225
            $game->setFbPageTabImage($media_url . $game->getId() . "-" . $data['uploadFbPageTabImage']['name']);
226
            ErrorHandler::stop(true);
227
        }
228
        $game = $this->getGameMapper()->update($game);
229
230
        $prize_mapper = $this->getServiceManager()->get('playgroundgame_prize_mapper');
231
        if (isset($data['prizes'])) {
232
            foreach ($data['prizes'] as $prize_data) {
233
                if (! empty($prize_data['picture']['tmp_name'])) {
234 View Code Duplication
                    if ($prize_data['id']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
235
                        $prize = $prize_mapper->findById($prize_data['id']);
236
                    } else {
237
                        $some_prizes = $prize_mapper->findBy(array(
238
                            'game' => $game,
239
                            'title' => $prize_data['title']
240
                        ));
241
                        if (count($some_prizes) == 1) {
242
                            $prize = $some_prizes[0];
243
                        } else {
244
                            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by PlaygroundGame\Service\Game::create of type PlaygroundGame\Entity\Game.

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

Let’s take a look at an example:

class Author {
    private $name;

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

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

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

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

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

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

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

Loading history...
245
                        }
246
                    }
247
                    ErrorHandler::start();
248
                    $filename = "game-" . $game->getId() . "-prize-";
249
                    $filename .= $prize->getId() . "-" . $prize_data['picture']['name'];
250
                    move_uploaded_file($prize_data['picture']['tmp_name'], $path . $filename);
251
                    $prize->setPicture($media_url . $filename);
252
                    ErrorHandler::stop(true);
253
                    $prize = $prize_mapper->update($prize);
0 ignored issues
show
Unused Code introduced by
$prize is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
254
                }
255
            }
256
        }
257
258
        return $game;
259
    }
260
261
    /**
262
     *
263
     *
264
     * This service is ready for all types of games
265
     *
266
     * @param array $data
267
     * @param string $formClass
268
     * @return \PlaygroundGame\Entity\Game
269
     */
270
    public function edit(array $data, $game, $formClass)
271
    {
272
        $entityManager = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
273
        $form = $this->getServiceManager()->get($formClass);
274
        $form->get('publicationDate')->setOptions(array(
275
            'format' => 'Y-m-d'
276
        ));
277
        $form->get('startDate')->setOptions(array(
278
            'format' => 'Y-m-d'
279
        ));
280
        $form->get('endDate')->setOptions(array(
281
            'format' => 'Y-m-d'
282
        ));
283
        $form->get('closeDate')->setOptions(array(
284
            'format' => 'Y-m-d'
285
        ));
286
287
        $form->bind($game);
288
289
        $path = $this->getOptions()->getMediaPath() . '/';
290
        $media_url = $this->getOptions()->getMediaUrl() . '/';
291
292
        $identifierInput = $form->getInputFilter()->get('identifier');
293
        $noObjectExistsValidator = new NoObjectExistsValidator(array(
294
            'object_repository' => $entityManager->getRepository('PlaygroundGame\Entity\Game'),
295
            'fields' => 'identifier',
296
            'messages' => array(
297
                'objectFound' => 'This url already exists !'
298
            )
299
        ));
300
301
        if ($game->getIdentifier() != $data['identifier']) {
302
            $identifierInput->getValidatorChain()->addValidator($noObjectExistsValidator);
303
        }
304
305
        // I must switch from original format to the Y-m-d format because
306
        // this is the only one accepted by new DateTime($value)
307 View Code Duplication
        if (isset($data['publicationDate']) && $data['publicationDate']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
308
            $tmpDate = \DateTime::createFromFormat('d/m/Y', $data['publicationDate']);
309
            $data['publicationDate'] = $tmpDate->format('Y-m-d');
310
        }
311 View Code Duplication
        if (isset($data['startDate']) && $data['startDate']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
312
            $tmpDate = \DateTime::createFromFormat('d/m/Y', $data['startDate']);
313
            $data['startDate'] = $tmpDate->format('Y-m-d');
314
        }
315 View Code Duplication
        if (isset($data['endDate']) && $data['endDate']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
316
            $tmpDate = \DateTime::createFromFormat('d/m/Y', $data['endDate']);
317
            $data['endDate'] = $tmpDate->format('Y-m-d');
318
        }
319 View Code Duplication
        if (isset($data['closeDate']) && $data['closeDate']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
320
            $tmpDate = \DateTime::createFromFormat('d/m/Y', $data['closeDate']);
321
            $data['closeDate'] = $tmpDate->format('Y-m-d');
322
        }
323
324
        // If publicationDate is null, I update it with the startDate if not nul neither
325
        if ((! isset($data['publicationDate']) || $data['publicationDate'] == '') &&
326
            (isset($data['startDate']) && $data['startDate'] != '')
327
        ) {
328
            $data['publicationDate'] = $data['startDate'];
329
        }
330
331 View Code Duplication
        if ((! isset($data['identifier']) || empty($data['identifier'])) && isset($data['title'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
332
            $data['identifier'] = $data['title'];
333
        }
334
335
        $form->setData($data);
336
337
        // If someone want to claim... It's time to do it ! used for exemple by PlaygroundFacebook Module
338
        $result = $this->getEventManager()->trigger(__FUNCTION__ . '.validate', $this, array(
339
            'game' => $game,
340
            'data' => $data
341
        ));
342
        if (is_array($result) && ! $result[0]) {
343
            $form->get('fbAppId')->setMessages(array(
344
                'Vous devez d\'abord désinstaller l\'appli Facebook'
345
            ));
346
347
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by PlaygroundGame\Service\Game::edit of type PlaygroundGame\Entity\Game.

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

Let’s take a look at an example:

class Author {
    private $name;

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

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

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

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

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

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

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

Loading history...
348
        }
349
350 View Code Duplication
        if (! $form->isValid()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
351
            if (isset($data['publicationDate']) && $data['publicationDate']) {
352
                $tmpDate = \DateTime::createFromFormat('Y-m-d', $data['publicationDate']);
353
                $data['publicationDate'] = $tmpDate->format('d/m/Y');
354
                $form->setData(array(
355
                    'publicationDate' => $data['publicationDate']
356
                ));
357
            }
358
            if (isset($data['startDate']) && $data['startDate']) {
359
                $tmpDate = \DateTime::createFromFormat('Y-m-d', $data['startDate']);
360
                $data['startDate'] = $tmpDate->format('d/m/Y');
361
                $form->setData(array(
362
                    'startDate' => $data['startDate']
363
                ));
364
            }
365
            if (isset($data['endDate']) && $data['endDate']) {
366
                $tmpDate = \DateTime::createFromFormat('Y-m-d', $data['endDate']);
367
                $data['endDate'] = $tmpDate->format('d/m/Y');
368
                $form->setData(array(
369
                    'endDate' => $data['endDate']
370
                ));
371
            }
372
            if (isset($data['closeDate']) && $data['closeDate']) {
373
                $tmpDate = \DateTime::createFromFormat('Y-m-d', $data['closeDate']);
374
                $data['closeDate'] = $tmpDate->format('d/m/Y');
375
                $form->setData(array(
376
                    'closeDate' => $data['closeDate']
377
                ));
378
            }
379
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by PlaygroundGame\Service\Game::edit of type PlaygroundGame\Entity\Game.

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

Let’s take a look at an example:

class Author {
    private $name;

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

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

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

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

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

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

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

Loading history...
380
        }
381
382 View Code Duplication
        if (! empty($data['uploadMainImage']['tmp_name'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
383
            ErrorHandler::start();
384
            $data['uploadMainImage']['name'] = $this->fileNewname(
385
                $path,
386
                $game->getId() . "-" . $data['uploadMainImage']['name']
387
            );
388
            move_uploaded_file($data['uploadMainImage']['tmp_name'], $path . $data['uploadMainImage']['name']);
389
            $game->setMainImage($media_url . $data['uploadMainImage']['name']);
390
            ErrorHandler::stop(true);
391
        }
392
393 View Code Duplication
        if (isset($data['deleteMainImage']) &&
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
394
            $data['deleteMainImage'] &&
395
            empty($data['uploadMainImage']['tmp_name'])
396
        ) {
397
            ErrorHandler::start();
398
            $image = $game->getMainImage();
399
            $image = str_replace($media_url, '', $image);
400
            unlink($path . $image);
401
            $game->setMainImage(null);
402
            ErrorHandler::stop(true);
403
        }
404
405 View Code Duplication
        if (! empty($data['uploadSecondImage']['tmp_name'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
406
            ErrorHandler::start();
407
            $data['uploadSecondImage']['name'] = $this->fileNewname(
408
                $path,
409
                $game->getId() . "-" . $data['uploadSecondImage']['name']
410
            );
411
            move_uploaded_file($data['uploadSecondImage']['tmp_name'], $path . $data['uploadSecondImage']['name']);
412
            $game->setSecondImage($media_url . $data['uploadSecondImage']['name']);
413
            ErrorHandler::stop(true);
414
        }
415
416 View Code Duplication
        if (isset($data['deleteSecondImage']) &&
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
417
            $data['deleteSecondImage'] &&
418
            empty($data['uploadSecondImage']['tmp_name'])
419
        ) {
420
            ErrorHandler::start();
421
            $image = $game->getSecondImage();
422
            $image = str_replace($media_url, '', $image);
423
            unlink($path . $image);
424
            $game->setSecondImage(null);
425
            ErrorHandler::stop(true);
426
        }
427
428 View Code Duplication
        if (! empty($data['uploadStylesheet']['tmp_name'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
429
            ErrorHandler::start();
430
            move_uploaded_file($data['uploadStylesheet']['tmp_name'], $path . 'stylesheet_' . $game->getId() . '.css');
431
            $game->setStylesheet($media_url . 'stylesheet_' . $game->getId() . '.css');
432
            ErrorHandler::stop(true);
433
        }
434
435 View Code Duplication
        if (! empty($data['uploadFbShareImage']['tmp_name'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
436
            ErrorHandler::start();
437
            $data['uploadFbShareImage']['name'] = $this->fileNewname(
438
                $path,
439
                $game->getId() . "-" . $data['uploadFbShareImage']['name']
440
            );
441
            move_uploaded_file($data['uploadFbShareImage']['tmp_name'], $path . $data['uploadFbShareImage']['name']);
442
            $game->setFbShareImage($media_url . $data['uploadFbShareImage']['name']);
443
            ErrorHandler::stop(true);
444
        }
445
446 View Code Duplication
        if (isset($data['deleteFbShareImage']) &&
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
447
            $data['deleteFbShareImage'] &&
448
            empty($data['uploadFbShareImage']['tmp_name'])
449
        ) {
450
            ErrorHandler::start();
451
            $image = $game->getFbShareImage();
452
            $image = str_replace($media_url, '', $image);
453
            unlink($path . $image);
454
            $game->setFbShareImage(null);
455
            ErrorHandler::stop(true);
456
        }
457
458 View Code Duplication
        if (! empty($data['uploadFbPageTabImage']['tmp_name'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
459
            ErrorHandler::start();
460
461
            $extension = $this->getExtension(strtolower($data['uploadFbPageTabImage']['name']));
462
            $src = $this->getSrc($extension, $data['uploadFbPageTabImage']['tmp_name']);
463
            $this->resize(
464
                $data['uploadFbPageTabImage']['tmp_name'],
465
                $extension,
466
                $path . $game->getId() . "-" . $data['uploadFbPageTabImage']['name'],
467
                $src,
468
                111,
469
                74
470
            );
471
472
            $game->setFbPageTabImage($media_url . $game->getId() . "-" . $data['uploadFbPageTabImage']['name']);
473
            ErrorHandler::stop(true);
474
        }
475
476 View Code Duplication
        if (isset($data['deleteFbPageTabImage']) &&
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
477
            $data['deleteFbPageTabImage'] &&
478
            empty($data['uploadFbPageTabImage']['tmp_name'])
479
        ) {
480
            ErrorHandler::start();
481
            $image = $game->getFbPageTabImage();
482
            $image = str_replace($media_url, '', $image);
483
            unlink($path . $image);
484
            $game->setFbPageTabImage(null);
485
            ErrorHandler::stop(true);
486
        }
487
488
        $game = $this->getGameMapper()->update($game);
489
490
        $prize_mapper = $this->getServiceManager()->get('playgroundgame_prize_mapper');
491
        if (isset($data['prizes'])) {
492
            foreach ($data['prizes'] as $prize_data) {
493
                if (! empty($prize_data['picture_file']['tmp_name']) && ! $prize_data['picture_file']['error']) {
494 View Code Duplication
                    if ($prize_data['id']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
495
                        $prize = $prize_mapper->findById($prize_data['id']);
496
                    } else {
497
                        $some_prizes = $prize_mapper->findBy(array(
498
                            'game' => $game,
499
                            'title' => $prize_data['title']
500
                        ));
501
                        if (count($some_prizes) == 1) {
502
                            $prize = $some_prizes[0];
503
                        } else {
504
                            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by PlaygroundGame\Service\Game::edit of type PlaygroundGame\Entity\Game.

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

Let’s take a look at an example:

class Author {
    private $name;

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

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

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

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

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

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

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

Loading history...
505
                        }
506
                    }
507
                    // Remove if existing image
508
                    if ($prize->getPicture() && file_exists($prize->getPicture())) {
509
                        unlink($prize->getPicture());
510
                        $prize->getPicture(null);
511
                    }
512
                    // Upload and set new
513
                    ErrorHandler::start();
514
                    $filename = "game-" . $game->getId() . "-prize-";
515
                    $filename .= $prize->getId() . "-" . $prize_data['picture_file']['name'];
516
                    move_uploaded_file($prize_data['picture_file']['tmp_name'], $path . $filename);
517
                    $prize->setPicture($media_url . $filename);
518
                    ErrorHandler::stop(true);
519
                    $prize = $prize_mapper->update($prize);
0 ignored issues
show
Unused Code introduced by
$prize is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
520
                }
521
            }
522
        }
523
        // If I receive false, it means that the FB Id was not available anymore
524
        $result = $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
0 ignored issues
show
Unused Code introduced by
$result is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
525
            'game' => $game
526
        ));
527
528
        return $game;
529
    }
530
531
    /**
532
     * getActiveGames
533
     *
534
     * @return Array of PlaygroundGame\Entity\Game
535
     */
536
    public function getActiveGames($displayHome = true, $classType = '', $order = '')
537
    {
538
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
539
        $today = new \DateTime("now");
540
        $today = $today->format('Y-m-d') . ' 23:59:59';
541
        $orderBy = 'g.publicationDate';
542
        if ($order != '') {
543
            $orderBy = 'g.'.$order;
544
        }
545
546
        $qb = $em->createQueryBuilder();
547
        $and = $qb->expr()->andx();
548
        $and->add(
549
            $qb->expr()->orX(
550
                $qb->expr()->lte('g.publicationDate', ':date'),
551
                $qb->expr()->isNull('g.publicationDate')
552
            )
553
        );
554
        $and->add(
555
            $qb->expr()->orX(
556
                $qb->expr()->gte('g.closeDate', ':date'),
557
                $qb->expr()->isNull('g.closeDate')
558
            )
559
        );
560
        $qb->setParameter('date', $today);
561
        
562
        $and->add($qb->expr()->eq('g.active', '1'));
563
        $and->add($qb->expr()->eq('g.broadcastPlatform', '1'));
564
        
565
        if ($classType != '') {
566
            $and->add($qb->expr()->eq('g.classType', ':classType'));
567
            $qb->setParameter('classType', $classType);
568
        }
569
        
570
        if ($displayHome) {
571
            $and->add($qb->expr()->eq('g.displayHome', true));
572
        }
573
        
574
        $qb->select('g')
575
        ->from('PlaygroundGame\Entity\Game', 'g')
576
        ->where($and)
577
        ->orderBy($orderBy, 'DESC');
578
        
579
        $query = $qb->getQuery();
580
        $games = $query->getResult();
581
        
582
        // je les classe par date de publication (date comme clé dans le tableau afin de pouvoir merger les objets
583
        // de type article avec le même procédé en les classant naturellement par date asc ou desc
584
        $arrayGames = array();
585 View Code Duplication
        foreach ($games as $game) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
586
            if ($game->getPublicationDate()) {
587
                $key = $game->getPublicationDate()->format('Ymd');
588
            } elseif ($game->getStartDate()) {
589
                $key = $game->getStartDate()->format('Ymd');
590
            } else {
591
                $key = $game->getUpdatedAt()->format('Ymd');
592
            }
593
            $key .= $game->getUpdatedAt()->format('Ymd') . '-' . $game->getId();
594
            $arrayGames[$key] = $game;
595
        }
596
597
        return $arrayGames;
598
    }
599
600
    /**
601
     * getAvailableGames : Games OnLine and not already played by $user
602
     *
603
     * @return Array of PlaygroundGame\Entity\Game
604
     */
605
    public function getAvailableGames($user, $maxResults = 2)
606
    {
607
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
608
        $today = new \DateTime("now");
609
        $today = $today->format('Y-m-d') . ' 23:59:59';
610
611
        // Game active with a start_date before today (or without start_date)
612
        // and end_date after today (or without end-date)
613
        $query = $em->createQuery('SELECT g FROM PlaygroundGame\Entity\Game g
614
                WHERE NOT EXISTS (SELECT l FROM PlaygroundGame\Entity\Entry l WHERE l.game = g AND l.user = :user)
615
                AND (g.startDate <= :date OR g.startDate IS NULL)
616
                AND (g.endDate >= :date OR g.endDate IS NULL)
617
                AND g.active = 1 AND g.broadcastPlatform = 1
618
                ORDER BY g.startDate ASC');
619
        $query->setParameter('date', $today);
620
        $query->setParameter('user', $user);
621
        $query->setMaxResults($maxResults);
622
        $games = $query->getResult();
623
624
        return $games;
625
    }
626
627 View Code Duplication
    public function getEntriesQuery($game)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
628
    {
629
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
630
631
        $qb = $em->createQueryBuilder();
632
        $qb->select('
633
            e.id,
634
            u.username,
635
            u.title,
636
            u.firstname,
637
            u.lastname,
638
            u.email,
639
            u.optin,
640
            u.optinPartner,
641
            u.address,
642
            u.address2,
643
            u.postalCode,
644
            u.city,
645
            u.telephone,
646
            u.mobile,
647
            u.created_at,
648
            u.dob,
649
            e.winner,
650
            e.socialShares,
651
            e.playerData,
652
            e.updated_at
653
            ')
654
            ->from('PlaygroundGame\Entity\Entry', 'e')
655
            ->leftJoin('e.user', 'u')
656
            ->where($qb->expr()->eq('e.game', ':game'));
657
        
658
        $qb->setParameter('game', $game);
659
660
        return $qb->getQuery();
661
    }
662
663
    public function getEntriesHeader($game)
664
    {
665
        if ($game->getPlayerForm()) {
666
            $formPV = json_decode($game->getPlayerForm()->getForm(), true);
667
            $header = array('id'=> 1);
668 View Code Duplication
            foreach ($formPV as $element) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
669
                foreach ($element as $k => $v) {
670
                    if ($k !== 'form_properties') {
671
                        $header[$v[0]['name']] = 1;
672
                    }
673
                }
674
            }
675
        } else {
676
            $header = array(
677
                'id' => 1,
678
                'username' => 1,
679
                'title' => 1,
680
                'firstname' => 1,
681
                'lastname' => 1,
682
                'email' => 1,
683
                'optin' => 1,
684
                'optinPartner' => 1,
685
                'address' => 1,
686
                'address2' => 1,
687
                'postalCode' => 1,
688
                'city' => 1,
689
                'telephone' => 1,
690
                'mobile' => 1,
691
                'created_at' => 1,
692
                'dob' => 1,
693
                'winner' => 1
694
            );
695
        }
696
        $header['winner'] = 1;
697
        $header['socialShares'] = 1;
698
        $header['updated_at'] = 1;
699
700
        return $header;
701
    }
702
703
    /**
704
    * getGameEntries : I create an array of entries based on playerData + header
705
    *
706
    * @return Array of PlaygroundGame\Entity\Game
707
    */
708
    public function getGameEntries($header, $entries, $game)
709
    {
710
        $header = $this->getEntriesHeader($game);
711
712
        $results = array();
713
714
        foreach ($entries as $k => $entry) {
715
            $entryData = json_decode($entry['playerData'], true);
716 View Code Duplication
            foreach ($header as $key => $v) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
717
                if (isset($entryData[$key])) {
718
                    $results[$k][$key] = (is_array($entryData[$key]))?implode(', ', $entryData[$key]):$entryData[$key];
719
                } elseif (array_key_exists($key, $entry)) {
720
                    $results[$k][$key] = ($entry[$key] instanceof \DateTime)?
721
                        $entry[$key]->format('Y-m-d'):
722
                        $entry[$key];
723
                } else {
724
                    $results[$k][$key] = '';
725
                }
726
            }
727
        }
728
729
        return $results;
730
    }
731
732
    /**
733
     * getActiveSliderGames
734
     *
735
     * @return Array of PlaygroundGame\Entity\Game
736
     */
737
    public function getActiveSliderGames()
738
    {
739
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
740
        $today = new \DateTime("now");
741
        $today = $today->format('Y-m-d') . ' 23:59:59';
742
743
        // Game active with a start_date before today (or without start_date)
744
        // and end_date after today (or without end-date)
745
        $query = $em->createQuery('SELECT g FROM PlaygroundGame\Entity\Game g
746
            WHERE (g.publicationDate <= :date OR g.publicationDate IS NULL)
747
            AND (g.closeDate >= :date OR g.closeDate IS NULL)
748
            AND g.active = true AND g.broadcastPlatform = 1 AND g.pushHome = true');
749
        $query->setParameter('date', $today);
750
        $games = $query->getResult();
751
752
        // je les classe par date de publication (date comme clé dans le tableau afin de pouvoir merger les objets
753
        // de type article avec le même procédé en les classant naturellement par date asc ou desc
754
        $arrayGames = array();
755 View Code Duplication
        foreach ($games as $game) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
756
            if ($game->getPublicationDate()) {
757
                $key = $game->getPublicationDate()->format('Ymd');
758
            } elseif ($game->getStartDate()) {
759
                $key = $game->getStartDate()->format('Ymd');
760
            } else {
761
                $key = $game->getUpdatedAt()->format('Ymd');
762
            }
763
            $key .= $game->getUpdatedAt()->format('Ymd') . '-' . $game->getId();
764
            $arrayGames[$key] = $game;
765
        }
766
767
        return $arrayGames;
768
    }
769
770
    /**
771
     * getPrizeCategoryGames
772
     *
773
     * @return Array of PlaygroundGame\Entity\Game
774
     */
775 View Code Duplication
    public function getPrizeCategoryGames($categoryid)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
776
    {
777
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
778
779
        $query = $em->createQuery('SELECT g FROM PlaygroundGame\Entity\Game g
780
            WHERE (g.prizeCategory = :categoryid AND g.broadcastPlatform = 1)
781
            ORDER BY g.publicationDate DESC');
782
        $query->setParameter('categoryid', $categoryid);
783
        $games = $query->getResult();
784
785
        return $games;
786
    }
787
788
    public function checkGame($identifier, $checkIfStarted = true)
789
    {
790
        $gameMapper = $this->getGameMapper();
791
792
        if (! $identifier) {
793
            return false;
794
        }
795
796
        $game = $gameMapper->findByIdentifier($identifier);
797
798
        // the game has not been found
799
        if (! $game) {
800
            return false;
801
        }
802
803
        if ($this->getServiceManager()
804
            ->get('Application')
805
            ->getMvcEvent()
806
            ->getRouteMatch()
807
            ->getParam('channel') === 'preview' && $this->isAllowed('game', 'edit')) {
808
            $game->setActive(true);
809
            $game->setStartDate(null);
810
            $game->setEndDate(null);
811
            $game->setPublicationDate(null);
812
            $game->setBroadcastPlatform(true);
813
814
            // I don't want the game to be updated through any update during the preview mode.
815
            // I mark it as readonly for Doctrine
816
            $this->getServiceManager()
817
                ->get('doctrine.entitymanager.orm_default')
818
                ->getUnitOfWork()
819
                ->markReadOnly($game);
820
            return $game;
821
        }
822
823
        // The game is inactive
824
        if (! $game->getActive()) {
825
            return false;
826
        }
827
828
        // the game has not begun yet
829
        if (! $game->isOpen()) {
830
            return false;
831
        }
832
833
        // the game is finished and closed
834
        if (! $game->isStarted() && $checkIfStarted) {
835
            return false;
836
        }
837
838
        return $game;
839
    }
840
841
    /**
842
     * Return the last entry of the user on this game, if it exists.
843
     * An entry can be associated to :
844
     * - A user account (a real one, linked to PlaygroundUser
845
     * - An anonymous Identifier (based on one value of playerData (generally email))
846
     * - A cookie set on the player device (the less secure)
847
     * If the active param is set, it can check if the entry is active or not.
848
     * If the bonus param is set, it can check if the entry is a bonus or not.
849
     *
850
     * @param unknown $game
851
     * @param string $user
852
     * @param boolean $active
853
     * @param boolean $bonus
854
     * @return boolean
855
     */
856
    public function checkExistingEntry($game, $user = null, $active = null, $bonus = null)
857
    {
858
        $entry = false;
0 ignored issues
show
Unused Code introduced by
$entry is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
859
        $search = array('game'  => $game);
860
861
        if ($user) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $user of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

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

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

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

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
862
            $search['user'] = $user;
863
        } elseif ($this->getAnonymousIdentifier()) {
864
            $search['anonymousIdentifier'] = $this->getAnonymousIdentifier();
865
            $search['user'] = null;
866
        } else {
867
            $search['anonymousId'] = $this->getAnonymousId();
868
            $search['user'] = null;
869
        }
870
        
871
        if (! is_null($active)) {
872
            $search['active'] = $active;
873
        }
874
        if (! is_null($bonus)) {
875
            $search['bonus'] = $bonus;
876
        }
877
878
        $entry = $this->getEntryMapper()->findOneBy($search, array('updated_at' => 'desc'));
879
880
        return $entry;
881
    }
882
883
    /*
884
    * This function updates the entry with the player data after checking 
885
    * that the data are compliant with the formUser Game attribute
886
    *
887
    * The $data has to be a json object
888
    */
889
    public function updateEntryPlayerForm($data, $game, $user, $entry, $mandatory = true)
0 ignored issues
show
Unused Code introduced by
The parameter $user is not used and could be removed.

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

Loading history...
890
    {
891
        $form = $this->createFormFromJson($game->getPlayerForm()->getForm(), 'playerForm');
892
        $form->setData($data);
893
894
        if (!$mandatory) {
895
            $filter = $form->getInputFilter();
896
            foreach ($form->getElements() as $element) {
897
                try {
898
                    $elementInput = $filter->get($element->getName());
899
                    $elementInput->setRequired(false);
0 ignored issues
show
Bug introduced by
The method setRequired does only exist in Zend\InputFilter\InputInterface, but not in Zend\InputFilter\InputFilterInterface.

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

Let’s take a look at an example:

class A
{
    public function foo() { }
}

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

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

Available Fixes

  1. Add an additional type-check:

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

    function someFunction(B $x) { /** ... */ }
    
Loading history...
900
                    $form->get($element->getName())->setAttribute('required', false);
901
                } catch (\Zend\Form\Exception\InvalidElementException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
902
                }
903
            }
904
        }
905
906
        if ($form->isValid()) {
907
            $dataJson = json_encode($form->getData());
908
909
            if ($game->getAnonymousAllowed() &&
910
                $game->getAnonymousIdentifier() &&
911
                isset($data[$game->getAnonymousIdentifier()])
912
            ) {
913
                $session = new \Zend\Session\Container('anonymous_identifier');
914
                if (empty($session->offsetGet('anonymous_identifier'))) {
915
                    $anonymousIdentifier = $data[$game->getAnonymousIdentifier()];
916
                
917
                    $entry->setAnonymousIdentifier($anonymousIdentifier);
918
                
919
                    // I must transmit this info during the whole game workflow
920
                    $session->offsetSet('anonymous_identifier', $anonymousIdentifier);
921
                }
922
            }
923
924
            $entry->setPlayerData($dataJson);
925
            $this->getEntryMapper()->update($entry);
926
        } else {
927
            return false;
928
        }
929
930
        return true;
931
    }
932
933
934
    public function checkIsFan($game)
0 ignored issues
show
Unused Code introduced by
The parameter $game is not used and could be removed.

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

Loading history...
935
    {
936
        // If on Facebook, check if you have to be a FB fan to play the game
937
        $session = new Container('facebook');
938
939
        if ($session->offsetExists('signed_request')) {
940
            // I'm on Facebook
941
            $sr = $session->offsetGet('signed_request');
942
            if ($sr['page']['liked'] == 1) {
943
                return true;
944
            }
945
        } else {
946
            // I'm not on Facebook
947
            return true;
948
        }
949
950
        return false;
951
    }
952
    
953
    public function getAnonymousIdentifier()
954
    {
955
        if (is_null($this->anonymousIdentifier)) {
956
            // If on Facebook, check if you have to be a FB fan to play the game
957
            $session = new Container('anonymous_identifier');
958
            
959
            if ($session->offsetExists('anonymous_identifier')) {
960
                $this->anonymousIdentifier = $session->offsetGet('anonymous_identifier');
961
            } else {
962
                $this->anonymousIdentifier = false;
963
            }
964
        }
965
    
966
        return $this->anonymousIdentifier;
967
    }
968
969
    /**
970
     * errors :
971
     * -1 : user not connected
972
     * -2 : limit entry games for this user reached
973
     *
974
     * @param \PlaygroundGame\Entity\Game $game
975
     * @param \PlaygroundUser\Entity\UserInterface $user
976
     * @return number unknown
977
     */
978
    public function play($game, $user)
979
    {
980
981
        // certaines participations peuvent rester ouvertes.
982
        // On autorise alors le joueur à reprendre là ou il en était
983
        // par exemple les postvote...
984
        $entry = $this->checkExistingEntry($game, $user, true);
0 ignored issues
show
Documentation introduced by
$user is of type object<PlaygroundUser\Entity\UserInterface>, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

Let’s take a look at an example:

class Author {
    private $name;

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

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

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

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

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

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

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

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