Completed
Push — master ( 905126...e876c0 )
by greg
08:24 queued 04:04
created

Game::getQueryGamesOrderBy()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 48
Code Lines 23

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 48
rs 8.551
cc 5
eloc 23
nc 5
nop 2
1
<?php
2
namespace PlaygroundGame\Service;
3
4
use PlaygroundGame\Entity\Entry;
5
use Zend\Session\Container;
6
use Zend\ServiceManager\ServiceManagerAwareInterface;
7
use Zend\ServiceManager\ServiceManager;
8
use ZfcBase\EventManager\EventProvider;
9
use PlaygroundGame\Options\ModuleOptions;
10
use PlaygroundGame\Mapper\GameInterface as GameMapperInterface;
11
use DoctrineModule\Validator\NoObjectExists as NoObjectExistsValidator;
12
use Zend\Validator\File\Size;
13
use Zend\Validator\File\IsImage;
14
use Zend\Stdlib\ErrorHandler;
15
use PlaygroundCore\Filter\Sanitize;
16
use Zend\Form\Element;
17
use Zend\Form\Form;
18
use Zend\InputFilter\Factory as InputFactory;
19
20
class Game extends EventProvider implements ServiceManagerAwareInterface
21
{
22
    /**
23
     *
24
     * @var GameMapperInterface
25
     */
26
    protected $gameMapper;
27
28
    /**
29
     *
30
     * @var EntryMapperInterface
31
     */
32
    protected $entryMapper;
33
34
    /**
35
     *
36
     * @var ServiceManager
37
     */
38
    protected $serviceManager;
39
40
    /**
41
     *
42
     * @var UserServiceOptionsInterface
43
     */
44
    protected $options;
45
46
    protected $playerformMapper;
47
    
48
    protected $anonymousIdentifier = null;
49
50
    /**
51
     *
52
     *
53
     * This service is ready for all types of games
54
     *
55
     * @param array $data
56
     * @param string $entity
57
     * @param string $formClass
58
     * @return \PlaygroundGame\Entity\Game
59
     */
60
    public function create(array $data, $entity, $formClass)
61
    {
62
        $game = new $entity();
63
        $entityManager = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
64
65
        $form = $this->getServiceManager()->get($formClass);
66
        // I force the following format because this is the only one accepted by new DateTime($value) used by Doctrine when persisting
67
        $form->get('publicationDate')->setOptions(array(
68
            'format' => 'Y-m-d'
69
        ));
70
        $form->get('startDate')->setOptions(array(
71
            'format' => 'Y-m-d'
72
        ));
73
        $form->get('endDate')->setOptions(array(
74
            'format' => 'Y-m-d'
75
        ));
76
        $form->get('closeDate')->setOptions(array(
77
            'format' => 'Y-m-d'
78
        ));
79
80
        $form->bind($game);
81
82
        $path = $this->getOptions()->getMediaPath() . '/';
83
        $media_url = $this->getOptions()->getMediaUrl() . '/';
84
85
        $identifierInput = $form->getInputFilter()->get('identifier');
86
        $noObjectExistsValidator = new NoObjectExistsValidator(array(
87
            'object_repository' => $entityManager->getRepository('PlaygroundGame\Entity\Game'),
88
            'fields' => 'identifier',
89
            'messages' => array(
90
                'objectFound' => 'This url already exists !'
91
            )
92
        ));
93
94
        $identifierInput->getValidatorChain()->addValidator($noObjectExistsValidator);
95
96
        // I must switch from original format to the Y-m-d format because this is the only one accepted by new DateTime($value)
97 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...
98
            $tmpDate = \DateTime::createFromFormat('d/m/Y', $data['publicationDate']);
99
            $data['publicationDate'] = $tmpDate->format('Y-m-d');
100
        }
101 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...
102
            $tmpDate = \DateTime::createFromFormat('d/m/Y', $data['startDate']);
103
            $data['startDate'] = $tmpDate->format('Y-m-d');
104
        }
105 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...
106
            $tmpDate = \DateTime::createFromFormat('d/m/Y', $data['endDate']);
107
            $data['endDate'] = $tmpDate->format('Y-m-d');
108
        }
109 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...
110
            $tmpDate = \DateTime::createFromFormat('d/m/Y', $data['closeDate']);
111
            $data['closeDate'] = $tmpDate->format('Y-m-d');
112
        }
113
114
        // If publicationDate is null, I update it with the startDate if not null neither
115
        if (! isset($data['publicationDate']) && isset($data['startDate'])) {
116
            $data['publicationDate'] = $data['startDate'];
117
        }
118
119
        // If the identifier has not been set, I use the title to create one.
120 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...
121
            $data['identifier'] = $data['title'];
122
        }
123
124
        $form->setData($data);
125
126 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...
127
            if (isset($data['publicationDate']) && $data['publicationDate']) {
128
                $tmpDate = \DateTime::createFromFormat('Y-m-d', $data['publicationDate']);
129
                $data['publicationDate'] = $tmpDate->format('d/m/Y');
130
                $form->setData(array(
131
                    'publicationDate' => $data['publicationDate']
132
                ));
133
            }
134
            if (isset($data['startDate']) && $data['startDate']) {
135
                $tmpDate = \DateTime::createFromFormat('Y-m-d', $data['startDate']);
136
                $data['startDate'] = $tmpDate->format('d/m/Y');
137
                $form->setData(array(
138
                    'startDate' => $data['startDate']
139
                ));
140
            }
141
            if (isset($data['endDate']) && $data['endDate']) {
142
                $tmpDate = \DateTime::createFromFormat('Y-m-d', $data['endDate']);
143
                $data['endDate'] = $tmpDate->format('d/m/Y');
144
                $form->setData(array(
145
                    'endDate' => $data['endDate']
146
                ));
147
            }
148
            if (isset($data['closeDate']) && $data['closeDate']) {
149
                $tmpDate = \DateTime::createFromFormat('Y-m-d', $data['closeDate']);
150
                $data['closeDate'] = $tmpDate->format('d/m/Y');
151
                $form->setData(array(
152
                    'closeDate' => $data['closeDate']
153
                ));
154
            }
155
            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...
156
        }
157
158
        $game = $form->getData();
159
        $game = $this->getGameMapper()->insert($game);
160
161
        // If I receive false, it means that the FB Id was not available anymore
162
        $result = $this->getEventManager()->trigger(__FUNCTION__, $this, array(
163
            'game' => $game
164
        ));
165
        if (! $result) {
166
            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...
167
        }
168
169
            // I wait for the game to be saved to obtain its ID.
170 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...
171
            ErrorHandler::start();
172
            move_uploaded_file($data['uploadStylesheet']['tmp_name'], $path . 'stylesheet_' . $game->getId() . '.css');
173
            $game->setStylesheet($media_url . 'stylesheet_' . $game->getId() . '.css');
174
            ErrorHandler::stop(true);
175
        }
176
177 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...
178
            ErrorHandler::start();
179
            $data['uploadMainImage']['name'] = $this->fileNewname($path, $game->getId() . "-" . $data['uploadMainImage']['name']);
180
            move_uploaded_file($data['uploadMainImage']['tmp_name'], $path . $data['uploadMainImage']['name']);
181
            $game->setMainImage($media_url . $data['uploadMainImage']['name']);
182
            ErrorHandler::stop(true);
183
        }
184
185 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...
186
            ErrorHandler::start();
187
            $data['uploadSecondImage']['name'] = $this->fileNewname($path, $game->getId() . "-" . $data['uploadSecondImage']['name']);
188
            move_uploaded_file($data['uploadSecondImage']['tmp_name'], $path . $data['uploadSecondImage']['name']);
189
            $game->setSecondImage($media_url . $data['uploadSecondImage']['name']);
190
            ErrorHandler::stop(true);
191
        }
192
193 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...
194
            ErrorHandler::start();
195
            $data['uploadFbShareImage']['name'] = $this->fileNewname($path, $game->getId() . "-" . $data['uploadFbShareImage']['name']);
196
            move_uploaded_file($data['uploadFbShareImage']['tmp_name'], $path . $data['uploadFbShareImage']['name']);
197
            $game->setFbShareImage($media_url . $data['uploadFbShareImage']['name']);
198
            ErrorHandler::stop(true);
199
        }
200
201 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...
202
            ErrorHandler::start();
203
            $extension = $this->getExtension(strtolower($data['uploadFbPageTabImage']['name']));
204
            $src = $this->getSrc($extension, $data['uploadFbPageTabImage']['tmp_name']);
205
            $this->resize($data['uploadFbPageTabImage']['tmp_name'], $extension, $path . $game->getId() . "-" . $data['uploadFbPageTabImage']['name'], $src, 111, 74);
206
207
            $game->setFbPageTabImage($media_url . $game->getId() . "-" . $data['uploadFbPageTabImage']['name']);
208
            ErrorHandler::stop(true);
209
        }
210
        $game = $this->getGameMapper()->update($game);
211
212
        $prize_mapper = $this->getServiceManager()->get('playgroundgame_prize_mapper');
213
        if (isset($data['prizes'])) {
214
            foreach ($data['prizes'] as $prize_data) {
215
                if (! empty($prize_data['picture']['tmp_name'])) {
216 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...
217
                        $prize = $prize_mapper->findById($prize_data['id']);
218
                    } else {
219
                        $some_prizes = $prize_mapper->findBy(array(
220
                            'game' => $game,
221
                            'title' => $prize_data['title']
222
                        ));
223
                        if (count($some_prizes) == 1) {
224
                            $prize = $some_prizes[0];
225
                        } else {
226
                            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...
227
                        }
228
                    }
229
                    ErrorHandler::start();
230
                    $filename = "game-" . $game->getId() . "-prize-" . $prize->getId() . "-" . $prize_data['picture']['name'];
231
                    move_uploaded_file($prize_data['picture']['tmp_name'], $path . $filename);
232
                    $prize->setPicture($media_url . $filename);
233
                    ErrorHandler::stop(true);
234
                    $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...
235
                }
236
            }
237
        }
238
239
        return $game;
240
    }
241
242
    /**
243
     *
244
     *
245
     * This service is ready for all types of games
246
     *
247
     * @param array $data
248
     * @param string $formClass
249
     * @return \PlaygroundGame\Entity\Game
250
     */
251
    public function edit(array $data, $game, $formClass)
