Completed
Push — master ( 437856...5fb154 )
by greg
03:04
created

Game::getGameUserMediaUrl()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 7
Ratio 100 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 7
loc 7
rs 9.4285
cc 1
eloc 4
nc 1
nop 2
1
<?php
2
namespace PlaygroundGame\Service;
3
4
use PlaygroundGame\Entity\Entry;
5
use Zend\Session\Container;
6
use Zend\ServiceManager\ServiceManager;
7
use ZfcBase\EventManager\EventProvider;
8
use PlaygroundGame\Options\ModuleOptions;
9
use PlaygroundGame\Mapper\GameInterface as GameMapperInterface;
10
use DoctrineModule\Validator\NoObjectExists as NoObjectExistsValidator;
11
use Zend\Validator\File\Size;
12
use Zend\Validator\File\IsImage;
13
use Zend\Stdlib\ErrorHandler;
14
use PlaygroundCore\Filter\Sanitize;
15
use Zend\Form\Element;
16
use Zend\Form\Form;
17
use Zend\InputFilter\Factory as InputFactory;
18
use Zend\ServiceManager\ServiceLocatorInterface;
19
20
class Game extends EventProvider
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 UserServiceOptionsInterface
37
     */
38
    protected $options;
39
40
    protected $playerformMapper;
41
42
    protected $invitationMapper;
43
44
    protected $userMapper;
45
    
46
    protected $anonymousIdentifier = null;
47
48
    /**
49
     *
50
     * @var ServiceManager
51
     */
52
    protected $serviceLocator;
53
54
    public function __construct(ServiceLocatorInterface $locator)
55
    {
56
        $this->serviceLocator = $locator;
0 ignored issues
show
Documentation Bug introduced by
$locator is of type object<Zend\ServiceManag...erviceLocatorInterface>, but the property $serviceLocator was declared to be of type object<Zend\ServiceManager\ServiceManager>. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof 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 given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
57
    }
58
59 View Code Duplication
    public function getGameUserPath($game, $user)
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...
60
    {
61
        $path = $this->getOptions()->getMediaPath() . DIRECTORY_SEPARATOR;
62
        $path .= 'game' . $game->getId() . DIRECTORY_SEPARATOR;
63
        if (!is_dir($path)) {
64
            mkdir($path, 0777, true);
65
        }
66
        $path .= 'user'. $user->getId() . DIRECTORY_SEPARATOR;
67
        if (!is_dir($path)) {
68
            mkdir($path, 0777, true);
69
        }
70
71
        return $path;
72
    }
73
74 View Code Duplication
    public function getGameUserMediaUrl($game, $user)
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...
75
    {
76
        $media_url = $this->getOptions()->getMediaUrl() . '/';
77
        $media_url .= 'game' . $game->getId() . '/' . 'user'. $user->getId() . '/';
78
79
        return $media_url;
80
    }
81
82
    /**
83
     *
84
     *
85
     * This service is ready for all types of games
86
     *
87
     * @param array $data
88
     * @param string $formClass
89
     * @return \PlaygroundGame\Entity\Game
90
     */
91
    public function createOrUpdate(array $data, $game, $formClass)
92
    {
93
        $entityManager = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
94
95
        $form = $this->serviceLocator->get($formClass);
96
        $form->get('publicationDate')->setOptions(array(
97
            'format' => 'Y-m-d H:i:s'
98
        ));
99
        $form->get('startDate')->setOptions(array(
100
            'format' => 'Y-m-d H:i:s'
101
        ));
102
        $form->get('endDate')->setOptions(array(
103
            'format' => 'Y-m-d H:i:s'
104
        ));
105
        $form->get('closeDate')->setOptions(array(
106
            'format' => 'Y-m-d H:i:s'
107
        ));
108
109
        $form->bind($game);
110
111
        $path = $this->getOptions()->getMediaPath() . '/';
112
        $media_url = $this->getOptions()->getMediaUrl() . '/';
113
114
        $identifierInput = $form->getInputFilter()->get('identifier');
115
        $noObjectExistsValidator = new NoObjectExistsValidator(array(
116
            'object_repository' => $entityManager->getRepository('PlaygroundGame\Entity\Game'),
117
            'fields' => 'identifier',
118
            'messages' => array(
119
                'objectFound' => 'This url already exists !'
120
            )
121
        ));
122
123
        if ($game->getIdentifier() != $data['identifier']) {
124
            $identifierInput->getValidatorChain()->addValidator($noObjectExistsValidator);
125
        }
126
127
        // I must switch from original format to the Y-m-d format because
128
        // this is the only one accepted by new DateTime($value)
129 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...
130
            $tmpDate = \DateTime::createFromFormat('d/m/Y H:i:s', $data['publicationDate']);
131
            $data['publicationDate'] = $tmpDate->format('Y-m-d H:i:s');
132
        }
133 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...
134
            $tmpDate = \DateTime::createFromFormat('d/m/Y H:i:s', $data['startDate']);
135
            $data['startDate'] = $tmpDate->format('Y-m-d H:i:s');
136
        }
137 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...
138
            $tmpDate = \DateTime::createFromFormat('d/m/Y H:i:s', $data['endDate']);
139
            $data['endDate'] = $tmpDate->format('Y-m-d H:i:s');
140
        }
141 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...
142
            $tmpDate = \DateTime::createFromFormat('d/m/Y H:i:s', $data['closeDate']);
143
            $data['closeDate'] = $tmpDate->format('Y-m-d H:i:s');
144
        }
145
146
        // If publicationDate is null, I update it with the startDate if not null neither
147
        if ((! isset($data['publicationDate']) || $data['publicationDate'] == '') &&
148
            (isset($data['startDate']) && $data['startDate'] != '')
149
        ) {
150
            $data['publicationDate'] = $data['startDate'];
151
        }
152
153
        // If the identifier has not been set, I use the title to create one.
154 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...
155
            $data['identifier'] = $data['title'];
156
        }
157
158
        $form->setData($data);
159
160
        // If someone want to claim... It's time to do it ! used for exemple by PlaygroundFacebook Module
161
        $result = $this->getEventManager()->trigger(__FUNCTION__ . '.validate', $this, array(
162
            'game' => $game,
163
            'data' => $data
164
        ));
165
        if (is_array($result) && ! $result[0]) {
166
            $form->get('fbAppId')->setMessages(array(
167
                'Vous devez d\'abord désinstaller l\'appli Facebook'
168
            ));
169
170
            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::createOrUpdate 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...
171
        }
172
173
        if (! $form->isValid()) {
174 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...
175
                $tmpDate = \DateTime::createFromFormat('Y-m-d H:i:s', $data['publicationDate']);
176
                $data['publicationDate'] = $tmpDate->format('d/m/Y H:i:s');
177
                $form->setData(array(
178
                    'publicationDate' => $data['publicationDate']
179
                ));
180
            }
181 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...
182
                $tmpDate = \DateTime::createFromFormat('Y-m-d H:i:s', $data['startDate']);
183
                $data['startDate'] = $tmpDate->format('d/m/Y H:i:s');
184
                $form->setData(array(
185
                    'startDate' => $data['startDate']
186
                ));
187
            }
188 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...
189
                $tmpDate = \DateTime::createFromFormat('Y-m-d H:i:s', $data['endDate']);
190
                $data['endDate'] = $tmpDate->format('d/m/Y H:i:s');
191
                $form->setData(array(
192
                    'endDate' => $data['endDate']
193
                ));
194
            }
195 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...
196
                $tmpDate = \DateTime::createFromFormat('Y-m-d H:i:s', $data['closeDate']);
197
                $data['closeDate'] = $tmpDate->format('d/m/Y H:i:s');
198
                $form->setData(array(
199
                    'closeDate' => $data['closeDate']
200
                ));
201
            }
202
            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::createOrUpdate 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...
203
        }
204
205
        $game = $form->getData();
206
        $game = $this->getGameMapper()->insert($game);
207
208
        // I wait for the game to be saved to obtain its ID.
209 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...
210
            ErrorHandler::start();
211
            $data['uploadMainImage']['name'] = $this->fileNewname(
212
                $path,
213
                $game->getId() . "-" . $data['uploadMainImage']['name']
214
            );
215
            move_uploaded_file($data['uploadMainImage']['tmp_name'], $path . $data['uploadMainImage']['name']);
216
            $game->setMainImage($media_url . $data['uploadMainImage']['name']);
217
            ErrorHandler::stop(true);
218
        }
219
220 View Code Duplication
        if (isset($data['deleteMainImage']) &&
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
221
            $data['deleteMainImage'] &&
222
            empty($data['uploadMainImage']['tmp_name'])
223
        ) {
224
            ErrorHandler::start();
225
            $image = $game->getMainImage();
226
            $image = str_replace($media_url, '', $image);
227
            unlink($path . $image);
228
            $game->setMainImage(null);
229
            ErrorHandler::stop(true);
230
        }
231
232 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...
233
            ErrorHandler::start();
234
            $data['uploadSecondImage']['name'] = $this->fileNewname(
235
                $path,
236
                $game->getId() . "-" . $data['uploadSecondImage']['name']
237
            );
238
            move_uploaded_file($data['uploadSecondImage']['tmp_name'], $path . $data['uploadSecondImage']['name']);
239
            $game->setSecondImage($media_url . $data['uploadSecondImage']['name']);
