Completed
Push — develop ( 54744b...29957b )
by greg
03:57
created

Game::download()   D

Complexity

Conditions 25
Paths 133

Size

Total Lines 111
Code Lines 78

Duplication

Lines 29
Ratio 26.13 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 29
loc 111
rs 4.32
cc 25
eloc 78
nc 133
nop 2

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
namespace PlaygroundGame\Service;
3
4
use PlaygroundGame\Entity\Entry;
5
use Zend\Session\Container;
6
use Zend\ServiceManager\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
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
576
577
        $qb = $em->createQueryBuilder();
578
        $qb->select('
579
            e.id,
580
            u.username,
581
            u.title,
582
            u.firstname,
583
            u.lastname,
584
            u.email,
585
            u.optin,
586
            u.optinPartner,
587
            u.address,
588
            u.address2,
589
            u.postalCode,
590
            u.city,
591
            u.telephone,
592
            u.mobile,
593
            u.created_at,
594
            u.dob,
595
            e.winner,
596
            e.socialShares,
597
            e.playerData,
598
            e.updated_at
599
            ')
600
            ->from('PlaygroundGame\Entity\Entry', 'e')
601
            ->leftJoin('e.user', 'u')
602
            ->where($qb->expr()->eq('e.game', ':game'));
603
        
604
        $qb->setParameter('game', $game);
605
606
        return $qb->getQuery();
607
    }
608
609
    public function getEntriesHeader($game){
610
        if ($game->getPlayerForm()) {
611
            $formPV = json_decode($game->getPlayerForm()->getForm(), true);
612
            $header = array('id'=> 1);
613 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...
614
                foreach($element as $k => $v){
615
                    if($k !== 'form_properties')
616
                        $header[$v[0]['name']] = 1;
617
                }
618
            }
619
        } else {
620
            $header = array(
621
                'id' => 1,
622
                'username' => 1,
623
                'title' => 1,
624
                'firstname' => 1,
625
                'lastname' => 1,
626
                'email' => 1,
627
                'optin' => 1,
628
                'optinPartner' => 1,
629
                'address' => 1,
630
                'address2' => 1,
631
                'postalCode' => 1,
632
                'city' => 1,
633
                'telephone' => 1,
634
                'mobile' => 1,
635
                'created_at' => 1,
636
                'dob' => 1,
637
                'winner' => 1
638
            );
639
        }
640
        $header['winner'] = 1;
641
        $header['socialShares'] = 1;
642
        $header['updated_at'] = 1;
643
644
        return $header;
645
    }
646
647
    /**
648
    * getGameEntries : I create an array of entries based on playerData + header
649
    *
650
    * @return Array of PlaygroundGame\Entity\Game
651
    */
652
    public function getGameEntries($header, $entries, $game)
653
    {
654
        $header = $this->getEntriesHeader($game);
655
656
        $results = array();
657
658
        foreach ($entries as $k=>$entry) {
659
            $entryData = json_decode($entry['playerData'], true);
660 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...
661
                if (isset($entryData[$key])) {
662
                    $results[$k][$key] = (is_array($entryData[$key]))?implode(', ',$entryData[$key]):$entryData[$key];
663
                } elseif (array_key_exists($key,$entry) ){
664
                    $results[$k][$key] = ($entry[$key] instanceof \DateTime)?$entry[$key]->format('Y-m-d'):$entry[$key];
665
                } else {
666
                    $results[$k][$key] = '';
667
                }
668
            }
669
        }
670
671
        return $results;
672
    }
673
674
    /**
675
     * getActiveSliderGames
676
     *
677
     * @return Array of PlaygroundGame\Entity\Game
678
     */
679
    public function getActiveSliderGames()
680
    {
681
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
682
        $today = new \DateTime("now");
683
        $today = $today->format('Y-m-d') . ' 23:59:59';
684
685
        // Game active with a start_date before today (or without start_date) and end_date after today (or without end-date)
686
        $query = $em->createQuery('SELECT g FROM PlaygroundGame\Entity\Game g
687
            WHERE (g.publicationDate <= :date OR g.publicationDate IS NULL)
688
            AND (g.closeDate >= :date OR g.closeDate IS NULL)
689
            AND g.active = true AND g.broadcastPlatform = 1 AND g.pushHome = true');
690
        $query->setParameter('date', $today);
691
        $games = $query->getResult();
692
693
        // je les classe par date de publication (date comme clé dans le tableau afin de pouvoir merger les objets
694
        // de type article avec le même procédé en les classant naturellement par date asc ou desc
695
        $arrayGames = array();
696 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...
697
            if ($game->getPublicationDate()) {
698
                $key = $game->getPublicationDate()->format('Ymd') . $game->getUpdatedAt()->format('Ymd') . '-' . $game->getId();
699
            } elseif ($game->getStartDate()) {
700
                $key = $game->getStartDate()->format('Ymd') . $game->getUpdatedAt()->format('Ymd') . '-' . $game->getId();
701
            } else {
702
                $key = $game->getUpdatedAt()->format('Ymd') . $game->getUpdatedAt()->format('Ymd') . '-' . $game->getId();
703
            }
704
            $arrayGames[$key] = $game;
705
        }
706
707
        return $arrayGames;
708
    }
709
710
    /**
711
     * getPrizeCategoryGames
712
     *
713
     * @return Array of PlaygroundGame\Entity\Game
714
     */
715 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...
716
    {
717
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
718
719
        $query = $em->createQuery('SELECT g FROM PlaygroundGame\Entity\Game g
720
            WHERE (g.prizeCategory = :categoryid AND g.broadcastPlatform = 1)
721
            ORDER BY g.publicationDate DESC');
722
        $query->setParameter('categoryid', $categoryid);
723
        $games = $query->getResult();
724
725
        return $games;
726
    }
727
728
    public function checkGame($identifier, $checkIfStarted = true)
729
    {
730
        $gameMapper = $this->getGameMapper();
731
732
        if (! $identifier) {
733
            return false;
734
        }
735
736
        $game = $gameMapper->findByIdentifier($identifier);
737
738
        // the game has not been found
739
        if (! $game) {
740
            return false;
741
        }
742
743
        if ($this->getServiceManager()
744
            ->get('Application')
745
            ->getMvcEvent()
746
            ->getRouteMatch()
747
            ->getParam('channel') === 'preview' && $this->isAllowed('game', 'edit')) {
748
            $game->setActive(true);
749
            $game->setStartDate(null);
750
            $game->setEndDate(null);
751
            $game->setPublicationDate(null);
752
            $game->setBroadcastPlatform(true);
753
754
            // I don't want the game to be updated through any update during the preview mode. I mark it as readonly for Doctrine
755
            $this->getServiceManager()
756
                ->get('doctrine.entitymanager.orm_default')
757
                ->getUnitOfWork()
758
                ->markReadOnly($game);
759
            return $game;
760
        }
761
762
        // The game is inactive
763
        if (! $game->getActive()) {
764
            return false;
765
        }
766
767
        // the game has not begun yet
768
        if (! $game->isOpen()) {
769
            return false;
770
        }
771
772
        // the game is finished and closed
773
        if (! $game->isStarted() && $checkIfStarted) {
774
            return false;
775
        }
776
777
        return $game;
778
    }
779
780
    /**
781
     * Return the last entry of the user on this game, if it exists.
782
     * An entry can be associated to :
783
     * - A user account (a real one, linked to PlaygroundUser
784
     * - An anonymous Identifier (based on one value of playerData (generally email))
785
     * - A cookie set on the player device (the less secure)
786
     * If the active param is set, it can check if the entry is active or not.
787
     * If the bonus param is set, it can check if the entry is a bonus or not.
788
     *
789
     * @param unknown $game
790
     * @param string $user
791
     * @param boolean $active
792
     * @param boolean $bonus
793
     * @return boolean
794
     */
795
    public function checkExistingEntry($game, $user = null, $active = null, $bonus = null)
796
    {
797
        $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...
798
        $search = array('game'  => $game);
799
800
        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...
801
            $search['user'] = $user;
802
        } elseif ($this->getAnonymousIdentifier()) {
803
            $search['anonymousIdentifier'] = $this->getAnonymousIdentifier();
804
            $search['user'] = null;
805
        } else {
806
            $search['anonymousId'] = $this->getAnonymousId();
807
            $search['user'] = null;
808
        }
809
        
810
        if (! is_null($active)) {
811
            $search['active'] = $active;
812
        }
813
        if (! is_null($bonus)) {
814
            $search['bonus'] = $bonus;
815
        }
816
817
        $entry = $this->getEntryMapper()->findOneBy($search);
818
819
        return $entry;
820
    }