252
    {
253
        $entityManager = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
254
        $form = $this->getServiceManager()->get($formClass);
255
        $form->get('publicationDate')->setOptions(array(
256
            'format' => 'Y-m-d'
257
        ));
258
        $form->get('startDate')->setOptions(array(
259
            'format' => 'Y-m-d'
260
        ));
261
        $form->get('endDate')->setOptions(array(
262
            'format' => 'Y-m-d'
263
        ));
264
        $form->get('closeDate')->setOptions(array(
265
            'format' => 'Y-m-d'
266
        ));
267
268
        $form->bind($game);
269
270
        $path = $this->getOptions()->getMediaPath() . '/';
271
        $media_url = $this->getOptions()->getMediaUrl() . '/';
272
273
        $identifierInput = $form->getInputFilter()->get('identifier');
274
        $noObjectExistsValidator = new NoObjectExistsValidator(array(
275
            'object_repository' => $entityManager->getRepository('PlaygroundGame\Entity\Game'),
276
            'fields' => 'identifier',
277
            'messages' => array(
278
                'objectFound' => 'This url already exists !'
279
            )
280
        ));
281
282
        if ($game->getIdentifier() != $data['identifier']) {
283
            $identifierInput->getValidatorChain()->addValidator($noObjectExistsValidator);
284
        }
285
286
        // I must switch from original format to the Y-m-d format because this is the only one accepted by new DateTime($value)
287 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...
288
            $tmpDate = \DateTime::createFromFormat('d/m/Y', $data['publicationDate']);
289
            $data['publicationDate'] = $tmpDate->format('Y-m-d');
290
        }
291 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...
292
            $tmpDate = \DateTime::createFromFormat('d/m/Y', $data['startDate']);
293
            $data['startDate'] = $tmpDate->format('Y-m-d');
294
        }
295 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...
296
            $tmpDate = \DateTime::createFromFormat('d/m/Y', $data['endDate']);
297
            $data['endDate'] = $tmpDate->format('Y-m-d');
298
        }
299 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...
300
            $tmpDate = \DateTime::createFromFormat('d/m/Y', $data['closeDate']);
301
            $data['closeDate'] = $tmpDate->format('Y-m-d');
302
        }
303
304
        // If publicationDate is null, I update it with the startDate if not nul neither
305
        if ((! isset($data['publicationDate']) || $data['publicationDate'] == '') && (isset($data['startDate']) && $data['startDate'] != '')) {
306
            $data['publicationDate'] = $data['startDate'];
307
        }
308
309 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...
310
            $data['identifier'] = $data['title'];
311
        }
312
313
        $form->setData($data);
314
315
        // If someone want to claim... It's time to do it ! used for exemple by PlaygroundFacebook Module
316
        $result = $this->getEventManager()->trigger(__FUNCTION__ . '.validate', $this, array(
317
            'game' => $game,
318
            'data' => $data
319
        ));
320
        if (is_array($result) && ! $result[0]) {
321
            $form->get('fbAppId')->setMessages(array(
322
                'Vous devez d\'abord désinstaller l\'appli Facebook'
323
            ));
324
325
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by PlaygroundGame\Service\Game::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...
326
        }
327
328 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...
329
            if (isset($data['publicationDate']) && $data['publicationDate']) {
330
                $tmpDate = \DateTime::createFromFormat('Y-m-d', $data['publicationDate']);
331
                $data['publicationDate'] = $tmpDate->format('d/m/Y');
332
                $form->setData(array(
333
                    'publicationDate' => $data['publicationDate']
334
                ));
335
            }
336
            if (isset($data['startDate']) && $data['startDate']) {
337
                $tmpDate = \DateTime::createFromFormat('Y-m-d', $data['startDate']);
338
                $data['startDate'] = $tmpDate->format('d/m/Y');
339
                $form->setData(array(
340
                    'startDate' => $data['startDate']
341
                ));
342
            }
343
            if (isset($data['endDate']) && $data['endDate']) {
344
                $tmpDate = \DateTime::createFromFormat('Y-m-d', $data['endDate']);
345
                $data['endDate'] = $tmpDate->format('d/m/Y');
346
                $form->setData(array(
347
                    'endDate' => $data['endDate']
348
                ));
349
            }
350
            if (isset($data['closeDate']) && $data['closeDate']) {
351
                $tmpDate = \DateTime::createFromFormat('Y-m-d', $data['closeDate']);
352
                $data['closeDate'] = $tmpDate->format('d/m/Y');
353
                $form->setData(array(
354
                    'closeDate' => $data['closeDate']
355
                ));
356
            }
357
            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...
358
        }
359
360 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...
361
            ErrorHandler::start();
362
            $data['uploadMainImage']['name'] = $this->fileNewname($path, $game->getId() . "-" . $data['uploadMainImage']['name']);
363
            move_uploaded_file($data['uploadMainImage']['tmp_name'], $path . $data['uploadMainImage']['name']);
364
            $game->setMainImage($media_url . $data['uploadMainImage']['name']);
365
            ErrorHandler::stop(true);
366
        }
367
368 View Code Duplication
        if (isset($data['deleteMainImage']) && $data['deleteMainImage'] && 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...
369
            ErrorHandler::start();
370
            $image = $game->getMainImage();
371
            $image = str_replace($media_url, '', $image);
372
            unlink($path . $image);
373
            $game->setMainImage(null);
374
            ErrorHandler::stop(true);
375
        }
376
377 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...
378
            ErrorHandler::start();
379
            $data['uploadSecondImage']['name'] = $this->fileNewname($path, $game->getId() . "-" . $data['uploadSecondImage']['name']);
380
            move_uploaded_file($data['uploadSecondImage']['tmp_name'], $path . $data['uploadSecondImage']['name']);
381
            $game->setSecondImage($media_url . $data['uploadSecondImage']['name']);
382
            ErrorHandler::stop(true);
383
        }
384
385 View Code Duplication
        if (isset($data['deleteSecondImage']) && $data['deleteSecondImage'] && 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...
386
            ErrorHandler::start();
387
            $image = $game->getSecondImage();
388
            $image = str_replace($media_url, '', $image);
389
            unlink($path . $image);
390
            $game->setSecondImage(null);
391
            ErrorHandler::stop(true);
392
        }
393
394 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...
395
            ErrorHandler::start();
396
            move_uploaded_file($data['uploadStylesheet']['tmp_name'], $path . 'stylesheet_' . $game->getId() . '.css');
397
            $game->setStylesheet($media_url . 'stylesheet_' . $game->getId() . '.css');
398
            ErrorHandler::stop(true);
399
        }
400
401 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...
402
            ErrorHandler::start();
403
            $data['uploadFbShareImage']['name'] = $this->fileNewname($path, $game->getId() . "-" . $data['uploadFbShareImage']['name']);
404
            move_uploaded_file($data['uploadFbShareImage']['tmp_name'], $path . $data['uploadFbShareImage']['name']);
405
            $game->setFbShareImage($media_url . $data['uploadFbShareImage']['name']);
406
            ErrorHandler::stop(true);
407
        }
408
409 View Code Duplication
        if (isset($data['deleteFbShareImage']) && $data['deleteFbShareImage'] && 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...
410
            ErrorHandler::start();
411
            $image = $game->getFbShareImage();
412
            $image = str_replace($media_url, '', $image);
413
            unlink($path . $image);
414
            $game->setFbShareImage(null);
415
            ErrorHandler::stop(true);
416
        }
417
418 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...
419
            ErrorHandler::start();
420
421
            $extension = $this->getExtension(strtolower($data['uploadFbPageTabImage']['name']));
422
            $src = $this->getSrc($extension, $data['uploadFbPageTabImage']['tmp_name']);
423
            $this->resize($data['uploadFbPageTabImage']['tmp_name'], $extension, $path . $game->getId() . "-" . $data['uploadFbPageTabImage']['name'], $src, 111, 74);
424
425
            $game->setFbPageTabImage($media_url . $game->getId() . "-" . $data['uploadFbPageTabImage']['name']);
426
            ErrorHandler::stop(true);
427
        }
428
429 View Code Duplication
        if (isset($data['deleteFbPageTabImage']) && $data['deleteFbPageTabImage'] && 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...
430
            ErrorHandler::start();
431
            $image = $game->getFbPageTabImage();
432
            $image = str_replace($media_url, '', $image);
433
            unlink($path . $image);
434
            $game->setFbPageTabImage(null);
435
            ErrorHandler::stop(true);
436
        }
437
438
        $game = $this->getGameMapper()->update($game);
439
440
        $prize_mapper = $this->getServiceManager()->get('playgroundgame_prize_mapper');
441
        if (isset($data['prizes'])) {
442
            foreach ($data['prizes'] as $prize_data) {
443
                if (! empty($prize_data['picture_file']['tmp_name']) && ! $prize_data['picture_file']['error']) {
444 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...
445
                        $prize = $prize_mapper->findById($prize_data['id']);
446
                    } else {
447
                        $some_prizes = $prize_mapper->findBy(array(
448
                            'game' => $game,
449
                            'title' => $prize_data['title']
450
                        ));
451
                        if (count($some_prizes) == 1) {
452
                            $prize = $some_prizes[0];
453
                        } else {
454
                            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...
455
                        }
456
                    }
457
                    // Remove if existing image
458
                    if ($prize->getPicture() && file_exists($prize->getPicture())) {
459
                        unlink($prize->getPicture());
460
                        $prize->getPicture(null);
461
                    }
462
                    // Upload and set new
463
                    ErrorHandler::start();
464
                    $filename = "game-" . $game->getId() . "-prize-" . $prize->getId() . "-" . $prize_data['picture_file']['name'];
465
                    move_uploaded_file($prize_data['picture_file']['tmp_name'], $path . $filename);
466
                    $prize->setPicture($media_url . $filename);
467
                    ErrorHandler::stop(true);
468
                    $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...
469
                }
470
            }
471
        }
472
        // If I receive false, it means that the FB Id was not available anymore
473
        $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...
474
            'game' => $game
475
        ));
476
477
        return $game;
478
    }
479
480
    /**
481
     * getActiveGames
482
     *
483
     * @return Array of PlaygroundGame\Entity\Game
484
     */
485
    public function getActiveGames($displayHome = true, $classType = '', $order = '')