240
            ErrorHandler::stop(true);
241
        }
242
243 View Code Duplication
        if (isset($data['deleteSecondImage']) &&
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
244
            $data['deleteSecondImage'] &&
245
            empty($data['uploadSecondImage']['tmp_name'])
246
        ) {
247
            ErrorHandler::start();
248
            $image = $game->getSecondImage();
249
            $image = str_replace($media_url, '', $image);
250
            unlink($path . $image);
251
            $game->setSecondImage(null);
252
            ErrorHandler::stop(true);
253
        }
254
255
        if (! empty($data['uploadStylesheet']['tmp_name'])) {
256
            ErrorHandler::start();
257
            move_uploaded_file($data['uploadStylesheet']['tmp_name'], $path . 'stylesheet_' . $game->getId() . '.css');
258
            $game->setStylesheet($media_url . 'stylesheet_' . $game->getId() . '.css');
259
            ErrorHandler::stop(true);
260
        }
261
262 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...
263
            ErrorHandler::start();
264
            $data['uploadFbShareImage']['name'] = $this->fileNewname(
265
                $path,
266
                $game->getId() . "-" . $data['uploadFbShareImage']['name']
267
            );
268
            move_uploaded_file($data['uploadFbShareImage']['tmp_name'], $path . $data['uploadFbShareImage']['name']);
269
            $game->setFbShareImage($media_url . $data['uploadFbShareImage']['name']);
270
            ErrorHandler::stop(true);
271
        }
272
273 View Code Duplication
        if (isset($data['deleteFbShareImage']) &&
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
274
            $data['deleteFbShareImage'] &&
275
            empty($data['uploadFbShareImage']['tmp_name'])
276
        ) {
277
            ErrorHandler::start();
278
            $image = $game->getFbShareImage();
279
            $image = str_replace($media_url, '', $image);
280
            unlink($path . $image);
281
            $game->setFbShareImage(null);
282
            ErrorHandler::stop(true);
283
        }
284
285
        if (! empty($data['uploadFbPageTabImage']['tmp_name'])) {
286
            ErrorHandler::start();
287
            $extension = $this->getExtension(strtolower($data['uploadFbPageTabImage']['name']));
288
            $src = $this->getSrc($extension, $data['uploadFbPageTabImage']['tmp_name']);
289
            $this->resize(
290
                $data['uploadFbPageTabImage']['tmp_name'],
291
                $extension,
292
                $path . $game->getId() . "-" . $data['uploadFbPageTabImage']['name'],
293
                $src,
294
                111,
295
                74
296
            );
297
298
            $game->setFbPageTabImage($media_url . $game->getId() . "-" . $data['uploadFbPageTabImage']['name']);
299
            ErrorHandler::stop(true);
300
        }
301
302 View Code Duplication
        if (isset($data['deleteFbPageTabImage']) &&
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
303
            $data['deleteFbPageTabImage'] &&
304
            empty($data['uploadFbPageTabImage']['tmp_name'])
305
        ) {
306
            ErrorHandler::start();
307
            $image = $game->getFbPageTabImage();
308
            $image = str_replace($media_url, '', $image);
309
            unlink($path . $image);
310
            $game->setFbPageTabImage(null);
311
            ErrorHandler::stop(true);
312
        }
313
314
        $game = $this->getGameMapper()->update($game);
315
316
        $prize_mapper = $this->serviceLocator->get('playgroundgame_prize_mapper');
317
        if (isset($data['prizes'])) {
318
            foreach ($data['prizes'] as $prize_data) {
319
                if (! empty($prize_data['picture_file']['tmp_name']) && ! $prize_data['picture_file']['error']) {
320
                    if ($prize_data['id']) {
321
                        $prize = $prize_mapper->findById($prize_data['id']);
322
                    } else {
323
                        $some_prizes = $prize_mapper->findBy(array(
324
                            'game' => $game,
325
                            'title' => $prize_data['title']
326
                        ));
327
                        if (count($some_prizes) == 1) {
328
                            $prize = $some_prizes[0];
329
                        } else {
330
                            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::createOrUpdate 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...
331
                        }
332
                    }
333
                    // Remove if existing image
334
                    if ($prize->getPicture() && file_exists($prize->getPicture())) {
335
                        unlink($prize->getPicture());
336
                        $prize->getPicture(null);
337
                    }
338
                    // Upload and set new
339
                    ErrorHandler::start();
340
                    $filename = "game-" . $game->getId() . "-prize-";
341
                    $filename .= $prize->getId() . "-" . $prize_data['picture_file']['name'];
342
                    move_uploaded_file($prize_data['picture_file']['tmp_name'], $path . $filename);
343
                    $prize->setPicture($media_url . $filename);
344
                    ErrorHandler::stop(true);
345
                    $prize_mapper->update($prize);
346
                }
347
            }
348
        }
349
        // If I receive false, it means that the FB Id was not available anymore
350
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
351
            'game' => $game
352
        ));
353
354
        return $game;
355
    }
356
    
357
    /**
358
     * getActiveGames
359
     *
360
     * @return Array of PlaygroundGame\Entity\Game
361
     */
362
    public function getActiveGames($displayHome = true, $classType = '', $order = '')
363
    {
364
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
365
        $today = new \DateTime("now");
366
        $today = $today->format('Y-m-d H:i:s');
367
        $orderBy = 'g.publicationDate';
368
        if ($order != '') {
369
            $orderBy = 'g.'.$order;
370
        }
371
372
        $qb = $em->createQueryBuilder();
373
        $and = $qb->expr()->andx();
374
        $and->add(
375
            $qb->expr()->orX(
376
                $qb->expr()->lte('g.publicationDate', ':date'),
377
                $qb->expr()->isNull('g.publicationDate')
378
            )
379
        );
380
        $and->add(
381
            $qb->expr()->orX(
382
                $qb->expr()->gte('g.closeDate', ':date'),
383
                $qb->expr()->isNull('g.closeDate')
384
            )
385
        );
386
        $qb->setParameter('date', $today);
387
        
388
        $and->add($qb->expr()->eq('g.active', '1'));
389
        $and->add($qb->expr()->eq('g.broadcastPlatform', '1'));
390
        
391
        if ($classType != '') {
392
            $and->add($qb->expr()->eq('g.classType', ':classType'));
393
            $qb->setParameter('classType', $classType);
394
        }
395
        
396
        if ($displayHome) {
397
            $and->add($qb->expr()->eq('g.displayHome', true));
398
        }
399
        
400
        $qb->select('g')
401
        ->from('PlaygroundGame\Entity\Game', 'g')
402
        ->where($and)
403
        ->orderBy($orderBy, 'DESC');
404
        
405
        $query = $qb->getQuery();
406
        $games = $query->getResult();
407
        
408
        // je les classe par date de publication (date comme clé dans le tableau afin de pouvoir merger les objets
409
        // de type article avec le même procédé en les classant naturellement par date asc ou desc
410
        $arrayGames = array();
411 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...
412
            if ($game->getPublicationDate()) {
413
                $key = $game->getPublicationDate()->format('Ymd');
414
            } elseif ($game->getStartDate()) {
415
                $key = $game->getStartDate()->format('Ymd');
416
            } else {
417
                $key = $game->getUpdatedAt()->format('Ymd');
418
            }
419
            $key .= $game->getUpdatedAt()->format('Ymd') . '-' . $game->getId();
420
            $arrayGames[$key] = $game;
421
        }
422
423
        return $arrayGames;
424
    }
425
426
    /**
427
     * getAvailableGames : Games OnLine and not already played by $user
428
     *
429
     * @return Array of PlaygroundGame\Entity\Game
430
     */
431
    public function getAvailableGames($user, $maxResults = 2)