821
822
    /*
823
    * This function updates the entry with the player data after checking 
824
    * that the data are compliant with the formUser Game attribute
825
    *
826
    * The $data has to be a json object
827
    */
828
    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...
829
    {
830
        $form = $this->createFormFromJson($game->getPlayerForm()->getForm(), 'playerForm');
831
        $form->setData($data);
832
833
        if (!$mandatory) {
834
            $filter = $form->getInputFilter();
835
            foreach ($form->getElements() as $element) {
836
                try {
837
                    $elementInput = $filter->get($element->getName());
838
                    $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...
839
                    $form->get($element->getName())->setAttribute('required', false);
840
                } 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...
841
                }
842
            }
843
        }
844
845
        if ($form->isValid()) {
846
            $dataJson = json_encode($form->getData());
847
848
            if ($game->getAnonymousAllowed() && $game->getAnonymousIdentifier() && isset($data[$game->getAnonymousIdentifier()])) {
849
                $session = new \Zend\Session\Container('anonymous_identifier');
850
                if (empty($session->offsetGet('anonymous_identifier'))) {
851
                    $anonymousIdentifier = $data[$game->getAnonymousIdentifier()];
852
                
853
                    $entry->setAnonymousIdentifier($anonymousIdentifier);
854
                
855
                    // I must transmit this info during the whole game workflow
856
                    $session->offsetSet('anonymous_identifier', $anonymousIdentifier);
857
                }
858
            }
859
860
            $entry->setPlayerData($dataJson);
861
            $this->getEntryMapper()->update($entry);
862
        } else {
863
            return false;
864
        }
865
866
        return true;
867
    }
868
869
870
    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...
871
    {
872
        // If on Facebook, check if you have to be a FB fan to play the game
873
        $session = new Container('facebook');
874
875
        if ($session->offsetExists('signed_request')) {
876
            // I'm on Facebook
877
            $sr = $session->offsetGet('signed_request');
878
            if ($sr['page']['liked'] == 1) {
879
                return true;
880
            }
881
        } else {
882
            // I'm not on Facebook
883
            return true;
884
        }
885
886
        return false;
887
    }
888
    
889
    public function getAnonymousIdentifier()
890
    {
891
        if (is_null($this->anonymousIdentifier)) {
892
            // If on Facebook, check if you have to be a FB fan to play the game
893
            $session = new Container('anonymous_identifier');
894
            
895
            if ($session->offsetExists('anonymous_identifier')) {
896
                $this->anonymousIdentifier = $session->offsetGet('anonymous_identifier');
897
            } else {
898
                $this->anonymousIdentifier = false;
899
            }
900
        }
901
    
902
        return $this->anonymousIdentifier;
903
    }
904
905
    /**
906
     * errors :
907
     * -1 : user not connected
908
     * -2 : limit entry games for this user reached
909
     *
910
     * @param \PlaygroundGame\Entity\Game $game
911
     * @param \PlaygroundUser\Entity\UserInterface $user
912
     * @return number unknown
913
     */
914
    public function play($game, $user)
915
    {
916
917
        // certaines participations peuvent rester ouvertes. On autorise alors le joueur à reprendre là ou il en était
918
        // par exemple les postvote...
919
        $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...
920
921
        if (! $entry) {
922
            if ($this->hasReachedPlayLimit($game, $user)) {
923
                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...
924
            }
925
926
            $entry = new Entry();
927
            $entry->setGame($game);
928
            $entry->setUser($user);
929
            $entry->setPoints(0);
930
            $entry->setIp($this->getIp());
931
            $entry->setAnonymousId($this->getAnonymousId());
932
            if ($this->getAnonymousIdentifier()) {
933
                $entry->setAnonymousIdentifier($this->getAnonymousIdentifier());
934
            }
935
936
            $entry = $this->getEntryMapper()->insert($entry);
937
            $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
938
                'user' => $user,
939
                'game' => $game,
940
                'entry' => $entry
941
            ));
942
        }
943
944
        return $entry;
945
    }
946
947
    /**
948
     * @param \PlaygroundGame\Entity\Game $game
949
     * @param \PlaygroundUser\Entity\UserInterface $user
950
     */
951
    public function hasReachedPlayLimit($game, $user)
952
    {
953
        // Is there a limitation on the game ?
954
        $limitAmount = $game->getPlayLimit();
955
        if ($limitAmount) {
956
            $limitScale = $game->getPlayLimitScale();
957
            $userEntries = $this->findLastEntries($game, $user, $limitScale);
958
959
            // player has reached the game limit
960
            if ($userEntries >= $limitAmount) {
961
                return true;
962
            }
963
        }
964
        return false;
965
    }
966
    
967
    public function findLastEntries($game, $user, $limitScale)
968
    {
969
        $limitDate = $this->getLimitDate($limitScale);
970
971
        if ($user) {
972
            return $this->getEntryMapper()->findLastEntriesByUser($game, $user, $limitDate);
973
        } elseif ($this->getAnonymousIdentifier()) {
974
            return $this->getEntryMapper()->findLastEntriesByAnonymousIdentifier($game, $this->getAnonymousIdentifier(), $limitDate);
975
        } else {
976
            return $this->getEntryMapper()->findLastEntriesByIp($game, $this->getIp(), $limitDate);
977
        }
978
    }
979
980
    /**
981
    *
982
    *
983
    */
984
    public function getLimitDate($limitScale)
985
    {
986
        $now = new \DateTime("now");
987
        switch ($limitScale) {
988
            case 'always':
989
                $interval = 'P100Y';
990
                $now->sub(new \DateInterval($interval));
991
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
992
                break;
993
            case 'day':
994
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
995
                break;
996
            case 'week':
997
                $interval = 'P7D';
998
                $now->sub(new \DateInterval($interval));
999
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
1000
                break;
1001
            case 'month':
1002
                $interval = 'P1M';
1003
                $now->sub(new \DateInterval($interval));
1004
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
1005
                break;
1006
            case 'year':
1007
                $interval = 'P1Y';
1008
                $now->sub(new \DateInterval($interval));
1009
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
1010
                break;
1011
            default:
1012
                $interval = 'P100Y';
1013
                $now->sub(new \DateInterval($interval));
1014
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
1015
        }
1016
1017
        return $dateLimit;
1018
    }
1019
1020
    public function findLastActiveEntry($game, $user)
1021
    {
1022
        return $this->checkExistingEntry($game, $user, true);
1023
    }
1024
1025
    public function findLastInactiveEntry($game, $user)
1026
    {
1027
        return $this->checkExistingEntry($game, $user, false, false);
1028
    }
1029
1030
    public function findLastEntry($game, $user)
1031
    {
1032
        return $this->checkExistingEntry($game, $user, null, false);
1033
    }
1034
1035
    public function sendShareMail($data, $game, $user, $entry, $template = 'share_game', $topic = null, $userTimer = array())