486
    {
487
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
488
        $today = new \DateTime("now");
489
        $today = $today->format('Y-m-d') . ' 23:59:59';
490
        $orderBy = 'g.publicationDate';
491
        if ($order != '') {
492
            $orderBy = 'g.'.$order;
493
        }
494
495
        $qb = $em->createQueryBuilder();
496
        $and = $qb->expr()->andx();
497
        $and->add(
498
            $qb->expr()->orX(
499
                $qb->expr()->lte('g.publicationDate', ':date'),
500
                $qb->expr()->isNull('g.publicationDate')
501
            )
502
        );
503
        $and->add(
504
            $qb->expr()->orX(
505
                $qb->expr()->gte('g.closeDate', ':date'),
506
                $qb->expr()->isNull('g.closeDate')
507
            )
508
        );
509
        $qb->setParameter('date', $today);
510
        
511
        $and->add($qb->expr()->eq('g.active', '1'));
512
        $and->add($qb->expr()->eq('g.broadcastPlatform', '1'));
513
        
514
        if ($classType != '') {
515
            $and->add($qb->expr()->eq('g.classType', ':classType'));
516
            $qb->setParameter('classType', $classType);
517
        }
518
        
519
        if ($displayHome) {
520
            $and->add($qb->expr()->eq('g.displayHome', true));
521
        }
522
        
523
        $qb->select('g')
524
        ->from('PlaygroundGame\Entity\Game', 'g')
525
        ->where($and)
526
        ->orderBy($orderBy, 'DESC');
527
        
528
        $query = $qb->getQuery();
529
        $games = $query->getResult();
530
        
531
        // je les classe par date de publication (date comme clé dans le tableau afin de pouvoir merger les objets
532
        // de type article avec le même procédé en les classant naturellement par date asc ou desc
533
        $arrayGames = array();
534 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...
535
            if ($game->getPublicationDate()) {
536
                $key = $game->getPublicationDate()->format('Ymd') . $game->getUpdatedAt()->format('Ymd') . '-' . $game->getId();
537
            } elseif ($game->getStartDate()) {
538
                $key = $game->getStartDate()->format('Ymd') . $game->getUpdatedAt()->format('Ymd') . '-' . $game->getId();
539
            } else {
540
                $key = $game->getUpdatedAt()->format('Ymd') . $game->getUpdatedAt()->format('Ymd') . '-' . $game->getId();
541
            }
542
            $arrayGames[$key] = $game;
543
        }
544
545
        return $arrayGames;
546
    }
547
548
    /**
549
     * getAvailableGames : Games OnLine and not already played by $user
550
     *
551
     * @return Array of PlaygroundGame\Entity\Game
552
     */
553
    public function getAvailableGames($user, $maxResults = 2)
554
    {
555
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
556
        $today = new \DateTime("now");
557
        $today = $today->format('Y-m-d') . ' 23:59:59';
558
559
        // Game active with a start_date before today (or without start_date) and end_date after today (or without end-date)
560
        $query = $em->createQuery('SELECT g FROM PlaygroundGame\Entity\Game g
561
                WHERE NOT EXISTS (SELECT l FROM PlaygroundGame\Entity\Entry l WHERE l.game = g AND l.user = :user)
562
                AND (g.startDate <= :date OR g.startDate IS NULL)
563
                AND (g.endDate >= :date OR g.endDate IS NULL)
564
                AND g.active = 1 AND g.broadcastPlatform = 1
565
                ORDER BY g.startDate ASC');
566
        $query->setParameter('date', $today);
567
        $query->setParameter('user', $user);
568
        $query->setMaxResults($maxResults);
569
        $games = $query->getResult();
570
571
        return $games;
572
    }
573
574 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...
575
    {
576
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
577
578
        $qb = $em->createQueryBuilder();
579
        $qb->select('
580
            e.id,
581
            u.username,
582
            u.title,
583
            u.firstname,
584
            u.lastname,
585
            u.email,
586
            u.optin,
587
            u.optinPartner,
588
            u.address,
589
            u.address2,
590
            u.postalCode,
591
            u.city,
592
            u.telephone,
593
            u.mobile,
594
            u.created_at,
595
            u.dob,
596
            e.winner,
597
            e.socialShares,
598
            e.playerData,
599
            e.updated_at
600
            ')
601
            ->from('PlaygroundGame\Entity\Entry', 'e')
602
            ->leftJoin('e.user', 'u')
603
            ->where($qb->expr()->eq('e.game', ':game'));
604
        
605
        $qb->setParameter('game', $game);
606
607
        return $qb->getQuery();
608
    }
609
610
    public function getEntriesHeader($game)
611
    {
612
        if ($game->getPlayerForm()) {
613
            $formPV = json_decode($game->getPlayerForm()->getForm(), true);
614
            $header = array('id'=> 1);
615 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...
616
                foreach ($element as $k => $v) {
617
                    if ($k !== 'form_properties') {
618
                        $header[$v[0]['name']] = 1;
619
                    }
620
                }
621
            }
622
        } else {
623
            $header = array(
624
                'id' => 1,
625
                'username' => 1,
626
                'title' => 1,
627
                'firstname' => 1,
628
                'lastname' => 1,
629
                'email' => 1,
630
                'optin' => 1,
631
                'optinPartner' => 1,
632
                'address' => 1,
633
                'address2' => 1,
634
                'postalCode' => 1,
635
                'city' => 1,
636
                'telephone' => 1,
637
                'mobile' => 1,
638
                'created_at' => 1,
639
                'dob' => 1,
640
                'winner' => 1
641
            );
642
        }
643
        $header['winner'] = 1;
644
        $header['socialShares'] = 1;
645
        $header['updated_at'] = 1;
646
647
        return $header;
648
    }
649
650
    /**
651
    * getGameEntries : I create an array of entries based on playerData + header
652
    *
653
    * @return Array of PlaygroundGame\Entity\Game
654
    */
655
    public function getGameEntries($header, $entries, $game)
656
    {
657
        $header = $this->getEntriesHeader($game);
658
659
        $results = array();
660
661
        foreach ($entries as $k => $entry) {
662
            $entryData = json_decode($entry['playerData'], true);
663 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...
664
                if (isset($entryData[$key])) {
665
                    $results[$k][$key] = (is_array($entryData[$key]))?implode(', ', $entryData[$key]):$entryData[$key];
666
                } elseif (array_key_exists($key, $entry)) {
667
                    $results[$k][$key] = ($entry[$key] instanceof \DateTime)?$entry[$key]->format('Y-m-d'):$entry[$key];
668
                } else {
669
                    $results[$k][$key] = '';
670
                }
671
            }
672
        }
673
674
        return $results;
675
    }
676
677
    /**
678
     * getActiveSliderGames
679
     *
680
     * @return Array of PlaygroundGame\Entity\Game
681
     */
682
    public function getActiveSliderGames()
683
    {
684
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
685
        $today = new \DateTime("now");
686
        $today = $today->format('Y-m-d') . ' 23:59:59';
687
688
        // Game active with a start_date before today (or without start_date) and end_date after today (or without end-date)
689
        $query = $em->createQuery('SELECT g FROM PlaygroundGame\Entity\Game g
690
            WHERE (g.publicationDate <= :date OR g.publicationDate IS NULL)
691
            AND (g.closeDate >= :date OR g.closeDate IS NULL)
692
            AND g.active = true AND g.broadcastPlatform = 1 AND g.pushHome = true');
693
        $query->setParameter('date', $today);
694
        $games = $query->getResult();
695
696
        // je les classe par date de publication (date comme clé dans le tableau afin de pouvoir merger les objets
697
        // de type article avec le même procédé en les classant naturellement par date asc ou desc
698
        $arrayGames = array();
699 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...
700
            if ($game->getPublicationDate()) {
701
                $key = $game->getPublicationDate()->format('Ymd') . $game->getUpdatedAt()->format('Ymd') . '-' . $game->getId();
702
            } elseif ($game->getStartDate()) {
703
                $key = $game->getStartDate()->format('Ymd') . $game->getUpdatedAt()->format('Ymd') . '-' . $game->getId();
704
            } else {
705
                $key = $game->getUpdatedAt()->format('Ymd') . $game->getUpdatedAt()->format('Ymd') . '-' . $game->getId();
706
            }
707
            $arrayGames[$key] = $game;
708
        }
709
710
        return $arrayGames;
711
    }
712
713
    /**
714
     * getPrizeCategoryGames
715
     *
716
     * @return Array of PlaygroundGame\Entity\Game
717
     */
718 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...
719
    {
720
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
721
722
        $query = $em->createQuery('SELECT g FROM PlaygroundGame\Entity\Game g
723
            WHERE (g.prizeCategory = :categoryid AND g.broadcastPlatform = 1)
724
            ORDER BY g.publicationDate DESC');
725
        $query->setParameter('categoryid', $categoryid);
726
        $games = $query->getResult();
727
728
        return $games;
729
    }
730
731
    public function checkGame($identifier, $checkIfStarted = true)
732
    {
733
        $gameMapper = $this->getGameMapper();
734
735
        if (! $identifier) {
736
            return false;
737
        }
738
739
        $game = $gameMapper->findByIdentifier($identifier);
740
741
        // the game has not been found
742
        if (! $game) {
743
            return false;
744
        }
745
746
        if ($this->getServiceManager()
747
            ->get('Application')
748
            ->getMvcEvent()
749
            ->getRouteMatch()
750
            ->getParam('channel') === 'preview' && $this->isAllowed('game', 'edit')) {
751
            $game->setActive(true);
752
            $game->setStartDate(null);
753
            $game->setEndDate(null);
754
            $game->setPublicationDate(null);
755
            $game->setBroadcastPlatform(true);
756
757
            // I don't want the game to be updated through any update during the preview mode. I mark it as readonly for Doctrine
758
            $this->getServiceManager()
759
                ->get('doctrine.entitymanager.orm_default')
760
                ->getUnitOfWork()
761
                ->markReadOnly($game);
762
            return $game;
763
        }
764
765
        // The game is inactive
766
        if (! $game->getActive()) {
767
            return false;
768
        }
769
770
        // the game has not begun yet
771
        if (! $game->isOpen()) {
772
            return false;
773
        }
774
775
        // the game is finished and closed
776
        if (! $game->isStarted() && $checkIfStarted) {
777
            return false;
778
        }
779
780
        return $game;
781
    }
782
783
    /**
784
     * Return the last entry of the user on this game, if it exists.
785
     * An entry can be associated to :
786
     * - A user account (a real one, linked to PlaygroundUser
787
     * - An anonymous Identifier (based on one value of playerData (generally email))
788
     * - A cookie set on the player device (the less secure)
789
     * If the active param is set, it can check if the entry is active or not.
790
     * If the bonus param is set, it can check if the entry is a bonus or not.
791
     *
792
     * @param unknown $game
793
     * @param string $user
794
     * @param boolean $active
795
     * @param boolean $bonus
796
     * @return boolean
797
     */
798
    public function checkExistingEntry($game, $user = null, $active = null, $bonus = null)
799
    {
800
        $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...
801
        $search = array('game'  => $game);
802
803
        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...
804
            $search['user'] = $user;
805
        } elseif ($this->getAnonymousIdentifier()) {
806
            $search['anonymousIdentifier'] = $this->getAnonymousIdentifier();
807
            $search['user'] = null;
808
        } else {
809
            $search['anonymousId'] = $this->getAnonymousId();
810
            $search['user'] = null;
811
        }
812
        
813
        if (! is_null($active)) {
814
            $search['active'] = $active;
815
        }
816
        if (! is_null($bonus)) {
817
            $search['bonus'] = $bonus;
818
        }
819
820
        $entry = $this->getEntryMapper()->findOneBy($search);
821
822
        return $entry;
823
    }
824
825
    /*
826
    * This function updates the entry with the player data after checking 
827
    * that the data are compliant with the formUser Game attribute
828
    *
829
    * The $data has to be a json object
830
    */