432
    {
433
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
434
        $today = new \DateTime("now");
435
        $today = $today->format('Y-m-d H:i:s');
436
437
        // Game active with a start_date before today (or without start_date)
438
        // and end_date after today (or without end-date)
439
        $query = $em->createQuery('SELECT g FROM PlaygroundGame\Entity\Game g
440
                WHERE NOT EXISTS (SELECT l FROM PlaygroundGame\Entity\Entry l WHERE l.game = g AND l.user = :user)
441
                AND (g.startDate <= :date OR g.startDate IS NULL)
442
                AND (g.endDate >= :date OR g.endDate IS NULL)
443
                AND g.active = 1 AND g.broadcastPlatform = 1
444
                ORDER BY g.startDate ASC');
445
        $query->setParameter('date', $today);
446
        $query->setParameter('user', $user);
447
        $query->setMaxResults($maxResults);
448
        $games = $query->getResult();
449
450
        return $games;
451
    }
452
453 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...
454
    {
455
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
456
457
        $qb = $em->createQueryBuilder();
458
        $qb->select('
459
            e.id,
460
            u.username,
461
            u.title,
462
            u.firstname,
463
            u.lastname,
464
            u.email,
465
            u.optin,
466
            u.optinPartner,
467
            u.address,
468
            u.address2,
469
            u.postalCode,
470
            u.city,
471
            u.country,
472
            u.telephone,
473
            u.mobile,
474
            u.created_at,
475
            u.dob,
476
            e.winner,
477
            e.socialShares,
478
            e.playerData,
479
            e.updated_at
480
            ')
481
            ->from('PlaygroundGame\Entity\Entry', 'e')
482
            ->leftJoin('e.user', 'u')
483
            ->where($qb->expr()->eq('e.game', ':game'));
484
        
485
        $qb->setParameter('game', $game);
486
487
        return $qb->getQuery();
488
    }
489
490
    public function getEntriesHeader($game)
491
    {
492
        if ($game->getPlayerForm()) {
493
            $formPV = json_decode($game->getPlayerForm()->getForm(), true);
494
            $header = array('id'=> 1);
495 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...
496
                foreach ($element as $k => $v) {
497
                    if ($k !== 'form_properties') {
498
                        $header[$v[0]['name']] = 1;
499
                    }
500
                }
501
            }
502
        } else {
503
            $header = array(
504
                'id' => 1,
505
                'username' => 1,
506
                'title' => 1,
507
                'firstname' => 1,
508
                'lastname' => 1,
509
                'email' => 1,
510
                'optin' => 1,
511
                'optinPartner' => 1,
512
                'address' => 1,
513
                'address2' => 1,
514
                'postalCode' => 1,
515
                'city' => 1,
516
                'country' => 1,
517
                'telephone' => 1,
518
                'mobile' => 1,
519
                'created_at' => 1,
520
                'dob' => 1,
521
                'winner' => 1
522
            );
523
        }
524
        $header['winner'] = 1;
525
        $header['socialShares'] = 1;
526
        $header['updated_at'] = 1;
527
528
        return $header;
529
    }
530
531
    /**
532
    * getGameEntries : I create an array of entries based on playerData + header
533
    *
534
    * @return Array of PlaygroundGame\Entity\Game
535
    */
536
    public function getGameEntries($header, $entries, $game)
537
    {
538
        $header = $this->getEntriesHeader($game);
539
540
        $results = array();
541
542
        foreach ($entries as $k => $entry) {
543
            $entryData = json_decode($entry['playerData'], true);
544 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...
545
                if (isset($entryData[$key])) {
546
                    $results[$k][$key] = (is_array($entryData[$key]))?implode(', ', $entryData[$key]):$entryData[$key];
547
                } elseif (array_key_exists($key, $entry)) {
548
                    $results[$k][$key] = ($entry[$key] instanceof \DateTime)?
549
                        $entry[$key]->format('Y-m-d H:i:s'):
550
                        $entry[$key];
551
                } else {
552
                    $results[$k][$key] = '';
553
                }
554
            }
555
        }
556
557
        return $results;
558
    }
559
560
    /**
561
     * getActiveSliderGames
562
     *
563
     * @return Array of PlaygroundGame\Entity\Game
564
     */
565
    public function getActiveSliderGames()
566
    {
567
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
568
        $today = new \DateTime("now");
569
        $today = $today->format('Y-m-d H:i:s');
570
571
        // Game active with a start_date before today (or without start_date)
572
        // and end_date after today (or without end-date)
573
        $query = $em->createQuery('SELECT g FROM PlaygroundGame\Entity\Game g
574
            WHERE (g.publicationDate <= :date OR g.publicationDate IS NULL)
575
            AND (g.closeDate >= :date OR g.closeDate IS NULL)
576
            AND g.active = true AND g.broadcastPlatform = 1 AND g.pushHome = true');
577
        $query->setParameter('date', $today);
578
        $games = $query->getResult();
579
580
        // je les classe par date de publication (date comme clé dans le tableau afin de pouvoir merger les objets
581
        // de type article avec le même procédé en les classant naturellement par date asc ou desc
582
        $arrayGames = array();
583 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...
584
            if ($game->getPublicationDate()) {
585
                $key = $game->getPublicationDate()->format('Ymd');
586
            } elseif ($game->getStartDate()) {
587
                $key = $game->getStartDate()->format('Ymd');
588
            } else {
589
                $key = $game->getUpdatedAt()->format('Ymd');
590
            }
591
            $key .= $game->getUpdatedAt()->format('Ymd') . '-' . $game->getId();
592
            $arrayGames[$key] = $game;
593
        }
594
595
        return $arrayGames;
596
    }
597
598
    /**
599
     * getPrizeCategoryGames
600
     *
601
     * @return Array of PlaygroundGame\Entity\Game
602
     */
603 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...
604
    {
605
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
606
607
        $query = $em->createQuery('SELECT g FROM PlaygroundGame\Entity\Game g
608
            WHERE (g.prizeCategory = :categoryid AND g.broadcastPlatform = 1)
609
            ORDER BY g.publicationDate DESC');
610
        $query->setParameter('categoryid', $categoryid);
611
        $games = $query->getResult();
612
613
        return $games;
614
    }
615
616
    public function checkGame($identifier, $checkIfStarted = true)
617
    {
618
        $gameMapper = $this->getGameMapper();
619
620
        if (! $identifier) {
621
            return false;
622
        }
623
624
        $game = $gameMapper->findByIdentifier($identifier);
625
626
        // the game has not been found
627
        if (! $game) {
628
            return false;
629
        }
630
631
        // for preview stuff as admin
632
        if ($this->isAllowed('game', 'edit')) {
633
            $r =$this->serviceLocator->get('request');
634
            if ($r->getQuery()->get('preview')) {
635
                $game->setActive(true);
636
                $game->setStartDate(null);
637
                $game->setEndDate(null);
638
                $game->setPublicationDate(null);
639
                $game->setBroadcastPlatform(true);
640
641
                // I don't want the game to be updated through any update during the preview mode.
642
                // I mark it as readonly for Doctrine
643
                $this->serviceLocator
644
                    ->get('doctrine.entitymanager.orm_default')
645
                    ->getUnitOfWork()
646
                    ->markReadOnly($game);
647
                    
648
                return $game;
649
            }
650
        }
651
652
        // The game is inactive
653
        if (! $game->getActive()) {
654
            return false;
655
        }
656
657
        // the game has not begun yet
658
        if (! $game->isOpen()) {
659
            return false;
660
        }
661
662
        // the game is finished and closed
663
        if (! $game->isStarted() && $checkIfStarted) {
664
            return false;
665
        }
666
667
        return $game;
668
    }
669
670
    /**
671
     * Return the last entry of the user on this game, if it exists.
672
     * An entry can be associated to :
673
     * - A user account (a real one, linked to PlaygroundUser
674
     * - An anonymous Identifier (based on one value of playerData (generally email))
675
     * - A cookie set on the player device (the less secure)
676
     * If the active param is set, it can check if the entry is active or not.
677
     * If the bonus param is set, it can check if the entry is a bonus or not.
678
     *
679
     * @param unknown $game
680
     * @param string $user
681
     * @param boolean $active
682
     * @param boolean $bonus
683
     * @return boolean
684
     */
685
    public function checkExistingEntry($game, $user = null, $active = null, $bonus = null)
686
    {
687
        $search = array('game'  => $game);
688
689
        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...
690
            $search['user'] = $user;
691
        } elseif ($this->getAnonymousIdentifier()) {
692
            $search['anonymousIdentifier'] = $this->getAnonymousIdentifier();
693
            $search['user'] = null;
694
        } else {
695
            $search['anonymousId'] = $this->getAnonymousId();
696
            $search['user'] = null;
697
        }
698
        
699
        if (! is_null($active)) {
700
            $search['active'] = $active;
701
        }
702
        if (! is_null($bonus)) {
703
            $search['bonus'] = $bonus;
704
        }
705
706
        $entry = $this->getEntryMapper()->findOneBy($search, array('updated_at' => 'desc'));
707
708
        return $entry;
709
    }
710
711
    /*
712
    * This function updates the entry with the player data after checking 
713
    * that the data are compliant with the formUser Game attribute
714
    *
715
    * The $data has to be a json object
716
    */
717
    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...
718
    {
719
        $form = $this->createFormFromJson($game->getPlayerForm()->getForm(), 'playerForm');
720
        $form->setData($data);
721
722
        if (!$mandatory) {
723
            $filter = $form->getInputFilter();
724
            foreach ($form->getElements() as $element) {
725
                try {
726
                    $elementInput = $filter->get($element->getName());
727
                    $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...
728
                    $form->get($element->getName())->setAttribute('required', false);
729
                } 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...
730
                }
731
            }
732
        }
733
734
        if ($form->isValid()) {
735
            $dataJson = json_encode($form->getData());
736
737
            if ($game->getAnonymousAllowed() &&
738
                $game->getAnonymousIdentifier() &&
739
                isset($data[$game->getAnonymousIdentifier()])
740
            ) {
741
                $session = new \Zend\Session\Container('anonymous_identifier');
742
                if (empty($session->offsetGet('anonymous_identifier'))) {
743
                    $anonymousIdentifier = $data[$game->getAnonymousIdentifier()];
744
                
745
                    $entry->setAnonymousIdentifier($anonymousIdentifier);
746
                
747
                    // I must transmit this info during the whole game workflow
748
                    $session->offsetSet('anonymous_identifier', $anonymousIdentifier);
749
                }
750
            }
751
752
            $entry->setPlayerData($dataJson);
753
            $this->getEntryMapper()->update($entry);
754
        } else {
755
            return false;
756
        }
757
758
        return true;
759
    }
760
761
762
    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...