1036
    {
1037
        $mailService = $this->getServiceManager()->get('playgroundgame_message');
1038
        $mailSent = false;
1039
        $from = $this->getOptions()->getEmailFromAddress();
1040
        $subject = $this->getOptions()->getShareSubjectLine();
1041
        $renderer = $this->getServiceManager()->get('Zend\View\Renderer\RendererInterface');
1042
        if ($user) {
1043
            $email = $user->getEmail();
1044
        } elseif ($entry->getAnonymousIdentifier()) {
1045
            $email = $entry->getAnonymousIdentifier();
1046
        } else {
1047
            $email = $from;
1048
        }
1049
        $skinUrl = $renderer->url(
1050
            'frontend',
1051
            array('channel' => $this->getServiceManager()
1052
                ->get('Application')
1053
                ->getMvcEvent()
1054
                ->getRouteMatch()
1055
                ->getParam('channel')
1056
            ),
1057
            array(
1058
                'force_canonical' => true
1059
            )
1060
        );
1061
        $secretKey = strtoupper(substr(sha1(uniqid('pg_', true) . '####' . time()), 0, 15));
1062
1063
        if (! $topic) {
1064
            $topic = $game->getTitle();
1065
        }
1066
1067
        $shares = json_decode($entry->getSocialShares(), true);
1068
        
1069
        if ($data['email1']) {
1070
            $mailSent = true;
1071
            $message = $mailService->createHtmlMessage($from, $data['email1'], $subject, 'playground-game/email/' . $template, array(
1072
                'game' => $game,
1073
                'email' => $email,
1074
                'secretKey' => $secretKey,
1075
                'skinUrl' => $skinUrl,
1076
                'userTimer' => $userTimer
1077
            ));
1078
            $mailService->send($message);
1079
            
1080
            if (!isset($shares['mail'])) {
1081
                $shares['mail'] = 1;
1082
            } else {
1083
                $shares['mail'] += 1;
1084
            }
1085
        }
1086
        if ($data['email2'] && $data['email2'] != $data['email1']) {
1087
            $mailSent = true;
1088
            $message = $mailService->createHtmlMessage($from, $data['email2'], $subject, 'playground-game/email/' . $template, array(
1089
                'game' => $game,
1090
                'email' => $email,
1091
                'secretKey' => $secretKey,
1092
                'skinUrl' => $skinUrl,
1093
                'userTimer' => $userTimer
1094
            ));
1095
            $mailService->send($message);
1096
            
1097
            if (!isset($shares['mail'])) {
1098
                $shares['mail'] = 1;
1099
            } else {
1100
                $shares['mail'] += 1;
1101
            }
1102
        }
1103
        if ($data['email3'] && $data['email3'] != $data['email2'] && $data['email3'] != $data['email1']) {
1104
            $mailSent = true;
1105
            $message = $mailService->createHtmlMessage($from, $data['email3'], $subject, 'playground-game/email/' . $template, array(
1106
                'game' => $game,
1107
                'email' => $email,
1108
                'secretKey' => $secretKey,
1109
                'skinUrl' => $skinUrl,
1110
                'userTimer' => $userTimer
1111
            ));
1112
            $mailService->send($message);
1113
            
1114
            if (!isset($shares['mail'])) {
1115
                $shares['mail'] = 1;
1116
            } else {
1117
                $shares['mail'] += 1;
1118
            }
1119
        }
1120
        if ($data['email4'] && $data['email4'] != $data['email3'] && $data['email4'] != $data['email2'] && $data['email4'] != $data['email1']) {
1121
            $mailSent = true;
1122
            $message = $mailService->createHtmlMessage($from, $data['email4'], $subject, 'playground-game/email/' . $template, array(
1123
                'game' => $game,
1124
                'email' => $email,
1125
                'secretKey' => $secretKey,
1126
                'skinUrl' => $skinUrl,
1127
                'userTimer' => $userTimer
1128
            ));
1129
            $mailService->send($message);
1130
        
1131
            if (!isset($shares['mail'])) {
1132
                $shares['mail'] = 1;
1133
            } else {
1134
                $shares['mail'] += 1;
1135
            }
1136
        }
1137
        if ($data['email5'] && $data['email5'] != $data['email4'] && $data['email5'] != $data['email3'] && $data['email5'] != $data['email2'] && $data['email5'] != $data['email1']) {
1138
            $mailSent = true;
1139
            $message = $mailService->createHtmlMessage($from, $data['email5'], $subject, 'playground-game/email/' . $template, array(
1140
                'game' => $game,
1141
                'email' => $email,
1142
                'secretKey' => $secretKey,
1143
                'skinUrl' => $skinUrl,
1144
                'userTimer' => $userTimer
1145
            ));
1146
            $mailService->send($message);
1147
        
1148
            if (!isset($shares['mail'])) {
1149
                $shares['mail'] = 1;
1150
            } else {
1151
                $shares['mail'] += 1;
1152
            }
1153
        }
1154
        if ($mailSent) {
1155
            $sharesJson = json_encode($shares);
1156
            $entry->setSocialShares($sharesJson);
1157
            $entry = $this->getEntryMapper()->update($entry);
1158
            
1159
            $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1160
                'user' => $user,
1161
                'topic' => $topic,
1162
                'secretKey' => $secretKey,
1163
                'game' => $game,
1164
                'entry' => $entry
1165
            ));
1166
1167
            return true;
1168
        }
1169
1170
        return false;
1171
    }
1172
1173
    public function sendResultMail($game, $user, $entry, $template = 'entry', $prize = null)
1174
    {
1175
        $mailService = $this->getServiceManager()->get('playgroundgame_message');
1176
        $from = $this->getOptions()->getEmailFromAddress();
1177
        if ($user) {
1178
            $to = $user->getEmail();
1179
        } elseif ($entry->getAnonymousIdentifier()) {
1180
            $to = $entry->getAnonymousIdentifier();
1181
        } else {
1182
            return false;
1183
        }
1184
        $subject = $game->getTitle();
1185
        $renderer = $this->getServiceManager()->get('Zend\View\Renderer\RendererInterface');
1186
        $skinUrl = $renderer->url(
1187
            'frontend',
1188
            array('channel' => $this->getServiceManager()
1189
                ->get('Application')
1190
                ->getMvcEvent()
1191
                ->getRouteMatch()
1192
                ->getParam('channel')
1193
            ),
1194
            array(
1195
                'force_canonical' => true
1196
            )
1197
        );
1198
        $message = $mailService->createHtmlMessage($from, $to, $subject, 'playground-game/email/' . $template, array(
1199
            'game' => $game,
1200
            'entry' => $entry,
1201
            'skinUrl' => $skinUrl,
1202
            'prize' => $prize
1203
        ));
1204
        $mailService->send($message);
1205
    }
1206
1207
    public function sendGameMail($game, $user, $post, $template = 'postvote')
1208
    {
1209
        $mailService = $this->getServiceManager()->get('playgroundgame_message');
1210
        $from = $this->getOptions()->getEmailFromAddress();
1211
        $to = $user->getEmail();
1212
        $subject = $this->getOptions()->getParticipationSubjectLine();
1213
        $renderer = $this->getServiceManager()->get('Zend\View\Renderer\RendererInterface');
1214
        $skinUrl = $renderer->url(
1215
            'frontend',
1216
            array('channel' => $this->getServiceManager()
1217
                ->get('Application')
1218
                ->getMvcEvent()
1219
                ->getRouteMatch()
1220
                ->getParam('channel')
1221
            ),
1222
            array(
1223
                'force_canonical' => true
1224
            )
1225
        );
1226
1227
        $message = $mailService->createHtmlMessage($from, $to, $subject, 'playground-game/email/' . $template, array(
1228
            'game' => $game,
1229
            'post' => $post,
1230
            'skinUrl' => $skinUrl
1231
        ));
1232
        $mailService->send($message);
1233
    }