831
    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...
832
    {
833
        $form = $this->createFormFromJson($game->getPlayerForm()->getForm(), 'playerForm');
834
        $form->setData($data);
835
836
        if (!$mandatory) {
837
            $filter = $form->getInputFilter();
838
            foreach ($form->getElements() as $element) {
839
                try {
840
                    $elementInput = $filter->get($element->getName());
841
                    $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...
842
                    $form->get($element->getName())->setAttribute('required', false);
843
                } 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...
844
                }
845
            }
846
        }
847
848
        if ($form->isValid()) {
849
            $dataJson = json_encode($form->getData());
850
851
            if ($game->getAnonymousAllowed() && $game->getAnonymousIdentifier() && isset($data[$game->getAnonymousIdentifier()])) {
852
                $session = new \Zend\Session\Container('anonymous_identifier');
853
                if (empty($session->offsetGet('anonymous_identifier'))) {
854
                    $anonymousIdentifier = $data[$game->getAnonymousIdentifier()];
855
                
856
                    $entry->setAnonymousIdentifier($anonymousIdentifier);
857
                
858
                    // I must transmit this info during the whole game workflow
859
                    $session->offsetSet('anonymous_identifier', $anonymousIdentifier);
860
                }
861
            }
862
863
            $entry->setPlayerData($dataJson);
864
            $this->getEntryMapper()->update($entry);
865
        } else {
866
            return false;
867
        }
868
869
        return true;
870
    }
871
872
873
    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...
874
    {
875
        // If on Facebook, check if you have to be a FB fan to play the game
876
        $session = new Container('facebook');
877
878
        if ($session->offsetExists('signed_request')) {
879
            // I'm on Facebook
880
            $sr = $session->offsetGet('signed_request');
881
            if ($sr['page']['liked'] == 1) {
882
                return true;
883
            }
884
        } else {
885
            // I'm not on Facebook
886
            return true;
887
        }
888
889
        return false;
890
    }
891
    
892
    public function getAnonymousIdentifier()
893
    {
894
        if (is_null($this->anonymousIdentifier)) {
895
            // If on Facebook, check if you have to be a FB fan to play the game
896
            $session = new Container('anonymous_identifier');
897
            
898
            if ($session->offsetExists('anonymous_identifier')) {
899
                $this->anonymousIdentifier = $session->offsetGet('anonymous_identifier');
900
            } else {
901
                $this->anonymousIdentifier = false;
902
            }
903
        }
904
    
905
        return $this->anonymousIdentifier;
906
    }
907
908
    /**
909
     * errors :
910
     * -1 : user not connected
911
     * -2 : limit entry games for this user reached
912
     *
913
     * @param \PlaygroundGame\Entity\Game $game
914
     * @param \PlaygroundUser\Entity\UserInterface $user
915
     * @return number unknown
916
     */
917
    public function play($game, $user)
918
    {
919
920
        // certaines participations peuvent rester ouvertes. On autorise alors le joueur à reprendre là ou il en était
921
        // par exemple les postvote...
922
        $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...
923
924
        if (! $entry) {
925
            if ($this->hasReachedPlayLimit($game, $user)) {
926
                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...
927
            }
928
929
            $entry = new Entry();
930
            $entry->setGame($game);
931
            $entry->setUser($user);
932
            $entry->setPoints(0);
933
            $entry->setIp($this->getIp());
934
            $entry->setAnonymousId($this->getAnonymousId());
935
            if ($this->getAnonymousIdentifier()) {
936
                $entry->setAnonymousIdentifier($this->getAnonymousIdentifier());
937
            }
938
939
            $entry = $this->getEntryMapper()->insert($entry);
940
            $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
941
                'user' => $user,
942
                'game' => $game,
943
                'entry' => $entry
944
            ));
945
        }
946
947
        return $entry;
948
    }
949
950
    /**
951
     * @param \PlaygroundGame\Entity\Game $game
952
     * @param \PlaygroundUser\Entity\UserInterface $user
953
     */
954
    public function hasReachedPlayLimit($game, $user)
955
    {
956
        // Is there a limitation on the game ?
957
        $limitAmount = $game->getPlayLimit();
958
        if ($limitAmount) {
959
            $limitScale = $game->getPlayLimitScale();
960
            $userEntries = $this->findLastEntries($game, $user, $limitScale);
961
962
            // player has reached the game limit
963
            if ($userEntries >= $limitAmount) {
964
                return true;
965
            }
966
        }
967
        return false;
968
    }
969
    
970
    public function findLastEntries($game, $user, $limitScale)
971
    {
972
        $limitDate = $this->getLimitDate($limitScale);
973
974
        if ($user) {
975
            return $this->getEntryMapper()->findLastEntriesByUser($game, $user, $limitDate);
976
        } elseif ($this->getAnonymousIdentifier()) {
977
            return $this->getEntryMapper()->findLastEntriesByAnonymousIdentifier($game, $this->getAnonymousIdentifier(), $limitDate);
978
        } else {
979
            return $this->getEntryMapper()->findLastEntriesByIp($game, $this->getIp(), $limitDate);
980
        }
981
    }
982
983
    /**
984
    *
985
    *
986
    */
987
    public function getLimitDate($limitScale)
988
    {
989
        $now = new \DateTime("now");
990
        switch ($limitScale) {
991
            case 'always':
992
                $interval = 'P100Y';
993
                $now->sub(new \DateInterval($interval));
994
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
995
                break;
996
            case 'day':
997
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
998
                break;
999
            case 'week':
1000
                $interval = 'P7D';
1001
                $now->sub(new \DateInterval($interval));
1002
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
1003
                break;
1004
            case 'month':
1005
                $interval = 'P1M';
1006
                $now->sub(new \DateInterval($interval));
1007
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
1008
                break;
1009
            case 'year':
1010
                $interval = 'P1Y';
1011
                $now->sub(new \DateInterval($interval));
1012
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
1013
                break;
1014
            default:
1015
                $interval = 'P100Y';
1016
                $now->sub(new \DateInterval($interval));
1017
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
1018
        }
1019
1020
        return $dateLimit;
1021
    }
1022
1023
    public function findLastActiveEntry($game, $user)
1024
    {
1025
        return $this->checkExistingEntry($game, $user, true);
1026
    }
1027
1028
    public function findLastInactiveEntry($game, $user)
1029
    {
1030
        return $this->checkExistingEntry($game, $user, false, false);
1031
    }
1032
1033
    public function findLastEntry($game, $user)
1034
    {
1035
        return $this->checkExistingEntry($game, $user, null, false);
1036
    }
1037
1038
    public function sendShareMail($data, $game, $user, $entry, $template = 'share_game', $topic = null, $userTimer = array())
1039
    {
1040
        $mailService = $this->getServiceManager()->get('playgroundgame_message');
1041
        $mailSent = false;
1042
        $from = $this->getOptions()->getEmailFromAddress();
1043
        $subject = $this->getOptions()->getShareSubjectLine();
1044
        $renderer = $this->getServiceManager()->get('Zend\View\Renderer\RendererInterface');
1045
        if ($user) {
1046
            $email = $user->getEmail();
1047
        } elseif ($entry->getAnonymousIdentifier()) {
1048
            $email = $entry->getAnonymousIdentifier();
1049
        } else {
1050
            $email = $from;
1051
        }
1052
        $skinUrl = $renderer->url(
1053
            'frontend',
1054
            array('channel' => $this->getServiceManager()
1055
                ->get('Application')
1056
                ->getMvcEvent()
1057
                ->getRouteMatch()
1058
                ->getParam('channel')
1059
            ),
1060
            array(
1061
                'force_canonical' => true
1062
            )
1063
        );
1064
        $secretKey = strtoupper(substr(sha1(uniqid('pg_', true) . '####' . time()), 0, 15));
1065
1066
        if (! $topic) {
1067
            $topic = $game->getTitle();
1068
        }
1069
1070
        $shares = json_decode($entry->getSocialShares(), true);
1071
        
1072
        if ($data['email1']) {
1073
            $mailSent = true;
1074
            $message = $mailService->createHtmlMessage($from, $data['email1'], $subject, 'playground-game/email/' . $template, array(
1075
                'game' => $game,
1076
                'email' => $email,
1077
                'secretKey' => $secretKey,
1078
                'skinUrl' => $skinUrl,
1079
                'userTimer' => $userTimer
1080
            ));
1081
            $mailService->send($message);
1082
            
1083
            if (!isset($shares['mail'])) {
1084
                $shares['mail'] = 1;
1085
            } else {
1086
                $shares['mail'] += 1;
1087
            }
1088
        }
1089
        if ($data['email2'] && $data['email2'] != $data['email1']) {
1090
            $mailSent = true;
1091
            $message = $mailService->createHtmlMessage($from, $data['email2'], $subject, 'playground-game/email/' . $template, array(
1092
                'game' => $game,
1093
                'email' => $email,
1094
                'secretKey' => $secretKey,
1095
                'skinUrl' => $skinUrl,
1096
                'userTimer' => $userTimer
1097
            ));
1098
            $mailService->send($message);
1099
            
1100
            if (!isset($shares['mail'])) {
1101
                $shares['mail'] = 1;
1102
            } else {
1103
                $shares['mail'] += 1;
1104
            }
1105
        }
1106
        if ($data['email3'] && $data['email3'] != $data['email2'] && $data['email3'] != $data['email1']) {
1107
            $mailSent = true;
1108
            $message = $mailService->createHtmlMessage($from, $data['email3'], $subject, 'playground-game/email/' . $template, array(
1109
                'game' => $game,
1110
                'email' => $email,
1111
                'secretKey' => $secretKey,
1112
                'skinUrl' => $skinUrl,
1113
                'userTimer' => $userTimer
1114
            ));
1115
            $mailService->send($message);
1116
            
1117
            if (!isset($shares['mail'])) {
1118
                $shares['mail'] = 1;
1119
            } else {
1120
                $shares['mail'] += 1;
1121
            }
1122
        }
1123
        if ($data['email4'] && $data['email4'] != $data['email3'] && $data['email4'] != $data['email2'] && $data['email4'] != $data['email1']) {
1124
            $mailSent = true;
1125
            $message = $mailService->createHtmlMessage($from, $data['email4'], $subject, 'playground-game/email/' . $template, array(
1126
                'game' => $game,
1127
                'email' => $email,
1128
                'secretKey' => $secretKey,
1129
                'skinUrl' => $skinUrl,
1130
                'userTimer' => $userTimer
1131
            ));
1132
            $mailService->send($message);
1133
        
1134
            if (!isset($shares['mail'])) {
1135
                $shares['mail'] = 1;
1136
            } else {
1137
                $shares['mail'] += 1;
1138
            }
1139
        }
1140
        if ($data['email5'] && $data['email5'] != $data['email4'] && $data['email5'] != $data['email3'] && $data['email5'] != $data['email2'] && $data['email5'] != $data['email1']) {
1141
            $mailSent = true;
1142
            $message = $mailService->createHtmlMessage($from, $data['email5'], $subject, 'playground-game/email/' . $template, array(
1143
                'game' => $game,
1144
                'email' => $email,
1145
                'secretKey' => $secretKey,
1146
                'skinUrl' => $skinUrl,
1147
                'userTimer' => $userTimer
1148
            ));
1149
            $mailService->send($message);
1150
        
1151
            if (!isset($shares['mail'])) {
1152
                $shares['mail'] = 1;
1153
            } else {
1154
                $shares['mail'] += 1;
1155
            }
1156
        }
1157
        if ($mailSent) {
1158
            $sharesJson = json_encode($shares);
1159
            $entry->setSocialShares($sharesJson);
1160
            $entry = $this->getEntryMapper()->update($entry);
1161
            
1162
            $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1163
                'user' => $user,
1164
                'topic' => $topic,
1165
                'secretKey' => $secretKey,
1166
                'game' => $game,
1167
                'entry' => $entry
1168
            ));