763
    {
764
        // If on Facebook, check if you have to be a FB fan to play the game
765
        $session = new Container('facebook');
766
767
        if ($session->offsetExists('signed_request')) {
768
            // I'm on Facebook
769
            $sr = $session->offsetGet('signed_request');
770
            if ($sr['page']['liked'] == 1) {
771
                return true;
772
            }
773
        } else {
774
            // I'm not on Facebook
775
            return true;
776
        }
777
778
        return false;
779
    }
780
    
781
    public function getAnonymousIdentifier()
782
    {
783
        if (is_null($this->anonymousIdentifier)) {
784
            // If on Facebook, check if you have to be a FB fan to play the game
785
            $session = new Container('anonymous_identifier');
786
            
787
            if ($session->offsetExists('anonymous_identifier')) {
788
                $this->anonymousIdentifier = $session->offsetGet('anonymous_identifier');
789
            } else {
790
                $this->anonymousIdentifier = false;
791
            }
792
        }
793
    
794
        return $this->anonymousIdentifier;
795
    }
796
797
    /**
798
     * errors :
799
     * -1 : user not connected
800
     * -2 : limit entry games for this user reached
801
     *
802
     * @param \PlaygroundGame\Entity\Game $game
803
     * @param \PlaygroundUser\Entity\UserInterface $user
804
     * @return number unknown
805
     */
806
    public function play($game, $user)
807
    {
808
809
        // certaines participations peuvent rester ouvertes.
810
        // On autorise alors le joueur à reprendre là ou il en était
811
        // par exemple les postvote...
812
        $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...
813
814
        if (! $entry) {
815
            if ($this->hasReachedPlayLimit($game, $user)) {
816
                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...
817
            }
818
819
            $entry = new Entry();
820
            $entry->setGame($game);
821
            $entry->setUser($user);
822
            $entry->setPoints(0);
823
            $entry->setIp($this->getIp());
824
            $entry->setAnonymousId($this->getAnonymousId());
825
            if ($this->getAnonymousIdentifier()) {
826
                $entry->setAnonymousIdentifier($this->getAnonymousIdentifier());
827
            }
828
829
            $entry = $this->getEntryMapper()->insert($entry);
830
            $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
831
                'user' => $user,
832
                'game' => $game,
833
                'entry' => $entry
834
            ));
835
        }
836
837
        return $entry;
838
    }
839
840
    /**
841
     * @param \PlaygroundGame\Entity\Game $game
842
     * @param \PlaygroundUser\Entity\UserInterface $user
843
     */
844
    public function hasReachedPlayLimit($game, $user)
845
    {
846
        // Is there a limitation on the game ?
847
        $limitAmount = $game->getPlayLimit();
848
        if ($limitAmount) {
849
            $limitScale = $game->getPlayLimitScale();
850
            $userEntries = $this->findLastEntries($game, $user, $limitScale);
851
852
            // player has reached the game limit
853
            if ($userEntries >= $limitAmount) {
854
                return true;
855
            }
856
        }
857
        return false;
858
    }
859
    
860
    /**
861
     * @param \PlaygroundGame\Entity\Game $game
862
     * @param \PlaygroundUser\Entity\UserInterface $user
863
     */
864
    public function findLastEntries($game, $user, $limitScale)
865
    {
866
        $limitDate = $this->getLimitDate($limitScale);
867
868
        if ($user) {
869
            return $this->getEntryMapper()->findLastEntriesByUser($game, $user, $limitDate);
870
        } elseif ($this->getAnonymousIdentifier()) {
871
            return $this->getEntryMapper()->findLastEntriesByAnonymousIdentifier(
872
                $game,
873
                $this->getAnonymousIdentifier(),
874
                $limitDate
875
            );
876
        } else {
877
            return $this->getEntryMapper()->findLastEntriesByIp($game, $this->getIp(), $limitDate);
878
        }
879
    }
880
881
    /**
882
    *
883
    *
884
    */
885
    public function getLimitDate($limitScale)
886
    {
887
        $now = new \DateTime("now");
888
        switch ($limitScale) {
889
            case 'always':
890
                $interval = 'P100Y';
891
                $now->sub(new \DateInterval($interval));
892
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
893
                break;
894
            case 'day':
895
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
896
                break;
897 View Code Duplication
            case 'week':
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...
898
                $interval = 'P7D';
899
                $now->sub(new \DateInterval($interval));
900
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
901
                break;
902 View Code Duplication
            case 'month':
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...
903
                $interval = 'P1M';
904
                $now->sub(new \DateInterval($interval));
905
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
906
                break;
907 View Code Duplication
            case 'year':
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...
908
                $interval = 'P1Y';
909
                $now->sub(new \DateInterval($interval));
910
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
911
                break;
912 View Code Duplication
            default:
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...
913
                $interval = 'P100Y';
914
                $now->sub(new \DateInterval($interval));
915
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
916
        }
917
918
        return $dateLimit;
919
    }
920
921
    public function findLastActiveEntry($game, $user)
922
    {
923
        return $this->checkExistingEntry($game, $user, true);
924
    }
925
926
    public function findLastInactiveEntry($game, $user)
927
    {
928
        return $this->checkExistingEntry($game, $user, false, false);
929
    }
930
931
    public function findLastEntry($game, $user)
932
    {
933
        return $this->checkExistingEntry($game, $user, null, false);
934
    }
935
936
    public function inviteToTeam($data, $game, $user)
937
    {
938
        $mailService = $this->serviceLocator->get('playgroundgame_message');
939
        $invitationMapper = $this->serviceLocator->get('playgroundgame_invitation_mapper');
940
941
        $sentInvitations = $invitationMapper->findBy(array('host' => $user, 'game' => $game));
942
        $nbInvitations = count($sentInvitations);
943
        $to = $data['email'];
944
        if (empty($to)) {
945
            return ['result'=>false, 'message'=>'no email'];
946
        }
947
948
        if ($nbInvitations < 20) {
949
            $alreadyInvited = $invitationMapper->findBy(array('requestKey' => $to, 'game' => $game));
950
            if (!$alreadyInvited) {
951
                $alreadyInvited = $this->getUserMapper()->findByEmail($to);
952
            }
953
954
            if (empty($alreadyInvited)) {
955
                $invitation = new \PlaygroundGame\Entity\Invitation();
956
                $invitation->setRequestKey($to);
957
                $invitation->setGame($game);
958
                $invitation->setHost($user);
959
                $invitationMapper->insert($invitation);
960
961
                $from = $this->getOptions()->getEmailFromAddress();
962
                $subject = $this->serviceLocator->get('translator')->translate(
963
                    $this->getOptions()->getInviteToTeamSubjectLine(),
964
                    'playgroundgame'
965
                );
966
                $message = $mailService->createHtmlMessage(
967
                    $from,
968
                    $to,
969
                    $subject,
970
                    'playground-game/email/invite_team',
971
                    array(
972
                        'game' => $game,
973
                        'user' => $user,
974
                        'data' => $data,
975
                        'from' => $from
976
                    )
977
                );
978
                try {
979
                    $mailService->send($message);
980
                } catch (\Zend\Mail\Protocol\Exception\RuntimeException $e) {
981
                    return ['result' => true, 'message' => $this->serviceLocator->get('translator')->translate(
982
                        'mail error'
983
                    )];
984
                }
985
986
                return ['result' => true, 'message' => ''];
987
            } else {
988
                return ['result' => false, 'message' => 'already invited'];
989
            }
990
        } else {
991
            return [
992
                'result' => false,
993
                'message' => $this->serviceLocator->get('translator')->translate(
994
                    'Too many invitations for this user'
995
                )
996
            ];
997
        }
998
    }
999
1000
    public function sendShareMail(
1001
        $data,
1002
        $game,
1003
        $user,
1004
        $entry,
1005
        $template = 'share_game',
1006
        $topic = null,
1007
        $userTimer = array(),
1008
        $subject = ''
1009
    ) {
1010
        $mailService = $this->serviceLocator->get('playgroundgame_message');
1011
        $mailSent = false;
1012
        $from = $this->getOptions()->getEmailFromAddress();
1013
1014
        if (empty($subject)) {
1015
            $subject = $this->serviceLocator->get('translator')->translate(
1016
                $this->getOptions()->getShareSubjectLine(),
1017
                'playgroundgame'
1018
            );
1019
        } else {
1020
            $subject = $this->serviceLocator->get('translator')->translate(
1021
                $subject,
1022
                'playgroundgame'
1023
            );
1024
        }
1025
1026
        $renderer = $this->serviceLocator->get('Zend\View\Renderer\RendererInterface');
1027
        $skinUrl = $renderer->url(
1028
            'frontend',
1029
            array(),
1030
            array('force_canonical' => true)
1031
        );
1032
        $secretKey = strtoupper(substr(sha1(uniqid('pg_', true) . '####' . time()), 0, 15));
1033
1034
        if (! $topic) {
1035
            $topic = $game->getTitle();
1036
        }
1037
1038
        if (isset($data['email']) && !is_array($data['email'])) {
1039
            $data['email'] = array($data['email']);
1040
        }
1041
        
1042
        foreach ($data['email'] as $to) {
1043
            $mailSent = true;
1044
            if (!empty($to)) {
1045
                $message = $mailService->createHtmlMessage(
1046
                    $from,
1047
                    $to,
1048
                    $subject,
1049
                    'playground-game/email/' . $template,
1050
                    array(
1051
                        'game' => $game,
1052
                        'data' => $data,
1053
                        'from' => $from,
1054
                        'to' => $to,
1055
                        'secretKey' => $secretKey,
1056
                        'skinUrl' => $skinUrl,
1057
                        'userTimer' => $userTimer
1058
                    )
1059
                );
1060
                try {
1061
                    $mailService->send($message);
1062
                } catch (\Zend\Mail\Protocol\Exception\RuntimeException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
1063
                }
1064
                
1065
                if ($entry) {
1066
                    $shares = json_decode($entry->getSocialShares(), true);
1067
                    (!isset($shares['mail']))? $shares['mail'] = 1:$shares['mail'] += 1;
1068
                }
1069
            }
1070
        }
1071
1072
        if ($mailSent) {
1073
            if ($entry) {
1074
                $sharesJson = json_encode($shares);
0 ignored issues
show
Bug introduced by
The variable $shares 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...
1075
                $entry->setSocialShares($sharesJson);
1076
                $entry = $this->getEntryMapper()->update($entry);
1077
            }
1078
            
1079
            $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1080
                'user' => $user,
1081
                'topic' => $topic,
1082
                'secretKey' => $secretKey,
1083
                'data' => $data,
1084
                'game' => $game,
1085
                'entry' => $entry
1086
            ));