1234
1235 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...
1236
    {
1237
        $topic = $game->getTitle();
1238
        
1239
        $shares = json_decode($entry->getSocialShares(), true);
1240
        if (!isset($shares['fbwall'])) {
1241
            $shares['fbwall'] = 1;
1242
        } else {
1243
            $shares['fbwall'] += 1;
1244
        }
1245
        $sharesJson = json_encode($shares);
1246
        $entry->setSocialShares($sharesJson);
1247
        $entry = $this->getEntryMapper()->update($entry);
1248
        
1249
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1250
            'user' => $user,
1251
            'game' => $game,
1252
            'secretKey' => $secretKey,
1253
            'topic' => $topic,
1254
            'entry' => $entry
1255
        ));
1256
1257
        return true;
1258
    }
1259
1260
    public function postFbRequest($secretKey, $game, $user, $entry, $to)
1261
    {
1262
        $shares = json_decode($entry->getSocialShares(), true);
1263
        $to = explode(',', $to);
1264
        if (!isset($shares['fbrequest'])) {
1265
            $shares['fbrequest'] = count($to);
1266
        } else {
1267
            $shares['fbrequest'] += count($to);
1268
        }
1269
        $sharesJson = json_encode($shares);
1270
        $entry->setSocialShares($sharesJson);
1271
        $entry = $this->getEntryMapper()->update($entry);
1272
        
1273
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1274
            'user' => $user,
1275
            'game' => $game,
1276
            'secretKey' => $secretKey,
1277
            'entry' => $entry,
1278
            'invites' => count($to)
1279
        ));
1280
1281
        return true;
1282
    }
1283
1284 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...
1285
    {
1286
        $topic = $game->getTitle();
1287
1288
        $shares = json_decode($entry->getSocialShares(), true);
1289
        if (!isset($shares['fbrequest'])) {
1290
            $shares['tweet'] = 1;
1291
        } else {
1292
            $shares['tweet'] += 1;
1293
        }
1294
        $sharesJson = json_encode($shares);
1295
        $entry->setSocialShares($sharesJson);
1296
        $entry = $this->getEntryMapper()->update($entry);
1297
        
1298
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1299
            'user' => $user,
1300
            'game' => $game,
1301
            'secretKey' => $secretKey,
1302
            'topic' => $topic,
1303
            'entry' => $entry
1304
        ));
1305
1306
        return true;
1307
    }
1308
1309 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...
1310
    {
1311
        $topic = $game->getTitle();
1312
        
1313
        $shares = json_decode($entry->getSocialShares(), true);
1314
        if (!isset($shares['fbrequest'])) {
1315
            $shares['google'] = 1;
1316
        } else {
1317
            $shares['google'] += 1;
1318
        }
1319
        $sharesJson = json_encode($shares);
1320
        $entry->setSocialShares($sharesJson);
1321
        $entry = $this->getEntryMapper()->update($entry);
1322
1323
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1324
            'user' => $user,
1325
            'game' => $game,
1326
            'secretKey' => $secretKey,
1327
            'topic' => $topic,
1328
            'entry' => $entry
1329
        ));
1330
1331
        return true;
1332
    }
1333
1334
    /**
1335
     * Is it possible to trigger a bonus entry ?
1336
     *
1337
     * @param unknown_type $game
1338
     * @param unknown_type $user
1339
     */
1340
    public function allowBonus($game, $user)
1341
    {
1342
        if (! $game->getPlayBonus() || $game->getPlayBonus() == 'none') {
1343
            return false;
1344
        } elseif ($game->getPlayBonus() == 'one') {
1345
            if ($this->getEntryMapper()->findOneBy(array(
1346
                'game' => $game,
1347
                'user' => $user,
1348
                'bonus' => 1
1349
            ))) {
1350
                return false;
1351
            } else {
1352
                return true;
1353
            }
1354
        } elseif ($game->getPlayBonus() == 'per_entry') {
1355
            return $this->getEntryMapper()->checkBonusEntry($game, $user);
1356
        }
1357
1358
        return false;
1359
    }
1360
1361
    public function addAnotherEntry($game, $user, $winner = 0)
1362
    {
1363
        $entry = new Entry();
1364
        $entry->setGame($game);
1365
        $entry->setUser($user);
1366
        $entry->setPoints(0);
1367
        $entry->setIp($this->getIp());
1368
        $entry->setActive(0);
1369
        $entry->setBonus(1);
1370
        $entry->setWinner($winner);
1371
        $entry = $this->getEntryMapper()->insert($entry);
1372
1373
        return $entry;
1374
    }
1375
1376
    /**
1377
     * This bonus entry doesn't give points nor badges
1378
     * It's just there to increase the chances during the Draw
1379
     * Old Name playBonus
1380
     *
1381
     * @param PlaygroundGame\Entity\Game $game
1382
     * @param unknown $user
1383
     * @return boolean unknown
1384
     */
1385
    public function addAnotherChance($game, $user, $winner = 0)
1386
    {
1387
        if ($this->allowBonus($game, $user)) {
1388
            $this->addAnotherEntry($game, $user, $winner);
1389
1390
            return true;
1391
        }
1392
1393
        return false;
1394
    }
1395
1396
    /**
1397
     * This bonus entry doesn't give points nor badges but can play again
1398
     *
1399
     * @param PlaygroundGame\Entity\Game $game
1400
     * @param user $user
1401
     * @return boolean unknown
1402
     */
1403
    public function playAgain($game, $user, $winner = 0)
1404
    {
1405
        if ($this->allowBonus($game, $user)) {
1406
            $entry = $this->addAnotherEntry($game, $user, $winner);
1407
            $entry->setActive(1);
1408
            $entry = $this->getEntryMapper()->update($entry);
1409
            if ($entry->getActive() == 1) {
1410
                return true;
1411
            }
1412
        }
1413
1414
        return false;
1415
    }
1416
1417 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...
1418
    {
1419
        $configuration = require 'config/application.config.php';
1420
        $smConfig = isset($configuration['service_manager']) ? $configuration['service_manager'] : array();
1421
        $sm = new \Zend\ServiceManager\ServiceManager(new \Zend\Mvc\Service\ServiceManagerConfig($smConfig));
1422
        $sm->setService('ApplicationConfig', $configuration);
1423
        $sm->get('ModuleManager')->loadModules();
1424
        $sm->get('Application')->bootstrap();
1425
1426
        $mailService = $sm->get('playgrounduser_message');
1427
        $gameService = $sm->get('playgroundgame_quiz_service');
1428
1429
        $from = "[email protected]";
1430
        $subject = "sujet game";
1431
1432
        $to = "[email protected]";
1433
1434
        $game = $gameService->checkGame('qooqo');
1435
1436
        $message = $mailService->createTextMessage($from, $to, $subject, 'playground-game/email/share_reminder', array(
1437
            'game' => $game
1438
        ));
1439
1440
        $mailService->send($message);
1441
    }
1442
1443
    /**
1444
     * @param string $path
1445
     */
1446
    public function uploadFile($path, $file)