1169
1170
            return true;
1171
        }
1172
1173
        return false;
1174
    }
1175
1176
    public function sendResultMail($game, $user, $entry, $template = 'entry', $prize = null)
1177
    {
1178
        $mailService = $this->getServiceManager()->get('playgroundgame_message');
1179
        $from = $this->getOptions()->getEmailFromAddress();
1180
        if ($user) {
1181
            $to = $user->getEmail();
1182
        } elseif ($entry->getAnonymousIdentifier()) {
1183
            $to = $entry->getAnonymousIdentifier();
1184
        } else {
1185
            return false;
1186
        }
1187
        $subject = $game->getTitle();
1188
        $renderer = $this->getServiceManager()->get('Zend\View\Renderer\RendererInterface');
1189
        $skinUrl = $renderer->url(
1190
            'frontend',
1191
            array('channel' => $this->getServiceManager()
1192
                ->get('Application')
1193
                ->getMvcEvent()
1194
                ->getRouteMatch()
1195
                ->getParam('channel')
1196
            ),
1197
            array(
1198
                'force_canonical' => true
1199
            )
1200
        );
1201
        $message = $mailService->createHtmlMessage($from, $to, $subject, 'playground-game/email/' . $template, array(
1202
            'game' => $game,
1203
            'entry' => $entry,
1204
            'skinUrl' => $skinUrl,
1205
            'prize' => $prize
1206
        ));
1207
        $mailService->send($message);
1208
    }
1209
1210
    public function sendGameMail($game, $user, $post, $template = 'postvote')
1211
    {
1212
        $mailService = $this->getServiceManager()->get('playgroundgame_message');
1213
        $from = $this->getOptions()->getEmailFromAddress();
1214
        $to = $user->getEmail();
1215
        $subject = $this->getOptions()->getParticipationSubjectLine();
1216
        $renderer = $this->getServiceManager()->get('Zend\View\Renderer\RendererInterface');
1217
        $skinUrl = $renderer->url(
1218
            'frontend',
1219
            array('channel' => $this->getServiceManager()
1220
                ->get('Application')
1221
                ->getMvcEvent()
1222
                ->getRouteMatch()
1223
                ->getParam('channel')
1224
            ),
1225
            array(
1226
                'force_canonical' => true
1227
            )
1228
        );
1229
1230
        $message = $mailService->createHtmlMessage($from, $to, $subject, 'playground-game/email/' . $template, array(
1231
            'game' => $game,
1232
            'post' => $post,
1233
            'skinUrl' => $skinUrl
1234
        ));
1235
        $mailService->send($message);
1236
    }
1237
1238 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...
1239
    {
1240
        $topic = $game->getTitle();
1241
        
1242
        $shares = json_decode($entry->getSocialShares(), true);
1243
        if (!isset($shares['fbwall'])) {
1244
            $shares['fbwall'] = 1;
1245
        } else {
1246
            $shares['fbwall'] += 1;
1247
        }
1248
        $sharesJson = json_encode($shares);
1249
        $entry->setSocialShares($sharesJson);
1250
        $entry = $this->getEntryMapper()->update($entry);
1251
        
1252
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1253
            'user' => $user,
1254
            'game' => $game,
1255
            'secretKey' => $secretKey,
1256
            'topic' => $topic,
1257
            'entry' => $entry
1258
        ));
1259
1260
        return true;
1261
    }
1262
1263
    public function postFbRequest($secretKey, $game, $user, $entry, $to)
1264
    {
1265
        $shares = json_decode($entry->getSocialShares(), true);
1266
        $to = explode(',', $to);
1267
        if (!isset($shares['fbrequest'])) {
1268
            $shares['fbrequest'] = count($to);
1269
        } else {
1270
            $shares['fbrequest'] += count($to);
1271
        }
1272
        $sharesJson = json_encode($shares);
1273
        $entry->setSocialShares($sharesJson);
1274
        $entry = $this->getEntryMapper()->update($entry);
1275
        
1276
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1277
            'user' => $user,
1278
            'game' => $game,
1279
            'secretKey' => $secretKey,
1280
            'entry' => $entry,
1281
            'invites' => count($to)
1282
        ));
1283
1284
        return true;
1285
    }
1286
1287 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...
1288
    {
1289
        $topic = $game->getTitle();
1290
1291
        $shares = json_decode($entry->getSocialShares(), true);
1292
        if (!isset($shares['fbrequest'])) {
1293
            $shares['tweet'] = 1;
1294
        } else {
1295
            $shares['tweet'] += 1;
1296
        }
1297
        $sharesJson = json_encode($shares);
1298
        $entry->setSocialShares($sharesJson);
1299
        $entry = $this->getEntryMapper()->update($entry);
1300
        
1301
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1302
            'user' => $user,
1303
            'game' => $game,
1304
            'secretKey' => $secretKey,
1305
            'topic' => $topic,
1306
            'entry' => $entry
1307
        ));
1308
1309
        return true;
1310
    }
1311
1312 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...
1313
    {
1314
        $topic = $game->getTitle();
1315
        
1316
        $shares = json_decode($entry->getSocialShares(), true);
1317
        if (!isset($shares['fbrequest'])) {
1318
            $shares['google'] = 1;
1319
        } else {
1320
            $shares['google'] += 1;
1321
        }
1322
        $sharesJson = json_encode($shares);
1323
        $entry->setSocialShares($sharesJson);
1324
        $entry = $this->getEntryMapper()->update($entry);
1325
1326
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1327
            'user' => $user,
1328
            'game' => $game,
1329
            'secretKey' => $secretKey,
1330
            'topic' => $topic,
1331
            'entry' => $entry
1332
        ));
1333
1334
        return true;
1335
    }
1336
1337
    /**
1338
     * Is it possible to trigger a bonus entry ?
1339
     *
1340
     * @param unknown_type $game
1341
     * @param unknown_type $user
1342
     */
1343
    public function allowBonus($game, $user)
1344
    {
1345
        if (! $game->getPlayBonus() || $game->getPlayBonus() == 'none') {
1346
            return false;
1347
        } elseif ($game->getPlayBonus() == 'one') {
1348
            if ($this->getEntryMapper()->findOneBy(array(
1349
                'game' => $game,
1350
                'user' => $user,
1351
                'bonus' => 1
1352
            ))) {
1353
                return false;
1354
            } else {
1355
                return true;
1356
            }
1357
        } elseif ($game->getPlayBonus() == 'per_entry') {
1358
            return $this->getEntryMapper()->checkBonusEntry($game, $user);
1359
        }
1360
1361
        return false;
1362
    }
1363
1364
    public function addAnotherEntry($game, $user, $winner = 0)
1365
    {
1366
        $entry = new Entry();
1367
        $entry->setGame($game);
1368
        $entry->setUser($user);
1369
        $entry->setPoints(0);
1370
        $entry->setIp($this->getIp());
1371
        $entry->setActive(0);
1372
        $entry->setBonus(1);
1373
        $entry->setWinner($winner);
1374
        $entry = $this->getEntryMapper()->insert($entry);
1375
1376
        return $entry;
1377
    }
1378
1379
    /**
1380
     * This bonus entry doesn't give points nor badges
1381
     * It's just there to increase the chances during the Draw
1382
     * Old Name playBonus
1383
     *
1384
     * @param PlaygroundGame\Entity\Game $game
1385
     * @param unknown $user
1386
     * @return boolean unknown
1387
     */
1388
    public function addAnotherChance($game, $user, $winner = 0)
1389
    {
1390
        if ($this->allowBonus($game, $user)) {
1391
            $this->addAnotherEntry($game, $user, $winner);
1392
1393
            return true;
1394
        }
1395
1396
        return false;
1397
    }
1398
1399
    /**
1400
     * This bonus entry doesn't give points nor badges but can play again
1401
     *
1402
     * @param PlaygroundGame\Entity\Game $game
1403
     * @param user $user
1404
     * @return boolean unknown
1405
     */
1406
    public function playAgain($game, $user, $winner = 0)
1407
    {
1408
        if ($this->allowBonus($game, $user)) {
1409
            $entry = $this->addAnotherEntry($game, $user, $winner);
1410
            $entry->setActive(1);
1411
            $entry = $this->getEntryMapper()->update($entry);
1412
            if ($entry->getActive() == 1) {
1413
                return true;
1414
            }
1415
        }
1416
1417
        return false;
1418
    }
1419
1420 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...
1421
    {
1422
        $configuration = require 'config/application.config.php';
1423
        $smConfig = isset($configuration['service_manager']) ? $configuration['service_manager'] : array();
1424
        $sm = new \Zend\ServiceManager\ServiceManager(new \Zend\Mvc\Service\ServiceManagerConfig($smConfig));
1425
        $sm->setService('ApplicationConfig', $configuration);
1426
        $sm->get('ModuleManager')->loadModules();
1427
        $sm->get('Application')->bootstrap();
1428
1429
        $mailService = $sm->get('playgrounduser_message');
1430
        $gameService = $sm->get('playgroundgame_quiz_service');
1431
1432
        $from = "[email protected]";
1433
        $subject = "sujet game";
1434
1435
        $to = "[email protected]";
1436
1437
        $game = $gameService->checkGame('qooqo');
1438
1439
        $message = $mailService->createTextMessage($from, $to, $subject, 'playground-game/email/share_reminder', array(
1440
            'game' => $game
1441
        ));
1442
1443
        $mailService->send($message);
1444
    }
1445
1446
    /**
1447
     * @param string $path
1448
     */
1449
    public function uploadFile($path, $file)