1087
1088
            return true;
1089
        }
1090
1091
        return false;
1092
    }
1093
1094
    /**
1095
     * @param \PlaygroundGame\Entity\Game $game
1096
     * @param \PlaygroundUser\Entity\User $user
1097
     * @param Entry $entry
1098
     * @param \PlaygroundGame\Entity\Prize $prize
1099
     */
1100
    public function sendResultMail($game, $user, $entry, $template = 'entry', $prize = null)
1101
    {
1102
        $mailService = $this->serviceLocator->get('playgroundgame_message');
1103
        $from = $this->getOptions()->getEmailFromAddress();
1104
        if ($user) {
1105
            $to = $user->getEmail();
1106
        } elseif ($entry->getAnonymousIdentifier()) {
1107
            $to = $entry->getAnonymousIdentifier();
1108
        } else {
1109
            return false;
1110
        }
1111
        $subject = $game->getTitle();
1112
        $renderer = $this->serviceLocator->get('Zend\View\Renderer\RendererInterface');
1113
        $skinUrl = $renderer->url(
1114
            'frontend',
1115
            array(),
1116
            array('force_canonical' => true)
1117
        );
1118
        $message = $mailService->createHtmlMessage($from, $to, $subject, 'playground-game/email/' . $template, array(
1119
            'game' => $game,
1120
            'entry' => $entry,
1121
            'skinUrl' => $skinUrl,
1122
            'prize' => $prize
1123
        ));
1124
        $mailService->send($message);
1125
    }
1126
1127
    public function sendGameMail($game, $user, $post, $template = 'postvote')
1128
    {
1129
        $mailService = $this->serviceLocator->get('playgroundgame_message');
1130
        $from = $this->getOptions()->getEmailFromAddress();
1131
        $to = $user->getEmail();
1132
        $subject = $this->serviceLocator->get('translator')->translate(
1133
            $this->getOptions()->getParticipationSubjectLine(),
1134
            'playgroundgame'
1135
        );
1136
        $renderer = $this->serviceLocator->get('Zend\View\Renderer\RendererInterface');
1137
        $skinUrl = $renderer->url(
1138
            'frontend',
1139
            array(),
1140
            array('force_canonical' => true)
1141
        );
1142
1143
        $message = $mailService->createHtmlMessage($from, $to, $subject, 'playground-game/email/' . $template, array(
1144
            'game' => $game,
1145
            'post' => $post,
1146
            'skinUrl' => $skinUrl
1147
        ));
1148
        $mailService->send($message);
1149
    }
1150
1151 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...
1152
    {
1153
        $topic = $game->getTitle();
1154
        
1155
        $shares = json_decode($entry->getSocialShares(), true);
1156
        if (!isset($shares['fbwall'])) {
1157
            $shares['fbwall'] = 1;
1158
        } else {
1159
            $shares['fbwall'] += 1;
1160
        }
1161
        $sharesJson = json_encode($shares);
1162
        $entry->setSocialShares($sharesJson);
1163
        $entry = $this->getEntryMapper()->update($entry);
1164
        
1165
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1166
            'user' => $user,
1167
            'game' => $game,
1168
            'secretKey' => $secretKey,
1169
            'topic' => $topic,
1170
            'entry' => $entry
1171
        ));
1172
1173
        return true;
1174
    }
1175
1176
    public function postFbRequest($secretKey, $game, $user, $entry, $to)
1177
    {
1178
        $shares = json_decode($entry->getSocialShares(), true);
1179
        $to = explode(',', $to);
1180
        if (!isset($shares['fbrequest'])) {
1181
            $shares['fbrequest'] = count($to);
1182
        } else {
1183
            $shares['fbrequest'] += count($to);
1184
        }
1185
        $sharesJson = json_encode($shares);
1186
        $entry->setSocialShares($sharesJson);
1187
        $entry = $this->getEntryMapper()->update($entry);
1188
        
1189
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1190
            'user' => $user,
1191
            'game' => $game,
1192
            'secretKey' => $secretKey,
1193
            'entry' => $entry,
1194
            'invites' => count($to)
1195
        ));
1196
1197
        return true;
1198
    }
1199
1200 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...
1201
    {
1202
        $topic = $game->getTitle();
1203
1204
        $shares = json_decode($entry->getSocialShares(), true);
1205
        if (!isset($shares['fbrequest'])) {
1206
            $shares['tweet'] = 1;
1207
        } else {
1208
            $shares['tweet'] += 1;
1209
        }
1210
        $sharesJson = json_encode($shares);
1211
        $entry->setSocialShares($sharesJson);
1212
        $entry = $this->getEntryMapper()->update($entry);
1213
        
1214
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1215
            'user' => $user,
1216
            'game' => $game,
1217
            'secretKey' => $secretKey,
1218
            'topic' => $topic,
1219
            'entry' => $entry
1220
        ));
1221
1222
        return true;
1223
    }
1224
1225 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...
1226
    {
1227
        $topic = $game->getTitle();
1228
        
1229
        $shares = json_decode($entry->getSocialShares(), true);
1230
        if (!isset($shares['fbrequest'])) {
1231
            $shares['google'] = 1;
1232
        } else {
1233
            $shares['google'] += 1;
1234
        }
1235
        $sharesJson = json_encode($shares);
1236
        $entry->setSocialShares($sharesJson);
1237
        $entry = $this->getEntryMapper()->update($entry);
1238
1239
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1240
            'user' => $user,
1241
            'game' => $game,
1242
            'secretKey' => $secretKey,
1243
            'topic' => $topic,
1244
            'entry' => $entry
1245
        ));
1246
1247
        return true;
1248
    }
1249
1250
    /**
1251
     * Is it possible to trigger a bonus entry ?
1252
     *
1253
     * @param unknown_type $game
1254
     * @param unknown_type $user
1255
     */
1256
    public function allowBonus($game, $user)
1257
    {
1258
        if (! $game->getPlayBonus() || $game->getPlayBonus() == 'none') {
1259
            return false;
1260
        } elseif ($game->getPlayBonus() == 'one') {
1261
            if ($this->getEntryMapper()->findOneBy(array(
1262
                'game' => $game,
1263
                'user' => $user,
1264
                'bonus' => 1
1265
            ))) {
1266
                return false;
1267
            } else {
1268
                return true;
1269
            }
1270
        } elseif ($game->getPlayBonus() == 'per_entry') {
1271
            return $this->getEntryMapper()->checkBonusEntry($game, $user);
1272
        }
1273
1274
        return false;
1275
    }
1276
1277
    public function addAnotherEntry($game, $user, $winner = 0)
1278
    {
1279
        $entry = new Entry();
1280
        $entry->setGame($game);
1281
        $entry->setUser($user);
1282
        $entry->setPoints(0);
1283
        $entry->setIp($this->getIp());
1284
        $entry->setActive(0);
1285
        $entry->setBonus(1);
1286
        $entry->setWinner($winner);
1287
        $entry = $this->getEntryMapper()->insert($entry);
1288
1289
        return $entry;
1290
    }
1291
1292
    /**
1293
     * This bonus entry doesn't give points nor badges
1294
     * It's just there to increase the chances during the Draw
1295
     * Old Name playBonus
1296
     *
1297
     * @param PlaygroundGame\Entity\Game $game
1298
     * @param unknown $user
1299
     * @return boolean unknown
1300
     */
1301
    public function addAnotherChance($game, $user, $winner = 0)
1302
    {
1303
        if ($this->allowBonus($game, $user)) {
1304
            $this->addAnotherEntry($game, $user, $winner);
1305
1306
            return true;
1307
        }
1308
1309
        return false;
1310
    }
1311
1312
    /**
1313
     * This bonus entry doesn't give points nor badges but can play again
1314
     *
1315
     * @param PlaygroundGame\Entity\Game $game
1316
     * @param user $user
1317
     * @return boolean unknown
1318
     */
1319
    public function playAgain($game, $user, $winner = 0)
1320
    {
1321
        if ($this->allowBonus($game, $user)) {
1322
            $entry = $this->addAnotherEntry($game, $user, $winner);
1323
            $entry->setActive(1);
1324
            $entry = $this->getEntryMapper()->update($entry);
1325
            if ($entry->getActive() == 1) {
1326
                return true;
1327
            }
1328
        }
1329
1330
        return false;
1331
    }