1447
    {
1448
        $err = $file["error"];
1449
        $message = '';
1450
        if ($err > 0) {
1451
            switch ($err) {
1452
                case '1':
1453
                    $message .= 'Max file size exceeded. (php.ini)';
1454
                    break;
1455
                case '2':
1456
                    $message .= 'Max file size exceeded.';
1457
                    break;
1458
                case '3':
1459
                    $message .= 'File upload was only partial.';
1460
                    break;
1461
                case '4':
1462
                    $message .= 'No file was attached.';
1463
                    break;
1464
                case '7':
1465
                    $message .= 'File permission denied.';
1466
                    break;
1467
                default:
1468
                    $message .= 'Unexpected error occurs.';
1469
            }
1470
1471
            return $err;
1472
        } else {
1473
            $fileNewname = $this->fileNewname($path, $file['name'], true);
1474
1475
            if (isset($file["base64"])) {
1476
                list(, $img) = explode(',', $file["base64"]);
1477
                $img = str_replace(' ', '+', $img);
1478
                $im = base64_decode($img);
1479
                if ($im !== false) {
1480
                    // getimagesizefromstring
1481
                    file_put_contents($path . $fileNewname, $im);
1482
                } else {
1483
                    return 1;
1484
                }
1485
1486
                return $fileNewname;
1487
            } else {
1488
                $adapter = new \Zend\File\Transfer\Adapter\Http();
1489
                // 1Mo
1490
                $size = new Size(array(
1491
                    'max' => 1024000
1492
                ));
1493
                $is_image = new IsImage('jpeg,png,gif,jpg');
1494
                $adapter->setValidators(array(
1495
                    $size,
1496
                    $is_image
1497
                ), $fileNewname);
1498
1499
                if (! $adapter->isValid()) {
1500
                    return false;
1501
                }
1502
1503
                @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...
1504
            }
1505
1506
            
1507
            if (class_exists("Imagick")) {
1508
                $ext = pathinfo($fileNewname, PATHINFO_EXTENSION);
1509
                $img = new \Imagick($path . $fileNewname);
1510
                $img->cropThumbnailImage(100, 100);
1511
                $img->setImageCompression(\Imagick::COMPRESSION_JPEG);
1512
                $img->setImageCompressionQuality(75);
1513
                // Strip out unneeded meta data
1514
                $img->stripImage();
1515
                $img->writeImage($path . str_replace('.'.$ext, '-thumbnail.'.$ext, $fileNewname));
1516
                ErrorHandler::stop(true);
1517
            }
1518
        }
1519
1520
        return $fileNewname;
1521
    }
1522
1523
    /**
1524
     * @param string $path
1525
     */
1526
    public function fileNewname($path, $filename, $generate = false)
1527
    {
1528
        $sanitize = new Sanitize();
1529
        $name = $sanitize->filter($filename);
1530
        $newpath = $path . $name;
1531
1532
        if ($generate) {
1533
            if (file_exists($newpath)) {
1534
                $filename = pathinfo($name, PATHINFO_FILENAME);
1535
                $ext = pathinfo($name, PATHINFO_EXTENSION);
1536
1537
                $name = $filename . '_' . rand(0, 99) . '.' . $ext;
1538
            }
1539
        }
1540
1541
        unset($sanitize);
1542
1543
        return $name;
1544
    }
1545
1546
    /**
1547
     * This function returns the list of games, order by $type
1548
     */
1549
    public function getQueryGamesOrderBy($type = 'createdAt', $order = 'DESC')
1550
    {
1551
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
1552
        $today = new \DateTime("now");
1553
        $today = $today->format('Y-m-d') . ' 23:59:59';
1554
1555
        $onlineGames = '(
1556
            (
1557
                CASE WHEN (
1558
                    g.active = 1
1559
                    AND g.broadcastPlatform = 1
1560
                    AND (g.startDate <= :date OR g.startDate IS NULL)
1561
                    AND (g.closeDate >= :date OR g.closeDate IS NULL)
1562
                ) THEN 1 ELSE 0 END
1563
            ) +
1564
            (
1565
                CASE WHEN (
1566
                    g.active = 0
1567
                    AND (g.broadcastPlatform = 0 OR g.broadcastPlatform IS NULL)
1568
                    AND g.startDate > :date
1569
                    AND g.closeDate < :date
1570
                ) THEN 1 ELSE 0 END
1571
            )
1572
        )';
1573
1574
        $qb = $em->createQueryBuilder();
1575
        $qb->select('g')->from('PlaygroundGame\Entity\Game', 'g');
1576
        
1577
        switch ($type) {
1578
            case 'startDate':
1579
                $qb->orderBy('g.startDate', $order);
1580
                break;
1581
            case 'activeGames':
1582
                $qb->orderBy('g.active', $order);
1583
                break;
1584
            case 'onlineGames':
1585
                $qb->orderBy($onlineGames, $order);
1586
                $qb->setParameter('date', $today);
1587
                break;
1588
            case 'createdAt':
1589
                $qb->orderBy('g.createdAt', $order);
1590
                break;
1591
        }
1592
1593
        $query = $qb->getQuery();
1594
1595
        return $query;
1596
    }
1597
1598
    public function draw($game)
1599
    {
1600
        $total = $game->getWinners();
1601
1602
        // I Have to know what is the User Class used
1603
        $zfcUserOptions = $this->getServiceManager()->get('zfcuser_module_options');
1604
        $userClass = $zfcUserOptions->getUserEntityClass();
1605
1606
        $result = $this->getEntryMapper()->draw($game, $userClass, $total);
1607
1608
        foreach ($result as $e) {
1609
            $e->setWinner(1);
1610
            $e = $this->getEntryMapper()->update($e);
1611
            $this->getEventManager()->trigger('win_lottery.post', $this, array(
1612
                'user' => $e->getUser(),
1613
                'game' => $game,
1614
                'entry' => $e
1615
            ));
1616
        }
1617
1618
        return $result;
1619
    }
1620
1621
    /**
1622
     * getGameMapper
1623
     *
1624
     * @return GameMapperInterface
1625
     */
1626 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...
1627
    {
1628
        if (null === $this->gameMapper) {
1629
            $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...
1630
        }
1631
1632
        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 1632 which is incompatible with the return type documented by PlaygroundGame\Service\Game::getGameMapper of type PlaygroundGame\Mapper\GameInterface.
Loading history...
1633
    }
1634
1635
    /**
1636
     * setGameMapper
1637
     *
1638
     * @param GameMapperInterface $gameMapper
1639
     * @return Game
1640
     */
1641
    public function setGameMapper(GameMapperInterface $gameMapper)
1642
    {
1643
        $this->gameMapper = $gameMapper;
1644
1645
        return $this;
1646
    }
1647
1648
    /**
1649
     * getEntryMapper
1650
     *
1651
     * @return EntryMapperInterface
1652
     */
1653 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...
1654
    {
1655
        if (null === $this->entryMapper) {
1656
            $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...
1657
        }
1658
1659
        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 1659 which is incompatible with the return type documented by PlaygroundGame\Service\Game::getEntryMapper of type PlaygroundGame\Service\EntryMapperInterface.
Loading history...
1660
    }
1661
1662
    /**
1663
     * setEntryMapper
1664
     *
1665
     * @param EntryMapperInterface $entryMapper
1666
     * @return Game
1667
     */
1668
    public function setEntryMapper($entryMapper)
1669
    {
1670
        $this->entryMapper = $entryMapper;
1671
1672
        return $this;
1673
    }
1674
1675
    public function setOptions(ModuleOptions $options)
1676
    {
1677
        $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...
1678
1679
        return $this;
1680
    }
1681
1682
    public function getOptions()
1683
    {
1684
        if (! $this->options instanceof ModuleOptions) {
1685
            $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...
1686
                ->get('playgroundgame_module_options'));
1687
        }
1688
1689
        return $this->options;
1690
    }
1691
1692
    /**
1693
     * Retrieve service manager instance
1694
     *
1695
     * @return ServiceManager
1696
     */
1697
    public function getServiceManager()
1698
    {
1699
        return $this->serviceManager;
1700
    }
1701
1702
    /**
1703
     * Set service manager instance
1704
     *
1705
     * @param ServiceManager $serviceManager
1706
     * @return Game
1707
     */
1708
    public function setServiceManager(ServiceManager $serviceManager)
1709
    {
1710
        $this->serviceManager = $serviceManager;
1711
1712
        return $this;
1713
    }