1450
    {
1451
        $err = $file["error"];
1452
        $message = '';
1453
        if ($err > 0) {
1454
            switch ($err) {
1455
                case '1':
1456
                    $message .= 'Max file size exceeded. (php.ini)';
1457
                    break;
1458
                case '2':
1459
                    $message .= 'Max file size exceeded.';
1460
                    break;
1461
                case '3':
1462
                    $message .= 'File upload was only partial.';
1463
                    break;
1464
                case '4':
1465
                    $message .= 'No file was attached.';
1466
                    break;
1467
                case '7':
1468
                    $message .= 'File permission denied.';
1469
                    break;
1470
                default:
1471
                    $message .= 'Unexpected error occurs.';
1472
            }
1473
1474
            return $err;
1475
        } else {
1476
            $fileNewname = $this->fileNewname($path, $file['name'], true);
1477
1478
            if (isset($file["base64"])) {
1479
                list(, $img) = explode(',', $file["base64"]);
1480
                $img = str_replace(' ', '+', $img);
1481
                $im = base64_decode($img);
1482
                if ($im !== false) {
1483
                    // getimagesizefromstring
1484
                    file_put_contents($path . $fileNewname, $im);
1485
                } else {
1486
                    return 1;
1487
                }
1488
1489
                return $fileNewname;
1490
            } else {
1491
                $adapter = new \Zend\File\Transfer\Adapter\Http();
1492
                // 1Mo
1493
                $size = new Size(array(
1494
                    'max' => 1024000
1495
                ));
1496
                $is_image = new IsImage('jpeg,png,gif,jpg');
1497
                $adapter->setValidators(array(
1498
                    $size,
1499
                    $is_image
1500
                ), $fileNewname);
1501
1502
                if (! $adapter->isValid()) {
1503
                    return false;
1504
                }
1505
1506
                @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...
1507
            }
1508
1509
            
1510
            if (class_exists("Imagick")) {
1511
                $ext = pathinfo($fileNewname, PATHINFO_EXTENSION);
1512
                $img = new \Imagick($path . $fileNewname);
1513
                $img->cropThumbnailImage(100, 100);
1514
                $img->setImageCompression(\Imagick::COMPRESSION_JPEG);
1515
                $img->setImageCompressionQuality(75);
1516
                // Strip out unneeded meta data
1517
                $img->stripImage();
1518
                $img->writeImage($path . str_replace('.'.$ext, '-thumbnail.'.$ext, $fileNewname));
1519
                ErrorHandler::stop(true);
1520
            }
1521
        }
1522
1523
        return $fileNewname;
1524
    }
1525
1526
    /**
1527
     * @param string $path
1528
     */
1529
    public function fileNewname($path, $filename, $generate = false)
1530
    {
1531
        $sanitize = new Sanitize();
1532
        $name = $sanitize->filter($filename);
1533
        $newpath = $path . $name;
1534
1535
        if ($generate) {
1536
            if (file_exists($newpath)) {
1537
                $filename = pathinfo($name, PATHINFO_FILENAME);
1538
                $ext = pathinfo($name, PATHINFO_EXTENSION);
1539
1540
                $name = $filename . '_' . rand(0, 99) . '.' . $ext;
1541
            }
1542
        }
1543
1544
        unset($sanitize);
1545
1546
        return $name;
1547
    }
1548
1549
    /**
1550
     * This function returns the list of games, order by $type
1551
     */
1552
    public function getQueryGamesOrderBy($type = 'createdAt', $order = 'DESC')
1553
    {
1554
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
1555
        $today = new \DateTime("now");
1556
        $today = $today->format('Y-m-d') . ' 23:59:59';
1557
1558
        $onlineGames = '(
1559
            (
1560
                CASE WHEN (
1561
                    g.active = 1
1562
                    AND g.broadcastPlatform = 1
1563
                    AND (g.startDate <= :date OR g.startDate IS NULL)
1564
                    AND (g.closeDate >= :date OR g.closeDate IS NULL)
1565
                ) THEN 1 ELSE 0 END
1566
            ) +
1567
            (
1568
                CASE WHEN (
1569
                    g.active = 0
1570
                    AND (g.broadcastPlatform = 0 OR g.broadcastPlatform IS NULL)
1571
                    AND g.startDate > :date
1572
                    AND g.closeDate < :date
1573
                ) THEN 1 ELSE 0 END
1574
            )
1575
        )';
1576
1577
        $qb = $em->createQueryBuilder();
1578
        $qb->select('g')->from('PlaygroundGame\Entity\Game', 'g');
1579
        
1580
        switch ($type) {
1581
            case 'startDate':
1582
                $qb->orderBy('g.startDate', $order);
1583
                break;
1584
            case 'activeGames':
1585
                $qb->orderBy('g.active', $order);
1586
                break;
1587
            case 'onlineGames':
1588
                $qb->orderBy($onlineGames, $order);
1589
                $qb->setParameter('date', $today);
1590
                break;
1591
            case 'createdAt':
1592
                $qb->orderBy('g.createdAt', $order);
1593
                break;
1594
        }
1595
1596
        $query = $qb->getQuery();
1597
1598
        return $query;
1599
    }
1600
1601
    public function draw($game)
1602
    {
1603
        $total = $game->getWinners();
1604
1605
        // I Have to know what is the User Class used
1606
        $zfcUserOptions = $this->getServiceManager()->get('zfcuser_module_options');
1607
        $userClass = $zfcUserOptions->getUserEntityClass();
1608
1609
        $result = $this->getEntryMapper()->draw($game, $userClass, $total);
1610
1611
        foreach ($result as $e) {
1612
            $e->setWinner(1);
1613
            $e = $this->getEntryMapper()->update($e);
1614
            $this->getEventManager()->trigger('win_lottery.post', $this, array(
1615
                'user' => $e->getUser(),
1616
                'game' => $game,
1617
                'entry' => $e
1618
            ));
1619
        }
1620
1621
        return $result;
1622
    }
1623
1624
    /**
1625
     * getGameMapper
1626
     *
1627
     * @return GameMapperInterface
1628
     */
1629 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...
1630
    {
1631
        if (null === $this->gameMapper) {
1632
            $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...
1633
        }
1634
1635
        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 1635 which is incompatible with the return type documented by PlaygroundGame\Service\Game::getGameMapper of type PlaygroundGame\Mapper\GameInterface.
Loading history...
1636
    }
1637
1638
    /**
1639
     * setGameMapper
1640
     *
1641
     * @param GameMapperInterface $gameMapper
1642
     * @return Game
1643
     */
1644
    public function setGameMapper(GameMapperInterface $gameMapper)
1645
    {
1646
        $this->gameMapper = $gameMapper;
1647
1648
        return $this;
1649
    }
1650
1651
    /**
1652
     * getEntryMapper
1653
     *
1654
     * @return EntryMapperInterface
1655
     */
1656 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...
1657
    {
1658
        if (null === $this->entryMapper) {
1659
            $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...
1660
        }
1661
1662
        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 1662 which is incompatible with the return type documented by PlaygroundGame\Service\Game::getEntryMapper of type PlaygroundGame\Service\EntryMapperInterface.
Loading history...
1663
    }
1664
1665
    /**
1666
     * setEntryMapper
1667
     *
1668
     * @param EntryMapperInterface $entryMapper
1669
     * @return Game
1670
     */
1671
    public function setEntryMapper($entryMapper)
1672
    {
1673
        $this->entryMapper = $entryMapper;
1674
1675
        return $this;
1676
    }
1677
1678
    public function setOptions(ModuleOptions $options)
1679
    {
1680
        $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...
1681
1682
        return $this;
1683
    }
1684
1685
    public function getOptions()
1686
    {
1687
        if (! $this->options instanceof ModuleOptions) {
1688
            $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...
1689
                ->get('playgroundgame_module_options'));
1690
        }
1691
1692
        return $this->options;
1693
    }
1694
1695
    /**
1696
     * Retrieve service manager instance
1697
     *
1698
     * @return ServiceManager
1699
     */
1700
    public function getServiceManager()
1701
    {
1702
        return $this->serviceManager;
1703
    }
1704
1705
    /**
1706
     * Set service manager instance
1707
     *
1708
     * @param ServiceManager $serviceManager
1709
     * @return Game
1710
     */
1711
    public function setServiceManager(ServiceManager $serviceManager)
1712
    {
1713
        $this->serviceManager = $serviceManager;
1714
1715
        return $this;
1716
    }
1717
1718
    /**
1719
     * @param string $str
1720
     */
1721
    public function getExtension($str)
1722
    {
1723
        $i = strrpos($str, '.');
1724
1725
        $l = strlen($str) - $i;
1726
        $ext = substr($str, $i + 1, $l);
1727
1728
        return $ext;
1729
    }
1730
1731
    /**
1732
     * @param string $extension
1733
     */
1734
    public function getSrc($extension, $temp_path)
1735
    {
1736
        $image_src = '';
1737
        switch ($extension) {
1738
            case 'jpg':
1739
                $image_src = imagecreatefromjpeg($temp_path);
1740
                break;
1741
            case 'jpeg':
1742
                $image_src = imagecreatefromjpeg($temp_path);
1743
                break;
1744
            case 'png':
1745
                $image_src = imagecreatefrompng($temp_path);
1746
                break;
1747
            case 'gif':
1748
                $image_src = imagecreatefromgif($temp_path);
1749
                break;
1750
        }
1751
1752
        return $image_src;
1753
    }
1754
1755
    /**
1756
     * @param string $extension
1757
     * @param string $rep
1758
     * @param integer $mini_width
1759
     * @param integer $mini_height
1760
     */
1761
    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...
1762
    {
1763
        list($src_width, $src_height) = getimagesize($tmp_file);
1764
1765
        $ratio_src = $src_width / $src_height;
1766
        $ratio_mini = $mini_width / $mini_height;
1767
1768
        if ($ratio_src >= $ratio_mini) {
1769
            $new_height_mini = $mini_height;
1770
            $new_width_mini = $src_width / ($src_height / $mini_height);
1771
        } else {
1772
            $new_width_mini = $mini_width;
1773
            $new_height_mini = $src_height / ($src_width / $mini_width);
1774
        }
1775
1776
        $new_image_mini = imagecreatetruecolor($mini_width, $mini_height);
1777
1778
        imagecopyresampled($new_image_mini, $src, 0 - ($new_width_mini - $mini_width) / 2, 0 - ($new_height_mini - $mini_height) / 2, 0, 0, $new_width_mini, $new_height_mini, $src_width, $src_height);
1779
        imagejpeg($new_image_mini, $rep);
1780
1781
        imagedestroy($new_image_mini);
1782
    }
1783
1784
    public function getGameEntity()
1785
    {
1786
        return new \PlaygroundGame\Entity\Game();
1787
    }
1788
1789
    /**
1790
     * @param string $resource
1791
     * @param string $privilege
1792
     */
1793
    public function isAllowed($resource, $privilege = null)