1332
1333
    /**
1334
     * @param string $path
1335
     * @param boolean $noReplace : If the image name already exist, don't replace it but change the name
1336
     */
1337
    public function uploadFile($path, $file, $noReplace = true)
1338
    {
1339
        $err = $file["error"];
1340
        $message = '';
1341
        if ($err > 0) {
1342
            switch ($err) {
1343
                case '1':
1344
                    $message .= 'Max file size exceeded. (php.ini)';
1345
                    break;
1346
                case '2':
1347
                    $message .= 'Max file size exceeded.';
1348
                    break;
1349
                case '3':
1350
                    $message .= 'File upload was only partial.';
1351
                    break;
1352
                case '4':
1353
                    $message .= 'No file was attached.';
1354
                    break;
1355
                case '7':
1356
                    $message .= 'File permission denied.';
1357
                    break;
1358
                default:
1359
                    $message .= 'Unexpected error occurs.';
1360
            }
1361
1362
            return $err;
1363
        } else {
1364
            $fileNewname = $this->fileNewname($path, $file['name'], $noReplace);
1365
1366
            if (isset($file["base64"])) {
1367
                list(, $img) = explode(',', $file["base64"]);
1368
                $img = str_replace(' ', '+', $img);
1369
                $im = base64_decode($img);
1370
                if ($im !== false) {
1371
                    // getimagesizefromstring
1372
                    file_put_contents($path . $fileNewname, $im);
1373
                } else {
1374
                    return 1;
1375
                }
1376
1377
                return $fileNewname;
1378
            } else {
1379
                $adapter = new \Zend\File\Transfer\Adapter\Http();
1380
                // 1Mo
1381
                $size = new Size(array(
1382
                    'max' => 1024000
1383
                ));
1384
                $is_image = new IsImage('jpeg,png,gif,jpg');
1385
                $adapter->setValidators(array(
1386
                    $size,
1387
                    $is_image
1388
                ), $fileNewname);
1389
1390
                if (! $adapter->isValid()) {
1391
                    return false;
1392
                }
1393
1394
                @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...
1395
            }
1396
1397
            
1398
            if (class_exists("Imagick")) {
1399
                $ext = pathinfo($fileNewname, PATHINFO_EXTENSION);
1400
                $img = new \Imagick($path . $fileNewname);
1401
                $img->cropThumbnailImage(100, 100);
1402
                $img->setImageCompression(\Imagick::COMPRESSION_JPEG);
1403
                $img->setImageCompressionQuality(75);
1404
                // Strip out unneeded meta data
1405
                $img->stripImage();
1406
                $img->writeImage($path . str_replace('.'.$ext, '-thumbnail.'.$ext, $fileNewname));
1407
                ErrorHandler::stop(true);
1408
            }
1409
        }
1410
1411
        return $fileNewname;
1412
    }
1413
1414
    /**
1415
     * @param string $path
1416
     */
1417
    public function fileNewname($path, $filename, $generate = false)
1418
    {
1419
        $sanitize = new Sanitize();
1420
        $name = $sanitize->filter($filename);
1421
        $newpath = $path . $name;
1422
1423
        if ($generate) {
1424
            if (file_exists($newpath)) {
1425
                $filename = pathinfo($name, PATHINFO_FILENAME);
1426
                $ext = pathinfo($name, PATHINFO_EXTENSION);
1427
1428
                $name = $filename . '_' . rand(0, 99) . '.' . $ext;
1429
            }
1430
        }
1431
1432
        unset($sanitize);
1433
1434
        return $name;
1435
    }
1436
1437
    /**
1438
     * This function returns the list of games, order by $type
1439
     */
1440
    public function getQueryGamesOrderBy($type = 'createdAt', $order = 'DESC')
1441
    {
1442
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
1443
        $today = new \DateTime("now");
1444
        $today = $today->format('Y-m-d H:i:s');
1445
1446
        $onlineGames = '(
1447
            (
1448
                CASE WHEN (
1449
                    g.active = 1
1450
                    AND g.broadcastPlatform = 1
1451
                    AND (g.startDate <= :date OR g.startDate IS NULL)
1452
                    AND (g.closeDate >= :date OR g.closeDate IS NULL)
1453
                ) THEN 1 ELSE 0 END
1454
            ) +
1455
            (
1456
                CASE WHEN (
1457
                    g.active = 0
1458
                    AND (g.broadcastPlatform = 0 OR g.broadcastPlatform IS NULL)
1459
                    AND g.startDate > :date
1460
                    AND g.closeDate < :date
1461
                ) THEN 1 ELSE 0 END
1462
            )
1463
        )';
1464
1465
        $qb = $em->createQueryBuilder();
1466
        $qb->select('g')->from('PlaygroundGame\Entity\Game', 'g');
1467
        
1468
        switch ($type) {
1469
            case 'startDate':
1470
                $qb->orderBy('g.startDate', $order);
1471
                break;
1472
            case 'activeGames':
1473
                $qb->orderBy('g.active', $order);
1474
                break;
1475
            case 'onlineGames':
1476
                $qb->orderBy($onlineGames, $order);
1477
                $qb->setParameter('date', $today);
1478
                break;
1479
            case 'createdAt':
1480
                $qb->orderBy('g.createdAt', $order);
1481
                break;
1482
        }
1483
1484
        $query = $qb->getQuery();
1485
1486
        return $query;
1487
    }
1488
1489
    public function draw($game)
1490
    {
1491
        $total = $game->getWinners();
1492
1493
        // I Have to know what is the User Class used
1494
        $zfcUserOptions = $this->serviceLocator->get('zfcuser_module_options');
1495
        $userClass = $zfcUserOptions->getUserEntityClass();
1496
1497
        $result = $this->getEntryMapper()->draw($game, $userClass, $total);
1498
1499
        foreach ($result as $e) {
1500
            $e->setWinner(1);
1501
            $e = $this->getEntryMapper()->update($e);
1502
            $this->getEventManager()->trigger('win_lottery.post', $this, array(
1503
                'user' => $e->getUser(),
1504
                'game' => $game,
1505
                'entry' => $e
1506
            ));
1507
        }
1508
1509
        return $result;
1510
    }
1511
1512
    /**
1513
     * getGameMapper
1514
     *
1515
     * @return GameMapperInterface
1516
     */
1517 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...
1518
    {
1519
        if (null === $this->gameMapper) {
1520
            $this->gameMapper = $this->serviceLocator->get('playgroundgame_game_mapper');
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->serviceLocator->g...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...
1521
        }
1522
1523
        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 1523 which is incompatible with the return type documented by PlaygroundGame\Service\Game::getGameMapper of type PlaygroundGame\Mapper\GameInterface.
Loading history...
1524
    }
1525
1526
    /**
1527
     * setGameMapper
1528
     *
1529
     * @param GameMapperInterface $gameMapper
1530
     * @return Game
1531
     */
1532
    public function setGameMapper(GameMapperInterface $gameMapper)
1533
    {
1534
        $this->gameMapper = $gameMapper;
1535
1536
        return $this;
1537
    }
1538
1539
    /**
1540
     * getEntryMapper
1541
     *
1542
     * @return EntryMapperInterface
1543
     */
1544
    public function getEntryMapper()
1545
    {
1546
        if (null === $this->entryMapper) {
1547
            $this->entryMapper = $this->serviceLocator->get('playgroundgame_entry_mapper');
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->serviceLocator->g...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...
1548
        }
1549
1550
        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 1550 which is incompatible with the return type documented by PlaygroundGame\Service\Game::getEntryMapper of type PlaygroundGame\Service\EntryMapperInterface.
Loading history...
1551
    }
1552
1553
    /**
1554
     * setEntryMapper
1555
     *
1556
     * @param EntryMapperInterface $entryMapper
1557
     * @return Game
1558
     */
1559
    public function setEntryMapper($entryMapper)
1560
    {
1561
        $this->entryMapper = $entryMapper;
1562
1563
        return $this;
1564
    }
1565
1566
    public function setOptions(ModuleOptions $options)
1567
    {
1568
        $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...
1569
1570
        return $this;
1571
    }
1572
1573
    public function getOptions()
1574
    {
1575
        if (! $this->options instanceof ModuleOptions) {
1576
            $this->setOptions($this->serviceLocator
0 ignored issues
show
Documentation introduced by
$this->serviceLocator->g...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...
1577
                ->get('playgroundgame_module_options'));
1578
        }
1579
1580
        return $this->options;
1581
    }
1582
1583
    /**
1584
     * @param string $str
1585
     */
1586
    public function getExtension($str)
1587
    {
1588
        $i = strrpos($str, '.');
1589
1590
        $l = strlen($str) - $i;
1591
        $ext = substr($str, $i + 1, $l);
1592
1593
        return $ext;
1594
    }
1595
1596
    /**
1597
     * @param string $extension
1598
     */
1599
    public function getSrc($extension, $temp_path)
1600
    {
1601
        $image_src = '';
1602
        switch ($extension) {
1603
            case 'jpg':
1604
                $image_src = imagecreatefromjpeg($temp_path);
1605
                break;
1606
            case 'jpeg':
1607
                $image_src = imagecreatefromjpeg($temp_path);
1608
                break;
1609
            case 'png':
1610
                $image_src = imagecreatefrompng($temp_path);
1611
                break;
1612
            case 'gif':
1613
                $image_src = imagecreatefromgif($temp_path);
1614
                break;
1615
        }
1616
1617
        return $image_src;
1618
    }