1714
1715
    /**
1716
     * @param string $str
1717
     */
1718
    public function getExtension($str)
1719
    {
1720
        $i = strrpos($str, '.');
1721
1722
        $l = strlen($str) - $i;
1723
        $ext = substr($str, $i + 1, $l);
1724
1725
        return $ext;
1726
    }
1727
1728
    /**
1729
     * @param string $extension
1730
     */
1731
    public function getSrc($extension, $temp_path)
1732
    {
1733
        $image_src = '';
1734
        switch ($extension) {
1735
            case 'jpg':
1736
                $image_src = imagecreatefromjpeg($temp_path);
1737
                break;
1738
            case 'jpeg':
1739
                $image_src = imagecreatefromjpeg($temp_path);
1740
                break;
1741
            case 'png':
1742
                $image_src = imagecreatefrompng($temp_path);
1743
                break;
1744
            case 'gif':
1745
                $image_src = imagecreatefromgif($temp_path);
1746
                break;
1747
        }
1748
1749
        return $image_src;
1750
    }
1751
1752
    /**
1753
     * @param string $extension
1754
     * @param string $rep
1755
     * @param integer $mini_width
1756
     * @param integer $mini_height
1757
     */
1758
    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...
1759
    {
1760
        list($src_width, $src_height) = getimagesize($tmp_file);
1761
1762
        $ratio_src = $src_width / $src_height;
1763
        $ratio_mini = $mini_width / $mini_height;
1764
1765
        if ($ratio_src >= $ratio_mini) {
1766
            $new_height_mini = $mini_height;
1767
            $new_width_mini = $src_width / ($src_height / $mini_height);
1768
        } else {
1769
            $new_width_mini = $mini_width;
1770
            $new_height_mini = $src_height / ($src_width / $mini_width);
1771
        }
1772
1773
        $new_image_mini = imagecreatetruecolor($mini_width, $mini_height);
1774
1775
        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);
1776
        imagejpeg($new_image_mini, $rep);
1777
1778
        imagedestroy($new_image_mini);
1779
    }
1780
1781
    public function getGameEntity()
1782
    {
1783
        return new \PlaygroundGame\Entity\Game();
1784
    }
1785
1786
    /**
1787
     * @param string $resource
1788
     * @param string $privilege
1789
     */
1790
    public function isAllowed($resource, $privilege = null)
1791
    {
1792
        $auth = $this->getServiceManager()->get('BjyAuthorize\Service\Authorize');
1793
1794
        return $auth->isAllowed($resource, $privilege);
1795
    }
1796
1797
    public function getIp()
1798
    {
1799
        $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...
1800
        if (isset($_SERVER['HTTP_CLIENT_IP'])) {
1801
            $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
1802
        } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1803
            $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
1804
        } elseif (isset($_SERVER['HTTP_X_FORWARDED'])) {
1805
            $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
1806
        } elseif (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
1807
            $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
1808
        } elseif (isset($_SERVER['HTTP_FORWARDED'])) {
1809
            $ipaddress = $_SERVER['HTTP_FORWARDED'];
1810
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
1811
            $ipaddress = $_SERVER['REMOTE_ADDR'];
1812
        } else {
1813
            $ipaddress = 'UNKNOWN';
1814
        }
1815
1816
        return $ipaddress;
1817
    }
1818
1819
    public function getAnonymousId()
1820
    {
1821
        $anonymousId = '';
1822
        if ($_COOKIE && array_key_exists('pg_anonymous', $_COOKIE)) {
1823
            $anonymousId = $_COOKIE['pg_anonymous'];
1824
        }
1825
1826
        return $anonymousId;
1827
    }
1828
1829
    /**
1830
     *
1831
     *
1832
     * This service is ready for all types of games
1833
     *
1834
     * @param array $data
1835
     * @return \PlaygroundGame\Entity\Game
1836
     */
1837 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...
1838
    {
1839
        $title = '';
1840
        $description = '';
1841
1842
        if ($data['form_jsonified']) {
1843
            $jsonPV = json_decode($data['form_jsonified']);
1844
            foreach ($jsonPV as $element) {
1845
                if ($element->form_properties) {
1846
                    $attributes = $element->form_properties[0];
1847
                    $title = $attributes->title;
1848
                    $description = $attributes->description;
1849
1850
                    break;
1851
                }
1852
            }
1853
        }
1854
        if (! $form) {
1855
            $form = new \PlaygroundGame\Entity\PlayerForm();
1856
        }
1857
        $form->setGame($game);
1858
        $form->setTitle($title);
1859
        $form->setDescription($description);
1860
        $form->setForm($data['form_jsonified']);
1861
        $form->setFormTemplate($data['form_template']);
1862
1863
        $form = $this->getPlayerFormMapper()->insert($form);
1864
1865
        return $form;
1866
    }
1867
1868
    /**
1869
     *  getCSV creates lines of CSV and returns it. 
1870
     */
1871
    public function getCSV($array) {
1872
        ob_start(); // buffer the output ...
1873
        $out = fopen('php://output', 'w');
1874
        fputcsv($out, array_keys($array[0]), ";");
1875
        foreach($array as $line) {
1876
            fputcsv($out, $line, ";");
1877
        }
1878
        fclose($out);
1879
        return ob_get_clean(); // ... then return it as a string!
1880
    }
1881
    
1882
    /**
1883
     * Create a ZF2 Form from json data
1884
     * @return Form
1885
     */
1886
    public function createFormFromJson($jsonForm, $id = 'jsonForm')