1794
    {
1795
        $auth = $this->getServiceManager()->get('BjyAuthorize\Service\Authorize');
1796
1797
        return $auth->isAllowed($resource, $privilege);
1798
    }
1799
1800
    public function getIp()
1801
    {
1802
        $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...
1803
        if (isset($_SERVER['HTTP_CLIENT_IP'])) {
1804
            $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
1805
        } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1806
            $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
1807
        } elseif (isset($_SERVER['HTTP_X_FORWARDED'])) {
1808
            $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
1809
        } elseif (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
1810
            $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
1811
        } elseif (isset($_SERVER['HTTP_FORWARDED'])) {
1812
            $ipaddress = $_SERVER['HTTP_FORWARDED'];
1813
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
1814
            $ipaddress = $_SERVER['REMOTE_ADDR'];
1815
        } else {
1816
            $ipaddress = 'UNKNOWN';
1817
        }
1818
1819
        return $ipaddress;
1820
    }
1821
1822
    public function getAnonymousId()
1823
    {
1824
        $anonymousId = '';
1825
        if ($_COOKIE && array_key_exists('pg_anonymous', $_COOKIE)) {
1826
            $anonymousId = $_COOKIE['pg_anonymous'];
1827
        }
1828
1829
        return $anonymousId;
1830
    }
1831
1832
    /**
1833
     *
1834
     *
1835
     * This service is ready for all types of games
1836
     *
1837
     * @param array $data
1838
     * @return \PlaygroundGame\Entity\Game
1839
     */
1840 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...
1841
    {
1842
        $title = '';
1843
        $description = '';
1844
1845
        if ($data['form_jsonified']) {
1846
            $jsonPV = json_decode($data['form_jsonified']);
1847
            foreach ($jsonPV as $element) {
1848
                if ($element->form_properties) {
1849
                    $attributes = $element->form_properties[0];
1850
                    $title = $attributes->title;
1851
                    $description = $attributes->description;
1852
1853
                    break;
1854
                }
1855
            }
1856
        }
1857
        if (! $form) {
1858
            $form = new \PlaygroundGame\Entity\PlayerForm();
1859
        }
1860
        $form->setGame($game);
1861
        $form->setTitle($title);
1862
        $form->setDescription($description);
1863
        $form->setForm($data['form_jsonified']);
1864
        $form->setFormTemplate($data['form_template']);
1865
1866
        $form = $this->getPlayerFormMapper()->insert($form);
1867
1868
        return $form;
1869
    }
1870
1871
    /**
1872
     *  getCSV creates lines of CSV and returns it.
1873
     */
1874
    public function getCSV($array)
1875
    {
1876
        ob_start(); // buffer the output ...
1877
        $out = fopen('php://output', 'w');
1878
        fputcsv($out, array_keys($array[0]), ";");
1879
        foreach ($array as $line) {
1880
            fputcsv($out, $line, ";");
1881
        }
1882
        fclose($out);
1883
        return ob_get_clean(); // ... then return it as a string!
1884
    }
1885
    
1886
    /**
1887
     * Create a ZF2 Form from json data
1888
     * @return Form
1889
     */
1890
    public function createFormFromJson($jsonForm, $id = 'jsonForm')
1891
    {
1892
        $formPV = json_decode($jsonForm);
1893
        
1894
        $form = new Form();
1895
        $form->setAttribute('id', $id);
1896
        $form->setAttribute('enctype', 'multipart/form-data');
1897
        
1898
        $inputFilter = new \Zend\InputFilter\InputFilter();
1899
        $factory = new InputFactory();
1900
        
1901
        foreach ($formPV as $element) {
1902
            if (isset($element->line_text)) {
1903
                $attributes  = $element->line_text[0];
1904
                $name        = isset($attributes->name)? $attributes->name : '';
1905
                $placeholder = isset($attributes->data->placeholder)? $attributes->data->placeholder : '';
1906
                $label       = isset($attributes->data->label)? $attributes->data->label : '';
1907
                $required    = ($attributes->data->required == 'true') ? true : false ;
1908
                $class       = isset($attributes->data->class)? $attributes->data->class : '';
1909
                $id          = isset($attributes->data->id)? $attributes->data->id : '';
1910
                $lengthMin   = isset($attributes->data->length)? $attributes->data->length->min : '';
1911
                $lengthMax   = isset($attributes->data->length)? $attributes->data->length->max : '';
1912
                $validator   = isset($attributes->data->validator)? $attributes->data->validator : '';
1913
        
1914
                $element = new Element\Text($name);
1915
                $element->setLabel($label);
1916
                $element->setAttributes(
1917
                    array(
1918
                        'placeholder'    => $placeholder,
1919
                        'required'        => $required,
1920
                        'class'        => $class,
1921
                        'id'            => $id
1922
                    )
1923
                );
1924
                $form->add($element);
1925
        
1926
                $options = array();
1927
                $options['encoding'] = 'UTF-8';
1928
                if ($lengthMin && $lengthMin > 0) {
1929
                    $options['min'] = $lengthMin;
1930
                }
1931 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...
1932
                    $options['max'] = $lengthMax;
1933
                    $element->setAttribute('maxlength', $lengthMax);
1934
                    $options['messages'] = array(\Zend\Validator\StringLength::TOO_LONG => sprintf($this->getServiceLocator()->get('translator')->translate('This field contains more than %s characters', 'playgroundgame'), $lengthMax));
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...
1935
                }
1936
1937
                $validators = array(
1938
                    array(
1939
                        'name'    => 'StringLength',
1940
                        'options' => $options,
1941
                    ),
1942
                );
1943
                if ($validator) {
1944
                    $regex = "/.*\(([^)]*)\)/";
1945
                    preg_match($regex, $validator, $matches);
1946
                    $valArray = array('name' => str_replace('('.$matches[1].')', '', $validator), 'options' => array($matches[1]));
1947
                    $validators[] = $valArray;
1948
                }
1949
1950
                $inputFilter->add($factory->createInput(array(
1951
                    'name'     => $name,
1952
                    'required' => $required,
1953
                    'filters'  => array(
1954
                        array('name' => 'StripTags'),
1955
                        array('name' => 'StringTrim'),
1956
                    ),
1957
                    'validators' => $validators,
1958
                )));
1959
            }
1960
            if (isset($element->line_password)) {
1961
                $attributes  = $element->line_password[0];
1962
                $name        = isset($attributes->name)? $attributes->name : '';
1963
                $placeholder = isset($attributes->data->placeholder)? $attributes->data->placeholder : '';
1964
                $label       = isset($attributes->data->label)? $attributes->data->label : '';
1965
                $required    = (isset($attributes->data->required) && $attributes->data->required == 'true') ? true : false ;
1966
                $class       = isset($attributes->data->class)? $attributes->data->class : '';
1967
                $id          = isset($attributes->data->id)? $attributes->data->id : '';
1968
                $lengthMin   = isset($attributes->data->length)? $attributes->data->length->min : '';
1969
                $lengthMax   = isset($attributes->data->length)? $attributes->data->length->max : '';
1970
        
1971
                $element = new Element\Password($name);
1972
                $element->setLabel($label);
1973
                $element->setAttributes(
1974
                    array(
1975
                        'placeholder'   => $placeholder,
1976
                        'required'      => $required,
1977
                        'class'         => $class,
1978
                        'id'            => $id
1979
                    )
1980
                );
1981
                $form->add($element);
1982
        
1983
                $options = array();
1984
                $options['encoding'] = 'UTF-8';
1985
                if ($lengthMin && $lengthMin > 0) {
1986
                    $options['min'] = $lengthMin;
1987
                }
1988 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...
1989
                    $options['max'] = $lengthMax;
1990
                    $element->setAttribute('maxlength', $lengthMax);
1991
                    $options['messages'] = array(\Zend\Validator\StringLength::TOO_LONG => sprintf($this->getServiceLocator()->get('translator')->translate('This field contains more than %s characters', 'playgroundgame'), $lengthMax));
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...
1992
                }
1993
                $inputFilter->add($factory->createInput(array(
1994
                    'name'     => $name,
1995
                    'required' => $required,
1996
                    'filters'  => array(
1997
                        array('name' => 'StripTags'),
1998
                        array('name' => 'StringTrim'),
1999
                    ),
2000
                    'validators' => array(
2001
                        array(
2002
                            'name'    => 'StringLength',
2003
                            'options' => $options,
2004
                        ),
2005
                    ),
2006
                )));
2007
            }
2008
            if (isset($element->line_hidden)) {
2009
                $attributes  = $element->line_hidden[0];
2010
                $name        = isset($attributes->name)? $attributes->name : '';
2011
                $label       = isset($attributes->data->label)? $attributes->data->label : '';
2012
                $required    = ($attributes->data->required == 'true') ? true : false ;
2013
                $class       = isset($attributes->data->class)? $attributes->data->class : '';
2014
                $id          = isset($attributes->data->id)? $attributes->data->id : '';
2015
                $lengthMin   = isset($attributes->data->length)? $attributes->data->length->min : '';
2016
                $lengthMax   = isset($attributes->data->length)? $attributes->data->length->max : '';
2017
        
2018
                $element = new Element\Hidden($name);
2019
                $element->setLabel($label);
2020
                $element->setAttributes(
2021
                    array(
2022
                        'required'      => $required,
2023
                        'class'         => $class,
2024
                        'id'            => $id
2025
                    )
2026
                );
2027
                $form->add($element);
2028
        
2029
                $options = array();
2030
                $options['encoding'] = 'UTF-8';
2031
                if ($lengthMin && $lengthMin > 0) {
2032
                    $options['min'] = $lengthMin;
2033
                }
2034 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...
2035
                    $options['max'] = $lengthMax;
2036
                    $element->setAttribute('maxlength', $lengthMax);
2037
                    $options['messages'] = array(\Zend\Validator\StringLength::TOO_LONG => sprintf($this->getServiceLocator()->get('translator')->translate('This field contains more than %s characters', 'playgroundgame'), $lengthMax));
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...
2038
                }
2039
                $inputFilter->add($factory->createInput(array(
2040
                    'name'     => $name,
2041
                    'required' => $required,
2042
                    'filters'  => array(
2043
                        array('name' => 'StripTags'),
2044
                        array('name' => 'StringTrim'),
2045
                    ),
2046
                    'validators' => array(
2047
                        array(
2048
                            'name'    => 'StringLength',
2049
                            'options' => $options,
2050
                        ),
2051
                    ),
2052
                )));
2053
            }