1619
1620
    /**
1621
     * @param string $extension
1622
     * @param string $rep
1623
     * @param integer $mini_width
1624
     * @param integer $mini_height
1625
     */
1626
    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...
1627
    {
1628
        list($src_width, $src_height) = getimagesize($tmp_file);
1629
1630
        $ratio_src = $src_width / $src_height;
1631
        $ratio_mini = $mini_width / $mini_height;
1632
1633
        if ($ratio_src >= $ratio_mini) {
1634
            $new_height_mini = $mini_height;
1635
            $new_width_mini = $src_width / ($src_height / $mini_height);
1636
        } else {
1637
            $new_width_mini = $mini_width;
1638
            $new_height_mini = $src_height / ($src_width / $mini_width);
1639
        }
1640
1641
        $new_image_mini = imagecreatetruecolor($mini_width, $mini_height);
1642
1643
        imagecopyresampled(
1644
            $new_image_mini,
1645
            $src,
1646
            0 - ($new_width_mini - $mini_width) / 2,
1647
            0 - ($new_height_mini - $mini_height) / 2,
1648
            0,
1649
            0,
1650
            $new_width_mini,
1651
            $new_height_mini,
1652
            $src_width,
1653
            $src_height
1654
        );
1655
        imagejpeg($new_image_mini, $rep);
1656
1657
        imagedestroy($new_image_mini);
1658
    }
1659
1660
    public function getGameEntity()
1661
    {
1662
        return new \PlaygroundGame\Entity\Game();
1663
    }
1664
1665
    /**
1666
     * @param string $resource
1667
     * @param string $privilege
1668
     */
1669
    public function isAllowed($resource, $privilege = null)
1670
    {
1671
        $auth = $this->serviceLocator->get('BjyAuthorize\Service\Authorize');
1672
1673
        return $auth->isAllowed($resource, $privilege);
1674
    }
1675
1676
    public function getIp()
1677
    {
1678
        $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...
1679
        if (isset($_SERVER['HTTP_CLIENT_IP'])) {
1680
            $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
1681
        } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1682
            $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
1683
        } elseif (isset($_SERVER['HTTP_X_FORWARDED'])) {
1684
            $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
1685
        } elseif (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
1686
            $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
1687
        } elseif (isset($_SERVER['HTTP_FORWARDED'])) {
1688
            $ipaddress = $_SERVER['HTTP_FORWARDED'];
1689
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
1690
            $ipaddress = $_SERVER['REMOTE_ADDR'];
1691
        } else {
1692
            $ipaddress = 'UNKNOWN';
1693
        }
1694
1695
        return $ipaddress;
1696
    }
1697
1698
    public function getAnonymousId()
1699
    {
1700
        $anonymousId = '';
1701
        if ($_COOKIE && array_key_exists('pg_anonymous', $_COOKIE)) {
1702
            $anonymousId = $_COOKIE['pg_anonymous'];
1703
        }
1704
1705
        return $anonymousId;
1706
    }
1707
1708
    /**
1709
     *
1710
     *
1711
     * This service is ready for all types of games
1712
     *
1713
     * @param array $data
1714
     * @return \PlaygroundGame\Entity\Game
1715
     */
1716 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...
1717
    {
1718
        $title = '';
1719
        $description = '';
1720
1721
        if ($data['form_jsonified']) {
1722
            $jsonPV = json_decode($data['form_jsonified']);
1723
            foreach ($jsonPV as $element) {
1724
                if ($element->form_properties) {
1725
                    $attributes = $element->form_properties[0];
1726
                    $title = $attributes->title;
1727
                    $description = $attributes->description;
1728
1729
                    break;
1730
                }
1731
            }
1732
        }
1733
        if (! $form) {
1734
            $form = new \PlaygroundGame\Entity\PlayerForm();
1735
        }
1736
        $form->setGame($game);
1737
        $form->setTitle($title);
1738
        $form->setDescription($description);
1739
        $form->setForm($data['form_jsonified']);
1740
        $form->setFormTemplate($data['form_template']);
1741
1742
        $form = $this->getPlayerFormMapper()->insert($form);
1743
1744
        return $form;
1745
    }
1746
1747
    /**
1748
     *  getCSV creates lines of CSV and returns it.
1749
     */
1750
    public function getCSV($array)
1751
    {
1752
        ob_start(); // buffer the output ...
1753
        $out = fopen('php://output', 'w');
1754
        fputcsv($out, array_keys($array[0]), ";");
1755
        foreach ($array as $line) {
1756
            fputcsv($out, $line, ";");
1757
        }
1758
        fclose($out);
1759
        return ob_get_clean(); // ... then return it as a string!
1760
    }
1761
    
1762
    public function getAttributes($attributes)
1763
    {
1764
        $a = array();
1765
1766
        $a['name']          = isset($attributes->name)? $attributes->name : '';
1767
        $a['placeholder']   = isset($attributes->data->placeholder)? $attributes->data->placeholder : '';
1768
        $a['label']         = isset($attributes->data->label)? $attributes->data->label : '';
1769
        $a['required']      = (isset($attributes->data->required) && $attributes->data->required == 'true')?
1770
            true:
1771
            false;
1772
        $a['class']         = isset($attributes->data->class)? $attributes->data->class : '';
1773
        $a['id']            = isset($attributes->data->id)? $attributes->data->id : '';
1774
        $a['lengthMin']     = isset($attributes->data->length)? $attributes->data->length->min : '';
1775
        $a['lengthMax']     = isset($attributes->data->length)? $attributes->data->length->max : '';
1776
        $a['validator']     = isset($attributes->data->validator)? $attributes->data->validator : '';
1777
        $a['innerData']     = isset($attributes->data->innerData)? $attributes->data->innerData : array();
1778
        $a['dropdownValues']= isset($attributes->data->dropdownValues)?
1779
            $attributes->data->dropdownValues :
1780
            array();
1781
        $a['filesizeMin']   = isset($attributes->data->filesize)? $attributes->data->filesize->min : 0;
1782
        $a['filesizeMax']   = isset($attributes->data->filesize)? $attributes->data->filesize->max : 10*1024*1024;
1783
1784
        return $a;
1785
    }
1786
1787
    /**
1788
     * @param \Zend\InputFilter\InputFilter $inputFilter
1789
     */
1790
    public function decorate($element, $attr, $inputFilter)
1791
    {
1792
        $factory = new InputFactory();
1793
        $element->setAttributes(
1794
            array(
1795
                'placeholder'   => $attr['placeholder'],
1796
                'required'      => $attr['required'],
1797
                'class'         => $attr['class'],
1798
                'id'            => $attr['id']
1799
            )
1800
        );
1801
1802
        $options = array();
1803
        $options['encoding'] = 'UTF-8';
1804
        if ($attr['lengthMin'] && $attr['lengthMin'] > 0) {
1805
            $options['min'] = $attr['lengthMin'];
1806
        }
1807
        if ($attr['lengthMax'] && $attr['lengthMax'] > $attr['lengthMin']) {
1808
            $options['max'] = $attr['lengthMax'];
1809
            $element->setAttribute('maxlength', $attr['lengthMax']);
1810
            $options['messages'] = array(
1811
                \Zend\Validator\StringLength::TOO_LONG => sprintf(
1812
                    $this->serviceLocator->get('translator')->translate(
1813
                        'This field contains more than %s characters',
1814
                        'playgroundgame'
1815
                    ),
1816
                    $attr['lengthMax']
1817
                )
1818
            );
1819
        }
1820
1821
        $validators = array(
1822
            array(
1823
                'name'    => 'StringLength',
1824
                'options' => $options,
1825
            ),
1826
        );
1827
        if ($attr['validator']) {
1828
            $regex = "/.*\(([^)]*)\)/";
1829
            preg_match($regex, $attr['validator'], $matches);
1830
            $valArray = array(
1831
                'name' => str_replace(
1832
                    '('.$matches[1].')',
1833
                    '',
1834
                    $attr['validator']
1835
                ),
1836
                'options' => array($matches[1])
1837
            );
1838
            $validators[] = $valArray;
1839
        }
1840
1841
        $inputFilter->add($factory->createInput(array(
1842
            'name'     => $attr['name'],
1843
            'required' => $attr['required'],
1844
            'filters'  => array(
1845
                array('name' => 'StripTags'),
1846
                array('name' => 'StringTrim'),
1847
            ),
1848
            'validators' => $validators,
1849
        )));
1850
1851
        return $element;
1852
    }
1853
    /**
1854
     * Create a ZF2 Form from json data
1855
     * @return Form
1856
     */
1857
    public function createFormFromJson($jsonForm, $id = 'jsonForm')