1887
    {
1888
        $formPV = json_decode($jsonForm);
1889
        
1890
        $form = new Form();
1891
        $form->setAttribute('id', $id);
1892
        $form->setAttribute('enctype', 'multipart/form-data');
1893
        
1894
        $inputFilter = new \Zend\InputFilter\InputFilter();
1895
        $factory = new InputFactory();
1896
        
1897
        foreach ($formPV as $element) {
1898
            if (isset($element->line_text)) {
1899
                $attributes  = $element->line_text[0];
1900
                $name        = isset($attributes->name)? $attributes->name : '';
1901
                $placeholder = isset($attributes->data->placeholder)? $attributes->data->placeholder : '';
1902
                $label       = isset($attributes->data->label)? $attributes->data->label : '';
1903
                $required    = ($attributes->data->required == 'true') ? true : false ;
1904
                $class       = isset($attributes->data->class)? $attributes->data->class : '';
1905
                $id          = isset($attributes->data->id)? $attributes->data->id : '';
1906
                $lengthMin   = isset($attributes->data->length)? $attributes->data->length->min : '';
1907
                $lengthMax   = isset($attributes->data->length)? $attributes->data->length->max : '';
1908
                $validator   = isset($attributes->data->validator)? $attributes->data->validator : '';
1909
        
1910
                $element = new Element\Text($name);
1911
                $element->setLabel($label);
1912
                $element->setAttributes(
1913
                    array(
1914
                        'placeholder'    => $placeholder,
1915
                        'required'        => $required,
1916
                        'class'        => $class,
1917
                        'id'            => $id
1918
                    )
1919
                );
1920
                $form->add($element);
1921
        
1922
                $options = array();
1923
                $options['encoding'] = 'UTF-8';
1924
                if ($lengthMin && $lengthMin > 0) {
1925
                    $options['min'] = $lengthMin;
1926
                }
1927 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...
1928
                    $options['max'] = $lengthMax;
1929
                    $element->setAttribute('maxlength', $lengthMax);
1930
                    $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...
1931
                }
1932
1933
                $validators = array(
1934
                    array(
1935
                        'name'    => 'StringLength',
1936
                        'options' => $options,
1937
                    ),
1938
                );
1939
                if ($validator) {
1940
                    $regex = "/.*\(([^)]*)\)/";
1941
                    preg_match($regex, $validator, $matches);
1942
                    $valArray = array('name' => str_replace('('.$matches[1].')', '', $validator), 'options' => array($matches[1]));
1943
                    $validators[] = $valArray;
1944
                }
1945
1946
                $inputFilter->add($factory->createInput(array(
1947
                    'name'     => $name,
1948
                    'required' => $required,
1949
                    'filters'  => array(
1950
                        array('name' => 'StripTags'),
1951
                        array('name' => 'StringTrim'),
1952
                    ),
1953
                    'validators' => $validators,
1954
                )));
1955
            }
1956
            if (isset($element->line_password)) {
1957
                $attributes  = $element->line_password[0];
1958
                $name        = isset($attributes->name)? $attributes->name : '';
1959
                $placeholder = isset($attributes->data->placeholder)? $attributes->data->placeholder : '';
1960
                $label       = isset($attributes->data->label)? $attributes->data->label : '';
1961
                $required    = (isset($attributes->data->required) && $attributes->data->required == 'true') ? true : false ;
1962
                $class       = isset($attributes->data->class)? $attributes->data->class : '';
1963
                $id          = isset($attributes->data->id)? $attributes->data->id : '';
1964
                $lengthMin   = isset($attributes->data->length)? $attributes->data->length->min : '';
1965
                $lengthMax   = isset($attributes->data->length)? $attributes->data->length->max : '';
1966
        
1967
                $element = new Element\Password($name);
1968
                $element->setLabel($label);
1969
                $element->setAttributes(
1970
                    array(
1971
                        'placeholder'   => $placeholder,
1972
                        'required'      => $required,
1973
                        'class'         => $class,
1974
                        'id'            => $id
1975
                    )
1976
                );
1977
                $form->add($element);
1978
        
1979
                $options = array();
1980
                $options['encoding'] = 'UTF-8';
1981
                if ($lengthMin && $lengthMin > 0) {
1982
                    $options['min'] = $lengthMin;
1983
                }
1984 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...
1985
                    $options['max'] = $lengthMax;
1986
                    $element->setAttribute('maxlength', $lengthMax);
1987
                    $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...
1988
                }
1989
                $inputFilter->add($factory->createInput(array(
1990
                    'name'     => $name,
1991
                    'required' => $required,
1992
                    'filters'  => array(
1993
                        array('name' => 'StripTags'),
1994
                        array('name' => 'StringTrim'),
1995
                    ),
1996
                    'validators' => array(
1997
                        array(
1998
                            'name'    => 'StringLength',
1999
                            'options' => $options,
2000
                        ),
2001
                    ),
2002
                )));
2003
            }
2004
            if (isset($element->line_hidden)) {
2005
                $attributes  = $element->line_hidden[0];
2006
                $name        = isset($attributes->name)? $attributes->name : '';
2007
                $label       = isset($attributes->data->label)? $attributes->data->label : '';
2008
                $required    = ($attributes->data->required == 'true') ? true : false ;
2009
                $class       = isset($attributes->data->class)? $attributes->data->class : '';
2010
                $id          = isset($attributes->data->id)? $attributes->data->id : '';
2011
                $lengthMin   = isset($attributes->data->length)? $attributes->data->length->min : '';
2012
                $lengthMax   = isset($attributes->data->length)? $attributes->data->length->max : '';
2013
        
2014
                $element = new Element\Hidden($name);
2015
                $element->setLabel($label);
2016
                $element->setAttributes(
2017
                    array(
2018
                        'required'      => $required,
2019
                        'class'         => $class,
2020
                        'id'            => $id
2021
                    )
2022
                );
2023
                $form->add($element);
2024
        
2025
                $options = array();
2026
                $options['encoding'] = 'UTF-8';
2027
                if ($lengthMin && $lengthMin > 0) {
2028
                    $options['min'] = $lengthMin;
2029
                }
2030 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...
2031
                    $options['max'] = $lengthMax;
2032
                    $element->setAttribute('maxlength', $lengthMax);
2033
                    $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...
2034
                }
2035
                $inputFilter->add($factory->createInput(array(
2036
                    'name'     => $name,
2037
                    'required' => $required,
2038
                    'filters'  => array(
2039
                        array('name' => 'StripTags'),
2040
                        array('name' => 'StringTrim'),
2041
                    ),
2042
                    'validators' => array(
2043
                        array(
2044
                            'name'    => 'StringLength',
2045
                            'options' => $options,
2046
                        ),
2047
                    ),
2048
                )));
2049
            }
2050
            if (isset($element->line_email)) {
2051
                $attributes  = $element->line_email[0];
2052
                $name        = isset($attributes->name)? $attributes->name : '';
2053
                $placeholder = isset($attributes->data->placeholder)? $attributes->data->placeholder : '';
2054
                $label       = isset($attributes->data->label)? $attributes->data->label : '';
2055
                $class       = isset($attributes->data->class)? $attributes->data->class : '';
2056
                $id          = isset($attributes->data->id)? $attributes->data->id : '';
2057
                $lengthMin   = isset($attributes->data->length)? $attributes->data->length->min : '';
2058
                $lengthMax   = isset($attributes->data->length)? $attributes->data->length->max : '';
2059
        
2060
                $element = new Element\Email($name);
2061
                $element->setLabel($label);
2062
                $element->setAttributes(
2063
                    array(
2064
                        'placeholder'    => $placeholder,
2065
                        '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...
2066
                        'class'        => $class,
2067
                        'id'            => $id
2068
                    )
2069
                );
2070
                $form->add($element);
2071
        
2072
                $options = array();
2073
                $options['encoding'] = 'UTF-8';
2074
                if ($lengthMin && $lengthMin > 0) {
2075
                    $options['min'] = $lengthMin;
2076
                }
2077 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...
2078
                    $options['max'] = $lengthMax;
2079
                    $element->setAttribute('maxlength', $lengthMax);
2080
                    $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...
2081
                }
2082
                $inputFilter->add($factory->createInput(array(
2083
                    'name'     => $name,
2084
                    'required' => $required,
2085
                    'filters'  => array(
2086
                        array('name' => 'StripTags'),
2087
                        array('name' => 'StringTrim'),
2088
                    ),
2089
                    'validators' => array(
2090
                        array(
2091
                            'name'    => 'StringLength',
2092
                            'options' => $options,
2093
                        ),
2094
                    ),
2095
                )));
2096
            }
2097 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...
2098
                $attributes  = $element->line_radio[0];
2099
                $name        = isset($attributes->name)? $attributes->name : '';
2100
                $label       = isset($attributes->data->label)? $attributes->data->label : '';
2101
        
2102
                $required = false;
2103
                $class       = isset($attributes->data->class)? $attributes->data->class : '';
2104
                $id          = isset($attributes->data->id)? $attributes->data->id : '';
2105
                $lengthMin   = isset($attributes->data->length)? $attributes->data->length->min : '';
2106
                $lengthMax   = isset($attributes->data->length)? $attributes->data->length->max : '';
2107
                $innerData   = isset($attributes->data->innerData)? $attributes->data->innerData : array();
2108
        
2109
                $element = new Element\Radio($name);
2110
                $element->setLabel($label);
2111
                $element->setAttributes(
2112
                    array(
2113
                        'name'          => $name,
2114
                        'required'        => $required,
2115
                        'allowEmpty'    => !$required,
2116
                        'class'        => $class,
2117
                        'id'            => $id
2118
                    )
2119
                );
2120
                $values = array();
2121
                foreach ($innerData as $value) {
2122
                    $values[] = $value->label;
2123
                }
2124
                $element->setValueOptions($values);
2125
        
2126
                $options = array();
2127
                $options['encoding'] = 'UTF-8';
2128
                $options['disable_inarray_validator'] = true;
2129
        
2130
                $element->setOptions($options);
2131
        
2132
                $form->add($element);