2054
            if (isset($element->line_email)) {
2055
                $attributes  = $element->line_email[0];
2056
                $name        = isset($attributes->name)? $attributes->name : '';
2057
                $placeholder = isset($attributes->data->placeholder)? $attributes->data->placeholder : '';
2058
                $label       = isset($attributes->data->label)? $attributes->data->label : '';
2059
                $class       = isset($attributes->data->class)? $attributes->data->class : '';
2060
                $id          = isset($attributes->data->id)? $attributes->data->id : '';
2061
                $lengthMin   = isset($attributes->data->length)? $attributes->data->length->min : '';
2062
                $lengthMax   = isset($attributes->data->length)? $attributes->data->length->max : '';
2063
        
2064
                $element = new Element\Email($name);
2065
                $element->setLabel($label);
2066
                $element->setAttributes(
2067
                    array(
2068
                        'placeholder'    => $placeholder,
2069
                        '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...
2070
                        'class'        => $class,
2071
                        'id'            => $id
2072
                    )
2073
                );
2074
                $form->add($element);
2075
        
2076
                $options = array();
2077
                $options['encoding'] = 'UTF-8';
2078
                if ($lengthMin && $lengthMin > 0) {
2079
                    $options['min'] = $lengthMin;
2080
                }
2081 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...
2082
                    $options['max'] = $lengthMax;
2083
                    $element->setAttribute('maxlength', $lengthMax);
2084
                    $options['messages'] = array(\Zend\Validator\StringLength::TOO_LONG => sprintf($this->getServiceLocator()->get('translator')->translate('This field contains more than %s characters', 'playgroundgame'), $lengthMax));
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...
2085
                }
2086
                $inputFilter->add($factory->createInput(array(
2087
                    'name'     => $name,
2088
                    'required' => $required,
2089
                    'filters'  => array(
2090
                        array('name' => 'StripTags'),
2091
                        array('name' => 'StringTrim'),
2092
                    ),
2093
                    'validators' => array(
2094
                        array(
2095
                            'name'    => 'StringLength',
2096
                            'options' => $options,
2097
                        ),
2098
                    ),
2099
                )));
2100
            }
2101 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...
2102
                $attributes  = $element->line_radio[0];
2103
                $name        = isset($attributes->name)? $attributes->name : '';
2104
                $label       = isset($attributes->data->label)? $attributes->data->label : '';
2105
        
2106
                $required = false;
2107
                $class       = isset($attributes->data->class)? $attributes->data->class : '';
2108
                $id          = isset($attributes->data->id)? $attributes->data->id : '';
2109
                $lengthMin   = isset($attributes->data->length)? $attributes->data->length->min : '';
2110
                $lengthMax   = isset($attributes->data->length)? $attributes->data->length->max : '';
2111
                $innerData   = isset($attributes->data->innerData)? $attributes->data->innerData : array();
2112
        
2113
                $element = new Element\Radio($name);
2114
                $element->setLabel($label);
2115
                $element->setAttributes(
2116
                    array(
2117
                        'name'          => $name,
2118
                        'required'        => $required,
2119
                        'allowEmpty'    => !$required,
2120
                        'class'        => $class,
2121
                        'id'            => $id
2122
                    )
2123
                );
2124
                $values = array();
2125
                foreach ($innerData as $value) {
2126
                    $values[] = $value->label;
2127
                }
2128
                $element->setValueOptions($values);
2129
        
2130
                $options = array();
2131
                $options['encoding'] = 'UTF-8';
2132
                $options['disable_inarray_validator'] = true;
2133
        
2134
                $element->setOptions($options);
2135
        
2136
                $form->add($element);
2137
        
2138
                $inputFilter->add($factory->createInput(array(
2139
                    'name'     => $name,
2140
                    'required' => $required,
2141
                    'allowEmpty' => !$required,
2142
                )));
2143
            }
2144 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...
2145
                $attributes  = $element->line_checkbox[0];
2146
                $name        = isset($attributes->name)? $attributes->name : '';
2147
                $label       = isset($attributes->data->label)? $attributes->data->label : '';
2148
        
2149
                $required = false;
2150
                $class       = isset($attributes->data->class)? $attributes->data->class : '';
2151
                $id          = isset($attributes->data->id)? $attributes->data->id : '';
2152
                $lengthMin   = isset($attributes->data->length)? $attributes->data->length->min : '';
2153
                $lengthMax   = isset($attributes->data->length)? $attributes->data->length->max : '';
2154
                $innerData   = isset($attributes->data->innerData)? $attributes->data->innerData : array();
2155
        
2156
                $element = new Element\MultiCheckbox($name);
2157
                $element->setLabel($label);
2158
                $element->setAttributes(
2159
                    array(
2160
                        'name'     => $name,
2161
                        'required'        => $required,
2162
                        'allowEmpty'    => !$required,
2163
                        'class'        => $class,
2164
                        'id'            => $id
2165
                    )
2166
                );
2167
                $values = array();
2168
                foreach ($innerData as $value) {
2169
                    $values[] = $value->label;
2170
                }
2171
                $element->setValueOptions($values);
2172
                $form->add($element);
2173
        
2174
                $options = array();
2175
                $options['encoding'] = 'UTF-8';
2176
                $options['disable_inarray_validator'] = true;
2177
        
2178
                $element->setOptions($options);
2179
        
2180
                $inputFilter->add($factory->createInput(array(
2181
                    'name'     => $name,
2182
                    'required' => $required,
2183
                    'allowEmpty' => !$required,
2184
                )));
2185
            }
2186 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...
2187
                $attributes  = $element->line_dropdown[0];
2188
                $name        = isset($attributes->name)? $attributes->name : '';
2189
                $label       = isset($attributes->data->label)? $attributes->data->label : '';
2190
        
2191
                $required = false;
2192
                $class       = isset($attributes->data->class)? $attributes->data->class : '';
2193
                $id          = isset($attributes->data->id)? $attributes->data->id : '';
2194
                $lengthMin   = isset($attributes->data->length)? $attributes->data->length->min : '';
2195
                $lengthMax   = isset($attributes->data->length)? $attributes->data->length->max : '';
2196
                $dropdownValues   = isset($attributes->data->dropdownValues)? $attributes->data->dropdownValues : array();
2197
        
2198
                $element = new Element\Select($name);
2199
                $element->setLabel($label);
2200
                $element->setAttributes(
2201
                    array(
2202
                        'name'     => $name,
2203
                        'required'      => $required,
2204
                        'allowEmpty'    => !$required,
2205
                        'class'         => $class,
2206
                        'id'            => $id
2207
                    )
2208
                );
2209
                $values = array();
2210
                foreach ($dropdownValues as $value) {
2211
                    $values[] = $value->dropdown_label;
2212
                }
2213
                $element->setValueOptions($values);
2214
                $form->add($element);
2215
        
2216
                $options = array();
2217
                $options['encoding'] = 'UTF-8';
2218
                $options['disable_inarray_validator'] = true;
2219
        
2220
                $element->setOptions($options);
2221
        
2222
                $inputFilter->add($factory->createInput(array(
2223
                    'name'     => $name,
2224
                    'required' => $required,
2225
                    'allowEmpty' => !$required,
2226
                )));
2227
            }
2228
            if (isset($element->line_paragraph)) {
2229
                $attributes  = $element->line_paragraph[0];
2230
                $name        = isset($attributes->name)? $attributes->name : '';
2231
                $placeholder = isset($attributes->data->placeholder)? $attributes->data->placeholder : '';
2232
                $label       = isset($attributes->data->label)? $attributes->data->label : '';
2233
                $required    = ($attributes->data->required == 'true') ? true : false ;
2234
                $class       = isset($attributes->data->class)? $attributes->data->class : '';
2235
                $id          = isset($attributes->data->id)? $attributes->data->id : '';
2236
        
2237
                $element = new Element\Textarea($name);
2238
                $element->setLabel($label);
2239
                $element->setAttributes(
2240
                    array(
2241
                        'placeholder'    => $placeholder,
2242
                        'required'        => $required,
2243
                        'class'        => $class,
2244
                        'id'            => $id
2245
                    )
2246
                );
2247
                $form->add($element);
2248
        
2249
                $options = array();
2250
                $options['encoding'] = 'UTF-8';
2251
                if ($lengthMin && $lengthMin > 0) {
2252
                    $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...
2253
                }
2254
                if ($lengthMax && $lengthMax > $lengthMin) {
2255
                    $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...
2256
                    $element->setAttribute('maxlength', $lengthMax);
2257
                }
2258
                $inputFilter->add($factory->createInput(array(
2259
                    'name'     => $name,
2260
                    'required' => $required,
2261
                    'filters'  => array(
2262
                        array('name' => 'StripTags'),
2263
                        array('name' => 'StringTrim'),
2264
                    ),
2265
                    'validators' => array(
2266
                        array(
2267
                            'name'    => 'StringLength',
2268
                            'options' => $options,
2269
                        ),
2270
                    ),
2271
                )));
2272
            }
2273
            if (isset($element->line_upload)) {
2274
                $attributes  = $element->line_upload[0];
2275
                $name        = isset($attributes->name)? $attributes->name : '';
2276
                $label       = isset($attributes->data->label)? $attributes->data->label : '';
2277
                $required    = ($attributes->data->required == 'true') ? true : false ;
2278
                $class       = isset($attributes->data->class)? $attributes->data->class : '';
2279
                $id          = isset($attributes->data->id)? $attributes->data->id : '';
2280
                $filesizeMin = isset($attributes->data->filesize)? $attributes->data->filesize->min : 0;
2281
                $filesizeMax = isset($attributes->data->filesize)? $attributes->data->filesize->max : 10*1024*1024;
2282
                $element = new Element\File($name);
2283
                $element->setLabel($label);
2284
                $element->setAttributes(
2285
                    array(
2286
                        'required'    => $required,
2287
                        'class'    => $class,
2288
                        'id'        => $id
2289
                    )
2290
                );
2291
                $form->add($element);
2292
        
2293
                $inputFilter->add($factory->createInput(array(
2294
                    'name'     => $name,
2295
                    'required' => $required,
2296
                    'validators' => array(
2297
                        array('name' => '\Zend\Validator\File\Size', 'options' => array('min' => $filesizeMin, 'max' => $filesizeMax)),
2298
                        array('name' => '\Zend\Validator\File\Extension', 'options'  => array('png,PNG,jpg,JPG,jpeg,JPEG,gif,GIF', 'messages' => array(
2299
                            \Zend\Validator\File\Extension::FALSE_EXTENSION => 'Veuillez télécharger une image' ))
2300
                        ),
2301
                    ),
2302
                )));
2303
            }
2304
        }
2305
        
2306
        $form->setInputFilter($inputFilter);
2307
        
2308
        return $form;
2309
    }
2310
2311
    public function getPlayerFormMapper()
2312
    {
2313
        if (null === $this->playerformMapper) {
2314
            $this->playerformMapper = $this->getServiceManager()->get('playgroundgame_playerform_mapper');
2315
        }
2316
2317
        return $this->playerformMapper;
2318
    }
2319
2320
    public function setPlayerFormMapper($playerformMapper)
2321
    {
2322
        $this->playerformMapper = $playerformMapper;
2323
2324
        return $this;
2325
    }
2326
}
2327