1858
    {
1859
        $formPV = json_decode($jsonForm);
1860
        
1861
        $form = new Form();
1862
        $form->setAttribute('id', $id);
1863
        $form->setAttribute('enctype', 'multipart/form-data');
1864
        
1865
        $inputFilter = new \Zend\InputFilter\InputFilter();
1866
        $factory = new InputFactory();
1867
        
1868
        foreach ($formPV as $element) {
1869 View Code Duplication
            if (isset($element->line_text)) {
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...
1870
                $attr  = $this->getAttributes($element->line_text[0]);
1871
                $element = new Element\Text($attr['name']);
1872
                $element = $this->decorate($element, $attr, $inputFilter);
1873
                $form->add($element);
1874
            }
1875 View Code Duplication
            if (isset($element->line_password)) {
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...
1876
                $attr = $this->getAttributes($element->line_password[0]);
1877
                $element = new Element\Password($attr['name']);
1878
                $element = $this->decorate($element, $attr, $inputFilter);
1879
                $form->add($element);
1880
            }
1881 View Code Duplication
            if (isset($element->line_hidden)) {
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...
1882
                $attr = $this->getAttributes($element->line_hidden[0]);
1883
                $element = new Element\Hidden($attr['name']);
1884
                $element = $this->decorate($element, $attr, $inputFilter);
1885
                $form->add($element);
1886
            }
1887 View Code Duplication
            if (isset($element->line_email)) {
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...
1888
                $attr = $this->getAttributes($element->line_email[0]);
1889
                $element = new Element\Email($attr['name']);
1890
                $element = $this->decorate($element, $attr, $inputFilter);
1891
                $form->add($element);
1892
            }
1893 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...
1894
                $attr = $this->getAttributes($element->line_radio[0]);
1895
                $element = new Element\Radio($attr['name']);
1896
1897
                $element->setLabel($attr['label']);
1898
                $element->setAttributes(
1899
                    array(
1900
                        'name'      => $attr['name'],
1901
                        'required'  => $attr['required'],
1902
                        'allowEmpty'=> !$attr['required'],
1903
                        'class'     => $attr['class'],
1904
                        'id'        => $attr['id']
1905
                    )
1906
                );
1907
                $values = array();
1908
                foreach ($attr['innerData'] as $value) {
1909
                    $values[] = $value->label;
1910
                }
1911
                $element->setValueOptions($values);
1912
        
1913
                $options = array();
1914
                $options['encoding'] = 'UTF-8';
1915
                $options['disable_inarray_validator'] = true;
1916
        
1917
                $element->setOptions($options);
1918
        
1919
                $form->add($element);
1920
        
1921
                $inputFilter->add($factory->createInput(array(
1922
                    'name'     => $attr['name'],
1923
                    'required' => $attr['required'],
1924
                    'allowEmpty' => !$attr['required'],
1925
                )));
1926
            }
1927 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...
1928
                $attr = $this->getAttributes($element->line_checkbox[0]);
1929
                $element = new Element\MultiCheckbox($attr['name']);
1930
        
1931
                $element->setLabel($attr['label']);
1932
                $element->setAttributes(
1933
                    array(
1934
                        'name'      => $attr['name'],
1935
                        'required'  => $attr['required'],
1936
                        'allowEmpty'=> !$attr['required'],
1937
                        'class'     => $attr['class'],
1938
                        'id'        => $attr['id']
1939
                    )
1940
                );
1941
1942
                $values = array();
1943
                foreach ($attr['innerData'] as $value) {
1944
                    $values[] = $value->label;
1945
                }
1946
                $element->setValueOptions($values);
1947
                $form->add($element);
1948
        
1949
                $options = array();
1950
                $options['encoding'] = 'UTF-8';
1951
                $options['disable_inarray_validator'] = true;
1952
        
1953
                $element->setOptions($options);
1954
        
1955
                $inputFilter->add($factory->createInput(array(
1956
                    'name'      => $attr['name'],
1957
                    'required'  => $attr['required'],
1958
                    'allowEmpty'=> !$attr['required'],
1959
                )));
1960
            }
1961 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...
1962
                $attr = $this->getAttributes($element->line_dropdown[0]);
1963
                $element = new Element\Select($attr['name']);
1964
1965
                $element->setLabel($attr['label']);
1966
                $element->setAttributes(
1967
                    array(
1968
                        'name'      => $attr['name'],
1969
                        'required'  => $attr['required'],
1970
                        'allowEmpty'=> !$attr['required'],
1971
                        'class'     => $attr['class'],
1972
                        'id'        => $attr['id']
1973
                    )
1974
                );
1975
                $values = array();
1976
                foreach ($attr['dropdownValues'] as $value) {
1977
                    $values[] = $value->dropdown_label;
1978
                }
1979
                $element->setValueOptions($values);
1980
                $form->add($element);
1981
        
1982
                $options = array();
1983
                $options['encoding'] = 'UTF-8';
1984
                $options['disable_inarray_validator'] = true;
1985
        
1986
                $element->setOptions($options);
1987
        
1988
                $inputFilter->add($factory->createInput(array(
1989
                    'name'     => $attr['name'],
1990
                    'required' => $attr['required'],
1991
                    'allowEmpty' => !$attr['required'],
1992
                )));
1993
            }
1994 View Code Duplication
            if (isset($element->line_paragraph)) {
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...
1995
                $attr = $this->getAttributes($element->line_paragraph[0]);
1996
                $element = new Element\Textarea($attr['name']);
1997
                $element = $this->decorate($element, $attr, $inputFilter);
1998
                $form->add($element);
1999
            }
2000
            if (isset($element->line_upload)) {
2001
                $attr = $this->getAttributes($element->line_upload[0]);
2002
                $element = new Element\File($attr['name']);
2003
2004
                $element->setLabel($attr['label']);
2005
                $element->setAttributes(
2006
                    array(
2007
                        'name'      => $attr['name'],
2008
                        'required'  => $attr['required'],
2009
                        'class'     => $attr['class'],
2010
                        'id'        => $attr['id']
2011
                    )
2012
                );
2013
                $form->add($element);
2014
        
2015
                $inputFilter->add($factory->createInput(array(
2016
                    'name'     => $attr['name'],
2017
                    'required' => $attr['required'],
2018
                    'validators' => array(
2019
                        array(
2020
                            'name' => '\Zend\Validator\File\Size',
2021
                            'options' => array('min' => $attr['filesizeMin'], 'max' => $attr['filesizeMax'])
2022
                        ),
2023
                        array(
2024
                            'name' => '\Zend\Validator\File\Extension',
2025
                            'options'  => array(
2026
                                'png,PNG,jpg,JPG,jpeg,JPEG,gif,GIF',
2027
                                'messages' => array(
2028
                                    \Zend\Validator\File\Extension::FALSE_EXTENSION =>'Veuillez télécharger une image'
2029
                                )
2030
                            )
2031
                        ),
2032
                    ),
2033
                )));
2034
            }
2035
        }
2036
        
2037
        $form->setInputFilter($inputFilter);
2038
        
2039
        return $form;
2040
    }
2041
2042
    /**
2043
     * Send mail for winner and/or loser
2044
     * @param \PlaygroundGame\Entity\Game $game
2045
     * @param \PlaygroundUser\Entity\User $user
2046
     * @param \PlaygroundGame\Entity\Entry $lastEntry
2047
     * @param \PlaygroundGame\Entity\Prize $prize
2048
     */
2049
    public function sendMail($game, $user, $lastEntry, $prize = null)
2050
    {
2051 View Code Duplication
        if (($user || ($game->getAnonymousAllowed() && $game->getAnonymousIdentifier())) &&
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
2052
            $game->getMailWinner() &&
2053
            $lastEntry->getWinner()
2054
        ) {
2055
            $this->sendResultMail($game, $user, $lastEntry, 'winner', $prize);
2056
        }
2057
2058 View Code Duplication
        if (($user || ($game->getAnonymousAllowed() && $game->getAnonymousIdentifier())) &&
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
2059
            $game->getMailLooser() &&
2060
            !$lastEntry->getWinner()
2061
        ) {
2062
            $this->sendResultMail($game, $user, $lastEntry, 'looser');
2063
        }
2064
    }
2065
2066
    public function getPlayerFormMapper()
2067
    {
2068
        if (null === $this->playerformMapper) {
2069
            $this->playerformMapper = $this->serviceLocator->get('playgroundgame_playerform_mapper');
2070
        }
2071
2072
        return $this->playerformMapper;
2073
    }
2074
2075
    public function setPlayerFormMapper($playerformMapper)
2076
    {
2077
        $this->playerformMapper = $playerformMapper;
2078
2079
        return $this;
2080
    }
2081
2082
    public function getInvitationMapper()
2083
    {
2084
        if (null === $this->invitationMapper) {
2085
            $this->invitationMapper = $this->serviceLocator->get('playgroundgame_invitation_mapper');
2086
        }
2087
2088
        return $this->invitationMapper;
2089
    }
2090
2091
    public function setInvitationMapper($invitationMapper)
2092
    {
2093
        $this->invitationMapper = $invitationMapper;
2094
2095
        return $this;
2096
    }
2097
2098
    /**
2099
     * getUserMapper
2100
     *
2101
     * @return UserMapperInterface
2102
     */
2103
    public function getUserMapper()
2104
    {
2105
        if (null === $this->userMapper) {
2106
            $this->userMapper = $this->serviceLocator->get('zfcuser_user_mapper');
2107
        }
2108
2109
        return $this->userMapper;
2110
    }
2111
2112
    /**
2113
     * getUserMapper
2114
     *
2115
     * @return ServiceManager
2116
     */
2117
    public function getServiceManager()
2118
    {
2119
        return $this->serviceLocator;
2120
    }
2121
}
2122