2133
        
2134
                $inputFilter->add($factory->createInput(array(
2135
                    'name'     => $name,
2136
                    'required' => $required,
2137
                    'allowEmpty' => !$required,
2138
                )));
2139
            }
2140 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...
2141
                $attributes  = $element->line_checkbox[0];
2142
                $name        = isset($attributes->name)? $attributes->name : '';
2143
                $label       = isset($attributes->data->label)? $attributes->data->label : '';
2144
        
2145
                $required = false;
2146
                $class       = isset($attributes->data->class)? $attributes->data->class : '';
2147
                $id          = isset($attributes->data->id)? $attributes->data->id : '';
2148
                $lengthMin   = isset($attributes->data->length)? $attributes->data->length->min : '';
2149
                $lengthMax   = isset($attributes->data->length)? $attributes->data->length->max : '';
2150
                $innerData   = isset($attributes->data->innerData)? $attributes->data->innerData : array();
2151
        
2152
                $element = new Element\MultiCheckbox($name);
2153
                $element->setLabel($label);
2154
                $element->setAttributes(
2155
                    array(
2156
                        'name'     => $name,
2157
                        'required'        => $required,
2158
                        'allowEmpty'    => !$required,
2159
                        'class'        => $class,
2160
                        'id'            => $id
2161
                    )
2162
                );
2163
                $values = array();
2164
                foreach ($innerData as $value) {
2165
                    $values[] = $value->label;
2166
                }
2167
                $element->setValueOptions($values);
2168
                $form->add($element);
2169
        
2170
                $options = array();
2171
                $options['encoding'] = 'UTF-8';
2172
                $options['disable_inarray_validator'] = true;
2173
        
2174
                $element->setOptions($options);
2175
        
2176
                $inputFilter->add($factory->createInput(array(
2177
                    'name'     => $name,
2178
                    'required' => $required,
2179
                    'allowEmpty' => !$required,
2180
                )));
2181
            }
2182 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...
2183
                $attributes  = $element->line_dropdown[0];
2184
                $name        = isset($attributes->name)? $attributes->name : '';
2185
                $label       = isset($attributes->data->label)? $attributes->data->label : '';
2186
        
2187
                $required = false;
2188
                $class       = isset($attributes->data->class)? $attributes->data->class : '';
2189
                $id          = isset($attributes->data->id)? $attributes->data->id : '';
2190
                $lengthMin   = isset($attributes->data->length)? $attributes->data->length->min : '';
2191
                $lengthMax   = isset($attributes->data->length)? $attributes->data->length->max : '';
2192
                $dropdownValues   = isset($attributes->data->dropdownValues)? $attributes->data->dropdownValues : array();
2193
        
2194
                $element = new Element\Select($name);
2195
                $element->setLabel($label);
2196
                $element->setAttributes(
2197
                    array(
2198
                        'name'     => $name,
2199
                        'required'      => $required,
2200
                        'allowEmpty'    => !$required,
2201
                        'class'         => $class,
2202
                        'id'            => $id
2203
                    )
2204
                );
2205
                $values = array();
2206
                foreach ($dropdownValues as $value) {
2207
                    $values[] = $value->dropdown_label;
2208
                }
2209
                $element->setValueOptions($values);
2210
                $form->add($element);
2211
        
2212
                $options = array();
2213
                $options['encoding'] = 'UTF-8';
2214
                $options['disable_inarray_validator'] = true;
2215
        
2216
                $element->setOptions($options);
2217
        
2218
                $inputFilter->add($factory->createInput(array(
2219
                    'name'     => $name,
2220
                    'required' => $required,
2221
                    'allowEmpty' => !$required,
2222
                )));
2223
            }
2224
            if (isset($element->line_paragraph)) {
2225
                $attributes  = $element->line_paragraph[0];
2226
                $name        = isset($attributes->name)? $attributes->name : '';
2227
                $placeholder = isset($attributes->data->placeholder)? $attributes->data->placeholder : '';
2228
                $label       = isset($attributes->data->label)? $attributes->data->label : '';
2229
                $required    = ($attributes->data->required == 'true') ? true : false ;
2230
                $class       = isset($attributes->data->class)? $attributes->data->class : '';
2231
                $id          = isset($attributes->data->id)? $attributes->data->id : '';
2232
        
2233
                $element = new Element\Textarea($name);
2234
                $element->setLabel($label);
2235
                $element->setAttributes(
2236
                    array(
2237
                        'placeholder'    => $placeholder,
2238
                        'required'        => $required,
2239
                        'class'        => $class,
2240
                        'id'            => $id
2241
                    )
2242
                );
2243
                $form->add($element);
2244
        
2245
                $options = array();
2246
                $options['encoding'] = 'UTF-8';
2247
                if ($lengthMin && $lengthMin > 0) {
2248
                    $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...
2249
                }
2250
                if ($lengthMax && $lengthMax > $lengthMin) {
2251
                    $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...
2252
                    $element->setAttribute('maxlength', $lengthMax);
2253
                }
2254
                $inputFilter->add($factory->createInput(array(
2255
                    'name'     => $name,
2256
                    'required' => $required,
2257
                    'filters'  => array(
2258
                        array('name' => 'StripTags'),
2259
                        array('name' => 'StringTrim'),
2260
                    ),
2261
                    'validators' => array(
2262
                        array(
2263
                            'name'    => 'StringLength',
2264
                            'options' => $options,
2265
                        ),
2266
                    ),
2267
                )));
2268
            }
2269
            if (isset($element->line_upload)) {
2270
                $attributes  = $element->line_upload[0];
2271
                $name        = isset($attributes->name)? $attributes->name : '';
2272
                $label       = isset($attributes->data->label)? $attributes->data->label : '';
2273
                $required    = ($attributes->data->required == 'true') ? true : false ;
2274
                $class       = isset($attributes->data->class)? $attributes->data->class : '';
2275
                $id          = isset($attributes->data->id)? $attributes->data->id : '';
2276
                $filesizeMin = isset($attributes->data->filesize)? $attributes->data->filesize->min : 0;
2277
                $filesizeMax = isset($attributes->data->filesize)? $attributes->data->filesize->max : 10*1024*1024;
2278
                $element = new Element\File($name);
2279
                $element->setLabel($label);
2280
                $element->setAttributes(
2281
                    array(
2282
                        'required'    => $required,
2283
                        'class'    => $class,
2284
                        'id'        => $id
2285
                    )
2286
                );
2287
                $form->add($element);
2288
        
2289
                $inputFilter->add($factory->createInput(array(
2290
                    'name'     => $name,
2291
                    'required' => $required,
2292
                    'validators' => array(
2293
                        array('name' => '\Zend\Validator\File\Size', 'options' => array('min' => $filesizeMin, 'max' => $filesizeMax)),
2294
                        array('name' => '\Zend\Validator\File\Extension', 'options'  => array('png,PNG,jpg,JPG,jpeg,JPEG,gif,GIF', 'messages' => array(
2295
                            \Zend\Validator\File\Extension::FALSE_EXTENSION => 'Veuillez télécharger une image' ))
2296
                        ),
2297
                    ),
2298
                )));
2299
            }
2300
        }
2301
        
2302
        $form->setInputFilter($inputFilter);
2303
        
2304
        return $form;
2305
    }
2306
2307
    public function getPlayerFormMapper()
2308
    {
2309
        if (null === $this->playerformMapper) {
2310
            $this->playerformMapper = $this->getServiceManager()->get('playgroundgame_playerform_mapper');
2311
        }
2312
2313
        return $this->playerformMapper;
2314
    }
2315
2316
    public function setPlayerFormMapper($playerformMapper)
2317
    {
2318
        $this->playerformMapper = $playerformMapper;
2319
2320
        return $this;
2321
    }
2322
}
2323