Completed
Pull Request — master (#365)
by greg
34:28 queued 31:15
created

Game::getEventManager()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7

Duplication

Lines 7
Ratio 100 %

Importance

Changes 0
Metric Value
dl 7
loc 7
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 0
1
<?php
2
namespace PlaygroundGame\Service;
3
4
use PlaygroundGame\Entity\Entry;
5
use Zend\Session\Container;
6
use Zend\ServiceManager\ServiceManager;
7
use Zend\EventManager\EventManagerAwareTrait;
8
use Zend\EventManager\EventManager;
9
use PlaygroundGame\Options\ModuleOptions;
10
use PlaygroundGame\Mapper\GameInterface as GameMapperInterface;
11
use DoctrineModule\Validator\NoObjectExists as NoObjectExistsValidator;
12
use Zend\Validator\File\Size;
13
use Zend\Validator\File\IsImage;
14
use Zend\Stdlib\ErrorHandler;
15
use PlaygroundCore\Filter\Sanitize;
16
use Zend\Form\Element;
17
use Zend\Form\Form;
18
use Zend\InputFilter\Factory as InputFactory;
19
use Zend\ServiceManager\ServiceLocatorInterface;
20
21
class Game
22
{
23
    use EventManagerAwareTrait;
24
25
    /**
26
     *
27
     * @var GameMapperInterface
28
     */
29
    protected $gameMapper;
30
31
    /**
32
     *
33
     * @var EntryMapperInterface
34
     */
35
    protected $entryMapper;
36
37
    /**
38
     *
39
     * @var UserServiceOptionsInterface
40
     */
41
    protected $options;
42
43
    protected $playerformMapper;
44
45
    protected $invitationMapper;
46
47
    protected $userMapper;
48
    
49
    protected $anonymousIdentifier = null;
50
51
    /**
52
     *
53
     * @var ServiceManager
54
     */
55
    protected $serviceLocator;
56
57
    protected $event;
58
59
    public function __construct(ServiceLocatorInterface $locator)
60
    {
61
        $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...
62
    }
63
64 View Code Duplication
    public function getEventManager() {
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...
65
        if (null === $this->event) {
66
            $this->event = new EventManager($this->serviceLocator->get('SharedEventManager'), [get_class($this)]);
67
        }
68
69
        return $this->event;
70
    }
71
72 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...
73
    {
74
        $path = $this->getOptions()->getMediaPath() . DIRECTORY_SEPARATOR;
75
        $path .= 'game' . $game->getId() . DIRECTORY_SEPARATOR;
76
        if (!is_dir($path)) {
77
            mkdir($path, 0777, true);
78
        }
79
        $path .= 'user'. $user->getId() . DIRECTORY_SEPARATOR;
80
        if (!is_dir($path)) {
81
            mkdir($path, 0777, true);
82
        }
83
84
        return $path;
85
    }
86
87 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...
88
    {
89
        $media_url = $this->getOptions()->getMediaUrl() . '/';
90
        $media_url .= 'game' . $game->getId() . '/' . 'user'. $user->getId() . '/';
91
92
        return $media_url;
93
    }
94
95
    /**
96
     *
97
     * This service is ready for all types of games
98
     *
99
     * @param array $data
100
     * @param string $formClass
101
     * @return \PlaygroundGame\Entity\Game
102
     */
103
    public function createOrUpdate(array $data, $game, $formClass)
104
    {
105
        $entityManager = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
106
107
        $form = $this->serviceLocator->get($formClass);
108
        $form->get('publicationDate')->setOptions(array(
109
            'format' => 'Y-m-d H:i:s'
110
        ));
111
        $form->get('startDate')->setOptions(array(
112
            'format' => 'Y-m-d H:i:s'
113
        ));
114
        $form->get('endDate')->setOptions(array(
115
            'format' => 'Y-m-d H:i:s'
116
        ));
117
        $form->get('closeDate')->setOptions(array(
118
            'format' => 'Y-m-d H:i:s'
119
        ));
120
121
        $form->bind($game);
122
123
        $path = $this->getOptions()->getMediaPath() . '/';
124
        $media_url = $this->getOptions()->getMediaUrl() . '/';
125
126
        $identifierInput = $form->getInputFilter()->get('identifier');
127
        $noObjectExistsValidator = new NoObjectExistsValidator(array(
128
            'object_repository' => $entityManager->getRepository('PlaygroundGame\Entity\Game'),
129
            'fields' => 'identifier',
130
            'messages' => array(
131
                'objectFound' => 'This url already exists !'
132
            )
133
        ));
134
135
        if ($game->getIdentifier() != $data['identifier']) {
136
            $identifierInput->getValidatorChain()->addValidator($noObjectExistsValidator);
137
        }
138
139
        // I must switch from original format to the Y-m-d format because
140
        // this is the only one accepted by new DateTime($value)
141 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...
142
            $tmpDate = \DateTime::createFromFormat('d/m/Y H:i:s', $data['publicationDate']);
143
            $data['publicationDate'] = $tmpDate->format('Y-m-d H:i:s');
144
        }
145 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...
146
            $tmpDate = \DateTime::createFromFormat('d/m/Y H:i:s', $data['startDate']);
147
            $data['startDate'] = $tmpDate->format('Y-m-d H:i:s');
148
        }
149 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...
150
            $tmpDate = \DateTime::createFromFormat('d/m/Y H:i:s', $data['endDate']);
151
            $data['endDate'] = $tmpDate->format('Y-m-d H:i:s');
152
        }
153 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...
154
            $tmpDate = \DateTime::createFromFormat('d/m/Y H:i:s', $data['closeDate']);
155
            $data['closeDate'] = $tmpDate->format('Y-m-d H:i:s');
156
        }
157
158
        // If publicationDate is null, I update it with the startDate if not null neither
159
        if ((! isset($data['publicationDate']) || $data['publicationDate'] == '') &&
160
            (isset($data['startDate']) && $data['startDate'] != '')
161
        ) {
162
            $data['publicationDate'] = $data['startDate'];
163
        }
164
165
        // If the identifier has not been set, I use the title to create one.
166 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...
167
            $data['identifier'] = $data['title'];
168
        }
169
170
        $form->setData($data);
171
172
        // If someone want to claim... It's time to do it ! used for exemple by PlaygroundFacebook Module
173
        $result = $this->getEventManager()->trigger(__FUNCTION__ . '.validate', $this, array(
174
            'game' => $game,
175
            'data' => $data
176
        ));
177
        if (is_array($result) && ! $result[0]) {
178
            $form->get('fbAppId')->setMessages(array(
179
                'Vous devez d\'abord désinstaller l\'appli Facebook'
180
            ));
181
182
            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...
183
        }
184
185
        if (! $form->isValid()) {
186 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...
187
                $tmpDate = \DateTime::createFromFormat('Y-m-d H:i:s', $data['publicationDate']);
188
                $data['publicationDate'] = $tmpDate->format('d/m/Y H:i:s');
189
                $form->setData(array(
190
                    'publicationDate' => $data['publicationDate']
191
                ));
192
            }
193 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...
194
                $tmpDate = \DateTime::createFromFormat('Y-m-d H:i:s', $data['startDate']);
195
                $data['startDate'] = $tmpDate->format('d/m/Y H:i:s');
196
                $form->setData(array(
197
                    'startDate' => $data['startDate']
198
                ));
199
            }
200 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...
201
                $tmpDate = \DateTime::createFromFormat('Y-m-d H:i:s', $data['endDate']);
202
                $data['endDate'] = $tmpDate->format('d/m/Y H:i:s');
203
                $form->setData(array(
204
                    'endDate' => $data['endDate']
205
                ));
206
            }
207 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...
208
                $tmpDate = \DateTime::createFromFormat('Y-m-d H:i:s', $data['closeDate']);
209
                $data['closeDate'] = $tmpDate->format('d/m/Y H:i:s');
210
                $form->setData(array(
211
                    'closeDate' => $data['closeDate']
212
                ));
213
            }
214
            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...
215
        }
216
217
        $game = $form->getData();
218
        $game = $this->getGameMapper()->insert($game);
219
220
        // I wait for the game to be saved to obtain its ID.
221 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...
222
            ErrorHandler::start();
223
            $data['uploadMainImage']['name'] = $this->fileNewname(
224
                $path,
225
                $game->getId() . "-" . $data['uploadMainImage']['name']
226
            );
227
            move_uploaded_file($data['uploadMainImage']['tmp_name'], $path . $data['uploadMainImage']['name']);
228
            $game->setMainImage($media_url . $data['uploadMainImage']['name']);
229
            ErrorHandler::stop(true);
230
        }
231
232 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...
233
            $data['deleteMainImage'] &&
234
            empty($data['uploadMainImage']['tmp_name'])
235
        ) {
236
            ErrorHandler::start();
237
            $image = $game->getMainImage();
238
            $image = str_replace($media_url, '', $image);
239
            unlink($path . $image);
240
            $game->setMainImage(null);
241
            ErrorHandler::stop(true);
242
        }
243
244 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...
245
            ErrorHandler::start();
246
            $data['uploadSecondImage']['name'] = $this->fileNewname(
247
                $path,
248
                $game->getId() . "-" . $data['uploadSecondImage']['name']
249
            );
250
            move_uploaded_file($data['uploadSecondImage']['tmp_name'], $path . $data['uploadSecondImage']['name']);
251
            $game->setSecondImage($media_url . $data['uploadSecondImage']['name']);
252
            ErrorHandler::stop(true);
253
        }
254
255 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...
256
            $data['deleteSecondImage'] &&
257
            empty($data['uploadSecondImage']['tmp_name'])
258
        ) {
259
            ErrorHandler::start();
260
            $image = $game->getSecondImage();
261
            $image = str_replace($media_url, '', $image);
262
            unlink($path . $image);
263
            $game->setSecondImage(null);
264
            ErrorHandler::stop(true);
265
        }
266
267
        if (! empty($data['uploadStylesheet']['tmp_name'])) {
268
            ErrorHandler::start();
269
            move_uploaded_file($data['uploadStylesheet']['tmp_name'], $path . 'stylesheet_' . $game->getId() . '.css');
270
            $game->setStylesheet($media_url . 'stylesheet_' . $game->getId() . '.css');
271
            ErrorHandler::stop(true);
272
        }
273
274 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...
275
            ErrorHandler::start();
276
            $data['uploadFbShareImage']['name'] = $this->fileNewname(
277
                $path,
278
                $game->getId() . "-" . $data['uploadFbShareImage']['name']
279
            );
280
            move_uploaded_file($data['uploadFbShareImage']['tmp_name'], $path . $data['uploadFbShareImage']['name']);
281
            $game->setFbShareImage($media_url . $data['uploadFbShareImage']['name']);
282
            ErrorHandler::stop(true);
283
        }
284
285 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...
286
            $data['deleteFbShareImage'] &&
287
            empty($data['uploadFbShareImage']['tmp_name'])
288
        ) {
289
            ErrorHandler::start();
290
            $image = $game->getFbShareImage();
291
            $image = str_replace($media_url, '', $image);
292
            unlink($path . $image);
293
            $game->setFbShareImage(null);
294
            ErrorHandler::stop(true);
295
        }
296
297
        if (! empty($data['uploadFbPageTabImage']['tmp_name'])) {
298
            ErrorHandler::start();
299
            $extension = $this->getExtension(strtolower($data['uploadFbPageTabImage']['name']));
300
            $src = $this->getSrc($extension, $data['uploadFbPageTabImage']['tmp_name']);
301
            $this->resize(
302
                $data['uploadFbPageTabImage']['tmp_name'],
303
                $extension,
304
                $path . $game->getId() . "-" . $data['uploadFbPageTabImage']['name'],
305
                $src,
306
                111,
307
                74
308
            );
309
310
            $game->setFbPageTabImage($media_url . $game->getId() . "-" . $data['uploadFbPageTabImage']['name']);
311
            ErrorHandler::stop(true);
312
        }
313
314 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...
315
            $data['deleteFbPageTabImage'] &&
316
            empty($data['uploadFbPageTabImage']['tmp_name'])
317
        ) {
318
            ErrorHandler::start();
319
            $image = $game->getFbPageTabImage();
320
            $image = str_replace($media_url, '', $image);
321
            unlink($path . $image);
322
            $game->setFbPageTabImage(null);
323
            ErrorHandler::stop(true);
324
        }
325
326
        $game = $this->getGameMapper()->update($game);
327
328
        $prize_mapper = $this->serviceLocator->get('playgroundgame_prize_mapper');
329
        if (isset($data['prizes'])) {
330
            foreach ($data['prizes'] as $prize_data) {
331
                if (! empty($prize_data['picture_file']['tmp_name']) && ! $prize_data['picture_file']['error']) {
332
                    if ($prize_data['id']) {
333
                        $prize = $prize_mapper->findById($prize_data['id']);
334
                    } else {
335
                        $some_prizes = $prize_mapper->findBy(array(
336
                            'game' => $game,
337
                            'title' => $prize_data['title']
338
                        ));
339
                        if (count($some_prizes) == 1) {
340
                            $prize = $some_prizes[0];
341
                        } else {
342
                            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...
343
                        }
344
                    }
345
                    // Remove if existing image
346
                    if ($prize->getPicture() && file_exists($prize->getPicture())) {
347
                        unlink($prize->getPicture());
348
                        $prize->getPicture(null);
349
                    }
350
                    // Upload and set new
351
                    ErrorHandler::start();
352
                    $filename = "game-" . $game->getId() . "-prize-";
353
                    $filename .= $prize->getId() . "-" . $prize_data['picture_file']['name'];
354
                    move_uploaded_file($prize_data['picture_file']['tmp_name'], $path . $filename);
355
                    $prize->setPicture($media_url . $filename);
356
                    ErrorHandler::stop(true);
357
                    $prize_mapper->update($prize);
358
                }
359
            }
360
        }
361
        // If I receive false, it means that the FB Id was not available anymore
362
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
363
            'game' => $game
364
        ));
365
366
        return $game;
367
    }
368
    
369
    /**
370
     * getActiveGames
371
     *
372
     * @return Array of PlaygroundGame\Entity\Game
373
     */
374
    public function getActiveGames($displayHome = true, $classType = '', $order = '')
375
    {
376
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
377
        $today = new \DateTime("now");
378
        $today = $today->format('Y-m-d H:i:s');
379
        $orderBy = 'g.publicationDate';
380
        if ($order != '') {
381
            $orderBy = 'g.'.$order;
382
        }
383
384
        $qb = $em->createQueryBuilder();
385
        $and = $qb->expr()->andx();
386
        $and->add(
387
            $qb->expr()->orX(
388
                $qb->expr()->lte('g.publicationDate', ':date'),
389
                $qb->expr()->isNull('g.publicationDate')
390
            )
391
        );
392
        $and->add(
393
            $qb->expr()->orX(
394
                $qb->expr()->gte('g.closeDate', ':date'),
395
                $qb->expr()->isNull('g.closeDate')
396
            )
397
        );
398
        $qb->setParameter('date', $today);
399
        
400
        $and->add($qb->expr()->eq('g.active', '1'));
401
        $and->add($qb->expr()->eq('g.broadcastPlatform', '1'));
402
        
403
        if ($classType != '') {
404
            $and->add($qb->expr()->eq('g.classType', ':classType'));
405
            $qb->setParameter('classType', $classType);
406
        }
407
        
408
        if ($displayHome) {
409
            $and->add($qb->expr()->eq('g.displayHome', true));
410
        }
411
        
412
        $qb->select('g')
413
        ->from('PlaygroundGame\Entity\Game', 'g')
414
        ->where($and)
415
        ->orderBy($orderBy, 'DESC');
416
        
417
        $query = $qb->getQuery();
418
        $games = $query->getResult();
419
        
420
        // je les classe par date de publication (date comme clé dans le tableau afin de pouvoir merger les objets
421
        // de type article avec le même procédé en les classant naturellement par date asc ou desc
422
        $arrayGames = array();
423 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...
424
            if ($game->getPublicationDate()) {
425
                $key = $game->getPublicationDate()->format('Ymd');
426
            } elseif ($game->getStartDate()) {
427
                $key = $game->getStartDate()->format('Ymd');
428
            } else {
429
                $key = $game->getUpdatedAt()->format('Ymd');
430
            }
431
            $key .= $game->getUpdatedAt()->format('Ymd') . '-' . $game->getId();
432
            $arrayGames[$key] = $game;
433
        }
434
435
        return $arrayGames;
436
    }
437
438
    /**
439
     * getAvailableGames : Games OnLine and not already played by $user
440
     *
441
     * @return Array of PlaygroundGame\Entity\Game
442
     */
443
    public function getAvailableGames($user, $maxResults = 2)
444
    {
445
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
446
        $today = new \DateTime("now");
447
        $today = $today->format('Y-m-d H:i:s');
448
449
        // Game active with a start_date before today (or without start_date)
450
        // and end_date after today (or without end-date)
451
        $query = $em->createQuery('SELECT g FROM PlaygroundGame\Entity\Game g
452
                WHERE NOT EXISTS (SELECT l FROM PlaygroundGame\Entity\Entry l WHERE l.game = g AND l.user = :user)
453
                AND (g.startDate <= :date OR g.startDate IS NULL)
454
                AND (g.endDate >= :date OR g.endDate IS NULL)
455
                AND g.active = 1 AND g.broadcastPlatform = 1
456
                ORDER BY g.startDate ASC');
457
        $query->setParameter('date', $today);
458
        $query->setParameter('user', $user);
459
        $query->setMaxResults($maxResults);
460
        $games = $query->getResult();
461
462
        return $games;
463
    }
464
465 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...
466
    {
467
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
468
469
        $qb = $em->createQueryBuilder();
470
        $qb->select('
471
            e.id,
472
            u.username,
473
            u.title,
474
            u.firstname,
475
            u.lastname,
476
            u.email,
477
            u.optin,
478
            u.optinPartner,
479
            u.address,
480
            u.address2,
481
            u.postalCode,
482
            u.city,
483
            u.country,
484
            u.telephone,
485
            u.mobile,
486
            u.created_at,
487
            u.dob,
488
            e.winner,
489
            e.socialShares,
490
            e.playerData,
491
            e.updated_at
492
            ')
493
            ->from('PlaygroundGame\Entity\Entry', 'e')
494
            ->leftJoin('e.user', 'u')
495
            ->where($qb->expr()->eq('e.game', ':game'));
496
        
497
        $qb->setParameter('game', $game);
498
499
        return $qb->getQuery();
500
    }
501
502
    public function getEntriesHeader($game)
503
    {
504
        if ($game->getPlayerForm()) {
505
            $formPV = json_decode($game->getPlayerForm()->getForm(), true);
506
            $header = array('id'=> 1);
507 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...
508
                foreach ($element as $k => $v) {
509
                    if ($k !== 'form_properties') {
510
                        $header[$v[0]['name']] = 1;
511
                    }
512
                }
513
            }
514
        } else {
515
            $header = array(
516
                'id' => 1,
517
                'username' => 1,
518
                'title' => 1,
519
                'firstname' => 1,
520
                'lastname' => 1,
521
                'email' => 1,
522
                'optin' => 1,
523
                'optinPartner' => 1,
524
                'address' => 1,
525
                'address2' => 1,
526
                'postalCode' => 1,
527
                'city' => 1,
528
                'country' => 1,
529
                'telephone' => 1,
530
                'mobile' => 1,
531
                'created_at' => 1,
532
                'dob' => 1,
533
                'winner' => 1
534
            );
535
        }
536
        $header['winner'] = 1;
537
        $header['socialShares'] = 1;
538
        $header['updated_at'] = 1;
539
540
        return $header;
541
    }
542
543
    /**
544
    * getGameEntries : I create an array of entries based on playerData + header
545
    *
546
    * @return Array of PlaygroundGame\Entity\Game
547
    */
548
    public function getGameEntries($header, $entries, $game)
549
    {
550
        $header = $this->getEntriesHeader($game);
551
552
        $results = array();
553
554
        foreach ($entries as $k => $entry) {
555
            $entryData = json_decode($entry['playerData'], true);
556 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...
557
                if (isset($entryData[$key])) {
558
                    $results[$k][$key] = (is_array($entryData[$key]))?implode(', ', $entryData[$key]):$entryData[$key];
559
                } elseif (array_key_exists($key, $entry)) {
560
                    $results[$k][$key] = ($entry[$key] instanceof \DateTime)?
561
                        $entry[$key]->format('Y-m-d H:i:s'):
562
                        $entry[$key];
563
                } else {
564
                    $results[$k][$key] = '';
565
                }
566
            }
567
        }
568
569
        return $results;
570
    }
571
572
    /**
573
     * getActiveSliderGames
574
     *
575
     * @return Array of PlaygroundGame\Entity\Game
576
     */
577
    public function getActiveSliderGames()
578
    {
579
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
580
        $today = new \DateTime("now");
581
        $today = $today->format('Y-m-d H:i:s');
582
583
        // Game active with a start_date before today (or without start_date)
584
        // and end_date after today (or without end-date)
585
        $query = $em->createQuery('SELECT g FROM PlaygroundGame\Entity\Game g
586
            WHERE (g.publicationDate <= :date OR g.publicationDate IS NULL)
587
            AND (g.closeDate >= :date OR g.closeDate IS NULL)
588
            AND g.active = true AND g.broadcastPlatform = 1 AND g.pushHome = true');
589
        $query->setParameter('date', $today);
590
        $games = $query->getResult();
591
592
        // je les classe par date de publication (date comme clé dans le tableau afin de pouvoir merger les objets
593
        // de type article avec le même procédé en les classant naturellement par date asc ou desc
594
        $arrayGames = array();
595 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...
596
            if ($game->getPublicationDate()) {
597
                $key = $game->getPublicationDate()->format('Ymd');
598
            } elseif ($game->getStartDate()) {
599
                $key = $game->getStartDate()->format('Ymd');
600
            } else {
601
                $key = $game->getUpdatedAt()->format('Ymd');
602
            }
603
            $key .= $game->getUpdatedAt()->format('Ymd') . '-' . $game->getId();
604
            $arrayGames[$key] = $game;
605
        }
606
607
        return $arrayGames;
608
    }
609
610
    /**
611
     * getPrizeCategoryGames
612
     *
613
     * @return Array of PlaygroundGame\Entity\Game
614
     */
615 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...
616
    {
617
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
618
619
        $query = $em->createQuery('SELECT g FROM PlaygroundGame\Entity\Game g
620
            WHERE (g.prizeCategory = :categoryid AND g.broadcastPlatform = 1)
621
            ORDER BY g.publicationDate DESC');
622
        $query->setParameter('categoryid', $categoryid);
623
        $games = $query->getResult();
624
625
        return $games;
626
    }
627
628
    public function checkGame($identifier, $checkIfStarted = true)
629
    {
630
        $gameMapper = $this->getGameMapper();
631
632
        if (! $identifier) {
633
            return false;
634
        }
635
636
        $game = $gameMapper->findByIdentifier($identifier);
637
638
        // the game has not been found
639
        if (! $game) {
640
            return false;
641
        }
642
643
        // for preview stuff as admin
644
        if ($this->isAllowed('game', 'edit')) {
645
            $r =$this->serviceLocator->get('request');
646
            if ($r->getQuery()->get('preview')) {
647
                $game->setActive(true);
648
                $game->setStartDate(null);
649
                $game->setEndDate(null);
650
                $game->setPublicationDate(null);
651
                $game->setBroadcastPlatform(true);
652
653
                // I don't want the game to be updated through any update during the preview mode.
654
                // I mark it as readonly for Doctrine
655
                $this->serviceLocator
656
                    ->get('doctrine.entitymanager.orm_default')
657
                    ->getUnitOfWork()
658
                    ->markReadOnly($game);
659
                    
660
                return $game;
661
            }
662
        }
663
664
        // The game is inactive
665
        if (! $game->getActive()) {
666
            return false;
667
        }
668
669
        // the game has not begun yet
670
        if (! $game->isOpen()) {
671
            return false;
672
        }
673
674
        // the game is finished and closed
675
        if (! $game->isStarted() && $checkIfStarted) {
676
            return false;
677
        }
678
679
        return $game;
680
    }
681
682
    /**
683
     * Return the last entry of the user on this game, if it exists.
684
     * An entry can be associated to :
685
     * - A user account (a real one, linked to PlaygroundUser
686
     * - An anonymous Identifier (based on one value of playerData (generally email))
687
     * - A cookie set on the player device (the less secure)
688
     * If the active param is set, it can check if the entry is active or not.
689
     * If the bonus param is set, it can check if the entry is a bonus or not.
690
     *
691
     * @param unknown $game
692
     * @param string $user
693
     * @param boolean $active
694
     * @param boolean $bonus
695
     * @return boolean
696
     */
697
    public function checkExistingEntry($game, $user = null, $active = null, $bonus = null)
698
    {
699
        $search = array('game'  => $game);
700
701
        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...
702
            $search['user'] = $user;
703
        } elseif ($this->getAnonymousIdentifier()) {
704
            $search['anonymousIdentifier'] = $this->getAnonymousIdentifier();
705
            $search['user'] = null;
706
        } else {
707
            $search['anonymousId'] = $this->getAnonymousId();
708
            $search['user'] = null;
709
        }
710
        
711
        if (! is_null($active)) {
712
            $search['active'] = $active;
713
        }
714
        if (! is_null($bonus)) {
715
            $search['bonus'] = $bonus;
716
        }
717
718
        $entry = $this->getEntryMapper()->findOneBy($search, array('updated_at' => 'desc'));
719
720
        return $entry;
721
    }
722
723
    /*
724
    * This function updates the entry with the player data after checking
725
    * that the data are compliant with the formUser Game attribute
726
    *
727
    * The $data has to be a json object
728
    */
729
    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...
730
    {
731
        $form = $this->createFormFromJson($game->getPlayerForm()->getForm(), 'playerForm');
732
        $form->setData($data);
733
734
        if (!$mandatory) {
735
            $filter = $form->getInputFilter();
736
            foreach ($form->getElements() as $element) {
737
                try {
738
                    $elementInput = $filter->get($element->getName());
739
                    $elementInput->setRequired(false);
740
                    $form->get($element->getName())->setAttribute('required', false);
741
                } 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...
742
                }
743
            }
744
        }
745
746
        if ($form->isValid()) {
747
            $dataJson = json_encode($form->getData());
748
749
            if ($game->getAnonymousAllowed() &&
750
                $game->getAnonymousIdentifier() &&
751
                isset($data[$game->getAnonymousIdentifier()])
752
            ) {
753
                $session = new \Zend\Session\Container('anonymous_identifier');
754
                if (empty($session->offsetGet('anonymous_identifier'))) {
755
                    $anonymousIdentifier = $data[$game->getAnonymousIdentifier()];
756
                
757
                    $entry->setAnonymousIdentifier($anonymousIdentifier);
758
                
759
                    // I must transmit this info during the whole game workflow
760
                    $session->offsetSet('anonymous_identifier', $anonymousIdentifier);
761
                }
762
            }
763
764
            $entry->setPlayerData($dataJson);
765
            $this->getEntryMapper()->update($entry);
766
        } else {
767
            return false;
768
        }
769
770
        return true;
771
    }
772
773
774
    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...
775
    {
776
        // If on Facebook, check if you have to be a FB fan to play the game
777
        $session = new Container('facebook');
778
779
        if ($session->offsetExists('signed_request')) {
780
            // I'm on Facebook
781
            $sr = $session->offsetGet('signed_request');
782
            if ($sr['page']['liked'] == 1) {
783
                return true;
784
            }
785
        } else {
786
            // I'm not on Facebook
787
            return true;
788
        }
789
790
        return false;
791
    }
792
    
793
    public function getAnonymousIdentifier()
794
    {
795
        if (is_null($this->anonymousIdentifier)) {
796
            // If on Facebook, check if you have to be a FB fan to play the game
797
            $session = new Container('anonymous_identifier');
798
            
799
            if ($session->offsetExists('anonymous_identifier')) {
800
                $this->anonymousIdentifier = $session->offsetGet('anonymous_identifier');
801
            } else {
802
                $this->anonymousIdentifier = false;
803
            }
804
        }
805
    
806
        return $this->anonymousIdentifier;
807
    }
808
809
    /**
810
     * errors :
811
     * -1 : user not connected
812
     * -2 : limit entry games for this user reached
813
     *
814
     * @param \PlaygroundGame\Entity\Game $game
815
     * @param \PlaygroundUser\Entity\UserInterface $user
816
     * @return number unknown
817
     */
818
    public function play($game, $user)
819
    {
820
821
        // certaines participations peuvent rester ouvertes.
822
        // On autorise alors le joueur à reprendre là ou il en était
823
        // par exemple les postvote...
824
        $entry = $this->checkExistingEntry($game, $user, true);
0 ignored issues
show
Documentation introduced by
$game is of type object<PlaygroundGame\Entity\Game>, but the function expects a object<PlaygroundGame\Service\unknown>.

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...
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...
825
826
        if (! $entry) {
827
            if ($this->hasReachedPlayLimit($game, $user)) {
828
                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...
829
            }
830
831
            $entry = new Entry();
832
            $entry->setGame($game);
0 ignored issues
show
Documentation introduced by
$game is of type object<PlaygroundGame\Entity\Game>, but the function expects a object<PlaygroundGame\Entity\field_type>.

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...
833
            $entry->setUser($user);
0 ignored issues
show
Documentation introduced by
$user is of type object<PlaygroundUser\Entity\UserInterface>, but the function expects a object<PlaygroundGame\Entity\field_type>.

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...
834
            $entry->setPoints(0);
835
            $entry->setIp($this->getIp());
836
            $entry->setAnonymousId($this->getAnonymousId());
837
            if ($this->getAnonymousIdentifier()) {
838
                $entry->setAnonymousIdentifier($this->getAnonymousIdentifier());
839
            }
840
841
            $entry = $this->getEntryMapper()->insert($entry);
842
            $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
843
                'user' => $user,
844
                'game' => $game,
845
                'entry' => $entry
846
            ));
847
        }
848
849
        return $entry;
850
    }
851
852
    /**
853
     * @param \PlaygroundGame\Entity\Game $game
854
     * @param \PlaygroundUser\Entity\UserInterface $user
855
     */
856
    public function hasReachedPlayLimit($game, $user)
857
    {
858
        // Is there a limitation on the game ?
859
        $limitAmount = $game->getPlayLimit();
860
        if ($limitAmount) {
861
            $limitScale = $game->getPlayLimitScale();
862
            $userEntries = $this->findLastEntries($game, $user, $limitScale);
863
864
            // player has reached the game limit
865
            if ($userEntries >= $limitAmount) {
866
                return true;
867
            }
868
        }
869
        return false;
870
    }
871
    
872
    /**
873
     * @param \PlaygroundGame\Entity\Game $game
874
     * @param \PlaygroundUser\Entity\UserInterface $user
875
     */
876
    public function findLastEntries($game, $user, $limitScale)
877
    {
878
        $limitDate = $this->getLimitDate($limitScale);
879
880
        if ($user) {
881
            return $this->getEntryMapper()->findLastEntriesByUser($game, $user, $limitDate);
882
        } elseif ($this->getAnonymousIdentifier()) {
883
            return $this->getEntryMapper()->findLastEntriesByAnonymousIdentifier(
884
                $game,
885
                $this->getAnonymousIdentifier(),
886
                $limitDate
887
            );
888
        } else {
889
            return $this->getEntryMapper()->findLastEntriesByIp($game, $this->getIp(), $limitDate);
890
        }
891
    }
892
893
    /**
894
    *
895
    *
896
    */
897
    public function getLimitDate($limitScale)
898
    {
899
        $now = new \DateTime("now");
900
        switch ($limitScale) {
901
            case 'always':
902
                $interval = 'P100Y';
903
                $now->sub(new \DateInterval($interval));
904
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
905
                break;
906
            case 'day':
907
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
908
                break;
909 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...
910
                $interval = 'P7D';
911
                $now->sub(new \DateInterval($interval));
912
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
913
                break;
914 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...
915
                $interval = 'P1M';
916
                $now->sub(new \DateInterval($interval));
917
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
918
                break;
919 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...
920
                $interval = 'P1Y';
921
                $now->sub(new \DateInterval($interval));
922
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
923
                break;
924 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...
925
                $interval = 'P100Y';
926
                $now->sub(new \DateInterval($interval));
927
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
928
        }
929
930
        return $dateLimit;
931
    }
932
933
    public function findLastActiveEntry($game, $user)
934
    {
935
        return $this->checkExistingEntry($game, $user, true);
936
    }
937
938
    public function findLastInactiveEntry($game, $user)
939
    {
940
        return $this->checkExistingEntry($game, $user, false, false);
941
    }
942
943
    public function findLastEntry($game, $user)
944
    {
945
        return $this->checkExistingEntry($game, $user, null, false);
946
    }
947
948
    public function inviteToTeam($data, $game, $user)
949
    {
950
        $mailService = $this->serviceLocator->get('playgroundgame_message');
951
        $invitationMapper = $this->serviceLocator->get('playgroundgame_invitation_mapper');
952
953
        $sentInvitations = $invitationMapper->findBy(array('host' => $user, 'game' => $game));
954
        $nbInvitations = count($sentInvitations);
955
        $to = $data['email'];
956
        if (empty($to)) {
957
            return ['result'=>false, 'message'=>'no email'];
958
        }
959
960
        if ($nbInvitations < 20) {
961
            $alreadyInvited = $invitationMapper->findBy(array('requestKey' => $to, 'game' => $game));
962
            if (!$alreadyInvited) {
963
                $alreadyInvited = $this->getUserMapper()->findByEmail($to);
964
            }
965
966
            if (empty($alreadyInvited)) {
967
                $invitation = new \PlaygroundGame\Entity\Invitation();
968
                $invitation->setRequestKey($to);
969
                $invitation->setGame($game);
970
                $invitation->setHost($user);
971
                $invitationMapper->insert($invitation);
972
973
                $from = $this->getOptions()->getEmailFromAddress();
974
                $subject = $this->serviceLocator->get('MvcTranslator')->translate(
975
                    $this->getOptions()->getInviteToTeamSubjectLine(),
976
                    'playgroundgame'
977
                );
978
                $message = $mailService->createHtmlMessage(
979
                    $from,
980
                    $to,
981
                    $subject,
982
                    'playground-game/email/invite_team',
983
                    array(
984
                        'game' => $game,
985
                        'user' => $user,
986
                        'data' => $data,
987
                        'from' => $from
988
                    )
989
                );
990
                try {
991
                    $mailService->send($message);
992
                } catch (\Zend\Mail\Protocol\Exception\RuntimeException $e) {
0 ignored issues
show
Bug introduced by
The class Zend\Mail\Protocol\Exception\RuntimeException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
993
                    return ['result' => true, 'message' => $this->serviceLocator->get('MvcTranslator')->translate(
994
                        'mail error'
995
                    )];
996
                }
997
998
                return ['result' => true, 'message' => ''];
999
            } else {
1000
                return ['result' => false, 'message' => 'already invited'];
1001
            }
1002
        } else {
1003
            return [
1004
                'result' => false,
1005
                'message' => $this->serviceLocator->get('MvcTranslator')->translate(
1006
                    'Too many invitations for this user'
1007
                )
1008
            ];
1009
        }
1010
    }
1011
1012
    public function sendShareMail(
1013
        $data,
1014
        $game,
1015
        $user,
1016
        $entry,
1017
        $template = 'share_game',
1018
        $topic = null,
1019
        $userTimer = array(),
1020
        $subject = ''
1021
    ) {
1022
        $mailService = $this->serviceLocator->get('playgroundgame_message');
1023
        $mailSent = false;
1024
        $from = $this->getOptions()->getEmailFromAddress();
1025
1026
        if (empty($subject)) {
1027
            $subject = $this->serviceLocator->get('MvcTranslator')->translate(
1028
                $this->getOptions()->getShareSubjectLine(),
1029
                'playgroundgame'
1030
            );
1031
        } else {
1032
            $subject = $this->serviceLocator->get('MvcTranslator')->translate(
1033
                $subject,
1034
                'playgroundgame'
1035
            );
1036
        }
1037
1038
        $renderer = $this->serviceLocator->get('Zend\View\Renderer\RendererInterface');
1039
        $skinUrl = $renderer->url(
1040
            'frontend',
1041
            array(),
1042
            array('force_canonical' => true)
1043
        );
1044
        $secretKey = strtoupper(substr(sha1(uniqid('pg_', true) . '####' . time()), 0, 15));
1045
1046
        if (! $topic) {
1047
            $topic = $game->getTitle();
1048
        }
1049
1050
        if (isset($data['email']) && !is_array($data['email'])) {
1051
            $data['email'] = array($data['email']);
1052
        }
1053
        
1054
        foreach ($data['email'] as $to) {
1055
            $mailSent = true;
1056
            if (!empty($to)) {
1057
                $message = $mailService->createHtmlMessage(
1058
                    $from,
1059
                    $to,
1060
                    $subject,
1061
                    'playground-game/email/' . $template,
1062
                    array(
1063
                        'game' => $game,
1064
                        'data' => $data,
1065
                        'from' => $from,
1066
                        'to' => $to,
1067
                        'secretKey' => $secretKey,
1068
                        'skinUrl' => $skinUrl,
1069
                        'userTimer' => $userTimer
1070
                    )
1071
                );
1072
                try {
1073
                    $mailService->send($message);
1074
                } 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...
Bug introduced by
The class Zend\Mail\Protocol\Exception\RuntimeException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
1075
                }
1076
                
1077
                if ($entry) {
1078
                    $shares = json_decode($entry->getSocialShares(), true);
1079
                    (!isset($shares['mail']))? $shares['mail'] = 1:$shares['mail'] += 1;
1080
                }
1081
            }
1082
        }
1083
1084
        if ($mailSent) {
1085
            if ($entry) {
1086
                $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...
1087
                $entry->setSocialShares($sharesJson);
1088
                $entry = $this->getEntryMapper()->update($entry);
1089
            }
1090
            
1091
            $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1092
                'user' => $user,
1093
                'topic' => $topic,
1094
                'secretKey' => $secretKey,
1095
                'data' => $data,
1096
                'game' => $game,
1097
                'entry' => $entry
1098
            ));
1099
1100
            return true;
1101
        }
1102
1103
        return false;
1104
    }
1105
1106
    /**
1107
     * @param \PlaygroundGame\Entity\Game $game
1108
     * @param \PlaygroundUser\Entity\User $user
1109
     * @param Entry $entry
1110
     * @param \PlaygroundGame\Entity\Prize $prize
1111
     */
1112
    public function sendResultMail($game, $user, $entry, $template = 'entry', $prize = null)
1113
    {
1114
        $mailService = $this->serviceLocator->get('playgroundgame_message');
1115
        $from = $this->getOptions()->getEmailFromAddress();
1116
        if ($user) {
1117
            $to = $user->getEmail();
1118
        } elseif ($entry->getAnonymousIdentifier()) {
1119
            $to = $entry->getAnonymousIdentifier();
1120
        } else {
1121
            return false;
1122
        }
1123
        $subject = $game->getTitle();
1124
        $renderer = $this->serviceLocator->get('Zend\View\Renderer\RendererInterface');
1125
        $skinUrl = $renderer->url(
1126
            'frontend',
1127
            array(),
1128
            array('force_canonical' => true)
1129
        );
1130
        $message = $mailService->createHtmlMessage($from, $to, $subject, 'playground-game/email/' . $template, array(
1131
            'game' => $game,
1132
            'entry' => $entry,
1133
            'skinUrl' => $skinUrl,
1134
            'prize' => $prize
1135
        ));
1136
        $mailService->send($message);
1137
    }
1138
1139
    public function sendGameMail($game, $user, $post, $template = 'postvote')
1140
    {
1141
        $mailService = $this->serviceLocator->get('playgroundgame_message');
1142
        $from = $this->getOptions()->getEmailFromAddress();
1143
        $to = $user->getEmail();
1144
        $subject = $this->serviceLocator->get('MvcTranslator')->translate(
1145
            $this->getOptions()->getParticipationSubjectLine(),
1146
            'playgroundgame'
1147
        );
1148
        $renderer = $this->serviceLocator->get('Zend\View\Renderer\RendererInterface');
1149
        $skinUrl = $renderer->url(
1150
            'frontend',
1151
            array(),
1152
            array('force_canonical' => true)
1153
        );
1154
1155
        $message = $mailService->createHtmlMessage($from, $to, $subject, 'playground-game/email/' . $template, array(
1156
            'game' => $game,
1157
            'post' => $post,
1158
            'skinUrl' => $skinUrl
1159
        ));
1160
        $mailService->send($message);
1161
    }
1162
1163 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...
1164
    {
1165
        $topic = $game->getTitle();
1166
        
1167
        $shares = json_decode($entry->getSocialShares(), true);
1168
        if (!isset($shares['fbwall'])) {
1169
            $shares['fbwall'] = 1;
1170
        } else {
1171
            $shares['fbwall'] += 1;
1172
        }
1173
        $sharesJson = json_encode($shares);
1174
        $entry->setSocialShares($sharesJson);
1175
        $entry = $this->getEntryMapper()->update($entry);
1176
        
1177
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1178
            'user' => $user,
1179
            'game' => $game,
1180
            'secretKey' => $secretKey,
1181
            'topic' => $topic,
1182
            'entry' => $entry
1183
        ));
1184
1185
        return true;
1186
    }
1187
1188
    public function postFbRequest($secretKey, $game, $user, $entry, $to)
1189
    {
1190
        $shares = json_decode($entry->getSocialShares(), true);
1191
        $to = explode(',', $to);
1192
        if (!isset($shares['fbrequest'])) {
1193
            $shares['fbrequest'] = count($to);
1194
        } else {
1195
            $shares['fbrequest'] += count($to);
1196
        }
1197
        $sharesJson = json_encode($shares);
1198
        $entry->setSocialShares($sharesJson);
1199
        $entry = $this->getEntryMapper()->update($entry);
1200
        
1201
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1202
            'user' => $user,
1203
            'game' => $game,
1204
            'secretKey' => $secretKey,
1205
            'entry' => $entry,
1206
            'invites' => count($to)
1207
        ));
1208
1209
        return true;
1210
    }
1211
1212 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...
1213
    {
1214
        $topic = $game->getTitle();
1215
1216
        $shares = json_decode($entry->getSocialShares(), true);
1217
        if (!isset($shares['fbrequest'])) {
1218
            $shares['tweet'] = 1;
1219
        } else {
1220
            $shares['tweet'] += 1;
1221
        }
1222
        $sharesJson = json_encode($shares);
1223
        $entry->setSocialShares($sharesJson);
1224
        $entry = $this->getEntryMapper()->update($entry);
1225
        
1226
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1227
            'user' => $user,
1228
            'game' => $game,
1229
            'secretKey' => $secretKey,
1230
            'topic' => $topic,
1231
            'entry' => $entry
1232
        ));
1233
1234
        return true;
1235
    }
1236
1237 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...
1238
    {
1239
        $topic = $game->getTitle();
1240
        
1241
        $shares = json_decode($entry->getSocialShares(), true);
1242
        if (!isset($shares['fbrequest'])) {
1243
            $shares['google'] = 1;
1244
        } else {
1245
            $shares['google'] += 1;
1246
        }
1247
        $sharesJson = json_encode($shares);
1248
        $entry->setSocialShares($sharesJson);
1249
        $entry = $this->getEntryMapper()->update($entry);
1250
1251
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1252
            'user' => $user,
1253
            'game' => $game,
1254
            'secretKey' => $secretKey,
1255
            'topic' => $topic,
1256
            'entry' => $entry
1257
        ));
1258
1259
        return true;
1260
    }
1261
1262
    /**
1263
     * Is it possible to trigger a bonus entry ?
1264
     *
1265
     * @param unknown_type $game
1266
     * @param unknown_type $user
1267
     */
1268
    public function allowBonus($game, $user)
1269
    {
1270
        if (! $game->getPlayBonus() || $game->getPlayBonus() == 'none') {
1271
            return false;
1272
        } elseif ($game->getPlayBonus() == 'one') {
1273
            if ($this->getEntryMapper()->findOneBy(array(
1274
                'game' => $game,
1275
                'user' => $user,
1276
                'bonus' => 1
1277
            ))) {
1278
                return false;
1279
            } else {
1280
                return true;
1281
            }
1282
        } elseif ($game->getPlayBonus() == 'per_entry') {
1283
            return $this->getEntryMapper()->checkBonusEntry($game, $user);
1284
        }
1285
1286
        return false;
1287
    }
1288
1289
    public function addAnotherEntry($game, $user, $winner = 0)
1290
    {
1291
        $entry = new Entry();
1292
        $entry->setGame($game);
1293
        $entry->setUser($user);
1294
        $entry->setPoints(0);
1295
        $entry->setIp($this->getIp());
1296
        $entry->setActive(0);
1297
        $entry->setBonus(1);
1298
        $entry->setWinner($winner);
1299
        $entry = $this->getEntryMapper()->insert($entry);
1300
1301
        return $entry;
1302
    }
1303
1304
    /**
1305
     * This bonus entry doesn't give points nor badges
1306
     * It's just there to increase the chances during the Draw
1307
     * Old Name playBonus
1308
     *
1309
     * @param PlaygroundGame\Entity\Game $game
1310
     * @param unknown $user
1311
     * @return boolean unknown
1312
     */
1313
    public function addAnotherChance($game, $user, $winner = 0)
1314
    {
1315
        if ($this->allowBonus($game, $user)) {
1316
            $this->addAnotherEntry($game, $user, $winner);
1317
1318
            return true;
1319
        }
1320
1321
        return false;
1322
    }
1323
1324
    /**
1325
     * This bonus entry doesn't give points nor badges but can play again
1326
     *
1327
     * @param PlaygroundGame\Entity\Game $game
1328
     * @param user $user
1329
     * @return boolean unknown
1330
     */
1331
    public function playAgain($game, $user, $winner = 0)
1332
    {
1333
        if ($this->allowBonus($game, $user)) {
1334
            $entry = $this->addAnotherEntry($game, $user, $winner);
1335
            $entry->setActive(1);
1336
            $entry = $this->getEntryMapper()->update($entry);
1337
            if ($entry->getActive() == 1) {
1338
                return true;
1339
            }
1340
        }
1341
1342
        return false;
1343
    }
1344
1345
    /**
1346
     * @param string $path
1347
     * @param boolean $noReplace : If the image name already exist, don't replace it but change the name
1348
     */
1349
    public function uploadFile($path, $file, $noReplace = true)
1350
    {
1351
        $err = $file["error"];
1352
        $message = '';
1353
        if ($err > 0) {
1354
            switch ($err) {
1355
                case '1':
1356
                    $message .= 'Max file size exceeded. (php.ini)';
1357
                    break;
1358
                case '2':
1359
                    $message .= 'Max file size exceeded.';
1360
                    break;
1361
                case '3':
1362
                    $message .= 'File upload was only partial.';
1363
                    break;
1364
                case '4':
1365
                    $message .= 'No file was attached.';
1366
                    break;
1367
                case '7':
1368
                    $message .= 'File permission denied.';
1369
                    break;
1370
                default:
1371
                    $message .= 'Unexpected error occurs.';
1372
            }
1373
1374
            return $err;
1375
        } else {
1376
            $fileNewname = $this->fileNewname($path, $file['name'], $noReplace);
1377
1378
            if (isset($file["base64"])) {
1379
                list(, $img) = explode(',', $file["base64"]);
1380
                $img = str_replace(' ', '+', $img);
1381
                $im = base64_decode($img);
1382
                if ($im !== false) {
1383
                    // getimagesizefromstring
1384
                    file_put_contents($path . $fileNewname, $im);
1385
                } else {
1386
                    return 1;
1387
                }
1388
1389
                return $fileNewname;
1390
            } else {
1391
                $adapter = new \Zend\File\Transfer\Adapter\Http();
1392
                // 1Mo
1393
                $size = new Size(array(
1394
                    'max' => 1024000
1395
                ));
1396
                $is_image = new IsImage('jpeg,png,gif,jpg');
1397
                $adapter->setValidators(array(
1398
                    $size,
1399
                    $is_image
1400
                ), $fileNewname);
1401
1402
                if (! $adapter->isValid()) {
1403
                    return false;
1404
                }
1405
1406
                @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...
1407
            }
1408
1409
            
1410
            if (class_exists("Imagick")) {
1411
                $ext = pathinfo($fileNewname, PATHINFO_EXTENSION);
1412
                $img = new \Imagick($path . $fileNewname);
1413
                $img->cropThumbnailImage(100, 100);
1414
                $img->setImageCompression(\Imagick::COMPRESSION_JPEG);
1415
                $img->setImageCompressionQuality(75);
1416
                // Strip out unneeded meta data
1417
                $img->stripImage();
1418
                $img->writeImage($path . str_replace('.'.$ext, '-thumbnail.'.$ext, $fileNewname));
1419
                ErrorHandler::stop(true);
1420
            }
1421
        }
1422
1423
        return $fileNewname;
1424
    }
1425
1426
    /**
1427
     * @param string $path
1428
     */
1429
    public function fileNewname($path, $filename, $generate = false)
1430
    {
1431
        $sanitize = new Sanitize();
1432
        $name = $sanitize->filter($filename);
1433
        $newpath = $path . $name;
1434
1435
        if ($generate) {
1436
            if (file_exists($newpath)) {
1437
                $filename = pathinfo($name, PATHINFO_FILENAME);
1438
                $ext = pathinfo($name, PATHINFO_EXTENSION);
1439
1440
                $name = $filename . '_' . rand(0, 99) . '.' . $ext;
1441
            }
1442
        }
1443
1444
        unset($sanitize);
1445
1446
        return $name;
1447
    }
1448
1449
    /**
1450
     * This function returns the list of games, order by $type
1451
     */
1452
    public function getQueryGamesOrderBy($type = 'createdAt', $order = 'DESC')
1453
    {
1454
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
1455
        $today = new \DateTime("now");
1456
        $today = $today->format('Y-m-d H:i:s');
1457
1458
        $onlineGames = '(
1459
            (
1460
                CASE WHEN (
1461
                    g.active = 1
1462
                    AND g.broadcastPlatform = 1
1463
                    AND (g.startDate <= :date OR g.startDate IS NULL)
1464
                    AND (g.closeDate >= :date OR g.closeDate IS NULL)
1465
                ) THEN 1 ELSE 0 END
1466
            ) +
1467
            (
1468
                CASE WHEN (
1469
                    g.active = 0
1470
                    AND (g.broadcastPlatform = 0 OR g.broadcastPlatform IS NULL)
1471
                    AND g.startDate > :date
1472
                    AND g.closeDate < :date
1473
                ) THEN 1 ELSE 0 END
1474
            )
1475
        )';
1476
1477
        $qb = $em->createQueryBuilder();
1478
        $qb->select('g')->from('PlaygroundGame\Entity\Game', 'g');
1479
        
1480
        switch ($type) {
1481
            case 'startDate':
1482
                $qb->orderBy('g.startDate', $order);
1483
                break;
1484
            case 'activeGames':
1485
                $qb->orderBy('g.active', $order);
1486
                break;
1487
            case 'onlineGames':
1488
                $qb->orderBy($onlineGames, $order);
1489
                $qb->setParameter('date', $today);
1490
                break;
1491
            case 'createdAt':
1492
                $qb->orderBy('g.createdAt', $order);
1493
                break;
1494
        }
1495
1496
        $query = $qb->getQuery();
1497
1498
        return $query;
1499
    }
1500
1501
    public function draw($game)
1502
    {
1503
        $total = $game->getWinners();
1504
1505
        // I Have to know what is the User Class used
1506
        $zfcUserOptions = $this->serviceLocator->get('zfcuser_module_options');
1507
        $userClass = $zfcUserOptions->getUserEntityClass();
1508
1509
        $result = $this->getEntryMapper()->draw($game, $userClass, $total);
1510
1511
        foreach ($result as $e) {
1512
            $e->setWinner(1);
1513
            $e = $this->getEntryMapper()->update($e);
1514
            $this->getEventManager()->trigger('win_lottery.post', $this, array(
1515
                'user' => $e->getUser(),
1516
                'game' => $game,
1517
                'entry' => $e
1518
            ));
1519
        }
1520
1521
        return $result;
1522
    }
1523
1524
    /**
1525
     * getGameMapper
1526
     *
1527
     * @return GameMapperInterface
1528
     */
1529 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...
1530
    {
1531
        if (null === $this->gameMapper) {
1532
            $this->gameMapper = $this->serviceLocator->get('playgroundgame_game_mapper');
1533
        }
1534
1535
        return $this->gameMapper;
1536
    }
1537
1538
    /**
1539
     * setGameMapper
1540
     *
1541
     * @param GameMapperInterface $gameMapper
1542
     * @return Game
1543
     */
1544
    public function setGameMapper(GameMapperInterface $gameMapper)
1545
    {
1546
        $this->gameMapper = $gameMapper;
1547
1548
        return $this;
1549
    }
1550
1551
    /**
1552
     * getEntryMapper
1553
     *
1554
     * @return EntryMapperInterface
1555
     */
1556
    public function getEntryMapper()
1557
    {
1558
        if (null === $this->entryMapper) {
1559
            $this->entryMapper = $this->serviceLocator->get('playgroundgame_entry_mapper');
1560
        }
1561
1562
        return $this->entryMapper;
1563
    }
1564
1565
    /**
1566
     * setEntryMapper
1567
     *
1568
     * @param EntryMapperInterface $entryMapper
1569
     * @return Game
1570
     */
1571
    public function setEntryMapper($entryMapper)
1572
    {
1573
        $this->entryMapper = $entryMapper;
1574
1575
        return $this;
1576
    }
1577
1578
    public function setOptions(ModuleOptions $options)
1579
    {
1580
        $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...
1581
1582
        return $this;
1583
    }
1584
1585
    public function getOptions()
1586
    {
1587
        if (! $this->options instanceof ModuleOptions) {
1588
            $this->setOptions($this->serviceLocator
1589
                ->get('playgroundgame_module_options'));
1590
        }
1591
1592
        return $this->options;
1593
    }
1594
1595
    /**
1596
     * @param string $str
1597
     */
1598
    public function getExtension($str)
1599
    {
1600
        $i = strrpos($str, '.');
1601
1602
        $l = strlen($str) - $i;
1603
        $ext = substr($str, $i + 1, $l);
1604
1605
        return $ext;
1606
    }
1607
1608
    /**
1609
     * @param string $extension
1610
     */
1611
    public function getSrc($extension, $temp_path)
1612
    {
1613
        $image_src = '';
1614
        switch ($extension) {
1615
            case 'jpg':
1616
                $image_src = imagecreatefromjpeg($temp_path);
1617
                break;
1618
            case 'jpeg':
1619
                $image_src = imagecreatefromjpeg($temp_path);
1620
                break;
1621
            case 'png':
1622
                $image_src = imagecreatefrompng($temp_path);
1623
                break;
1624
            case 'gif':
1625
                $image_src = imagecreatefromgif($temp_path);
1626
                break;
1627
        }
1628
1629
        return $image_src;
1630
    }
1631
1632
    /**
1633
     * @param string $extension
1634
     * @param string $rep
1635
     * @param integer $mini_width
1636
     * @param integer $mini_height
1637
     */
1638
    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...
1639
    {
1640
        list($src_width, $src_height) = getimagesize($tmp_file);
1641
1642
        $ratio_src = $src_width / $src_height;
1643
        $ratio_mini = $mini_width / $mini_height;
1644
1645
        if ($ratio_src >= $ratio_mini) {
1646
            $new_height_mini = $mini_height;
1647
            $new_width_mini = $src_width / ($src_height / $mini_height);
1648
        } else {
1649
            $new_width_mini = $mini_width;
1650
            $new_height_mini = $src_height / ($src_width / $mini_width);
1651
        }
1652
1653
        $new_image_mini = imagecreatetruecolor($mini_width, $mini_height);
1654
1655
        imagecopyresampled(
1656
            $new_image_mini,
1657
            $src,
1658
            0 - ($new_width_mini - $mini_width) / 2,
1659
            0 - ($new_height_mini - $mini_height) / 2,
1660
            0,
1661
            0,
1662
            $new_width_mini,
1663
            $new_height_mini,
1664
            $src_width,
1665
            $src_height
1666
        );
1667
        imagejpeg($new_image_mini, $rep);
1668
1669
        imagedestroy($new_image_mini);
1670
    }
1671
1672
    public function getGameEntity()
1673
    {
1674
        return new \PlaygroundGame\Entity\Game();
1675
    }
1676
1677
    /**
1678
     * @param string $resource
1679
     * @param string $privilege
1680
     */
1681
    public function isAllowed($resource, $privilege = null)
1682
    {
1683
        $auth = $this->serviceLocator->get('BjyAuthorize\Service\Authorize');
1684
1685
        return $auth->isAllowed($resource, $privilege);
1686
    }
1687
1688
    public function getIp()
1689
    {
1690
        $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...
1691
        if (isset($_SERVER['HTTP_CLIENT_IP'])) {
1692
            $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
1693
        } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1694
            $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
1695
        } elseif (isset($_SERVER['HTTP_X_FORWARDED'])) {
1696
            $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
1697
        } elseif (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
1698
            $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
1699
        } elseif (isset($_SERVER['HTTP_FORWARDED'])) {
1700
            $ipaddress = $_SERVER['HTTP_FORWARDED'];
1701
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
1702
            $ipaddress = $_SERVER['REMOTE_ADDR'];
1703
        } else {
1704
            $ipaddress = 'UNKNOWN';
1705
        }
1706
1707
        return $ipaddress;
1708
    }
1709
1710
    public function getAnonymousId()
1711
    {
1712
        $anonymousId = '';
1713
        if ($_COOKIE && array_key_exists('pg_anonymous', $_COOKIE)) {
1714
            $anonymousId = $_COOKIE['pg_anonymous'];
1715
        }
1716
1717
        return $anonymousId;
1718
    }
1719
1720
    /**
1721
     *
1722
     *
1723
     * This service is ready for all types of games
1724
     *
1725
     * @param array $data
1726
     * @return \PlaygroundGame\Entity\Game
1727
     */
1728 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...
1729
    {
1730
        $title = '';
1731
        $description = '';
1732
1733
        if ($data['form_jsonified']) {
1734
            $jsonPV = json_decode($data['form_jsonified']);
1735
            foreach ($jsonPV as $element) {
1736
                if ($element->form_properties) {
1737
                    $attributes = $element->form_properties[0];
1738
                    $title = $attributes->title;
1739
                    $description = $attributes->description;
1740
1741
                    break;
1742
                }
1743
            }
1744
        }
1745
        if (! $form) {
1746
            $form = new \PlaygroundGame\Entity\PlayerForm();
1747
        }
1748
        $form->setGame($game);
1749
        $form->setTitle($title);
1750
        $form->setDescription($description);
1751
        $form->setForm($data['form_jsonified']);
1752
        $form->setFormTemplate($data['form_template']);
1753
1754
        $form = $this->getPlayerFormMapper()->insert($form);
1755
1756
        return $form;
1757
    }
1758
1759
    /**
1760
     *  getCSV creates lines of CSV and returns it.
1761
     */
1762
    public function getCSV($array)
1763
    {
1764
        ob_start(); // buffer the output ...
1765
        $out = fopen('php://output', 'w');
1766
        fputcsv($out, array_keys($array[0]), ";");
1767
        foreach ($array as $line) {
1768
            fputcsv($out, $line, ";");
1769
        }
1770
        fclose($out);
1771
        return ob_get_clean(); // ... then return it as a string!
1772
    }
1773
    
1774
    public function getAttributes($attributes)
1775
    {
1776
        $a = array();
1777
1778
        $a['name']          = isset($attributes->name)? $attributes->name : '';
1779
        $a['placeholder']   = isset($attributes->data->placeholder)? $attributes->data->placeholder : '';
1780
        $a['label']         = isset($attributes->data->label)? $attributes->data->label : '';
1781
        $a['required']      = (isset($attributes->data->required) && $attributes->data->required == 'true')?
1782
            true:
1783
            false;
1784
        $a['class']         = isset($attributes->data->class)? $attributes->data->class : '';
1785
        $a['id']            = isset($attributes->data->id)? $attributes->data->id : '';
1786
        $a['lengthMin']     = isset($attributes->data->length)? $attributes->data->length->min : '';
1787
        $a['lengthMax']     = isset($attributes->data->length)? $attributes->data->length->max : '';
1788
        $a['validator']     = isset($attributes->data->validator)? $attributes->data->validator : '';
1789
        $a['innerData']     = isset($attributes->data->innerData)? $attributes->data->innerData : array();
1790
        $a['dropdownValues']= isset($attributes->data->dropdownValues)?
1791
            $attributes->data->dropdownValues :
1792
            array();
1793
        $a['filesizeMin']   = isset($attributes->data->filesize)? $attributes->data->filesize->min : 0;
1794
        $a['filesizeMax']   = isset($attributes->data->filesize)? $attributes->data->filesize->max : 10*1024*1024;
1795
        $a['fileextension']   = isset($attributes->data->fileextension)?
1796
            str_replace(', ', ',', $attributes->data->fileextension) :
1797
            'png,jpg,jpeg,gif';
1798
1799
        // hiddenRequired('fileexcludeextension', '').appendTo(li);
1800
        // hiddenRequired('filemimetype', '').appendTo(li);
1801
        // hiddenRequired('fileexcludemimetype', '').appendTo(li);
1802
        // hiddenRequired('fileexists', '').appendTo(li);
1803
        // hiddenRequired('fileimagesize_minheight', '').appendTo(li);
1804
        // hiddenRequired('fileimagesize_maxheight', '').appendTo(li);
1805
        // hiddenRequired('fileimagesize_minwidth', '').appendTo(li);
1806
        // hiddenRequired('fileimagesize_maxwidth', '').appendTo(li);
1807
        // hiddenRequired('fileiscompressed', '').appendTo(li);
1808
        // hiddenRequired('fileisimage', '').appendTo(li);
1809
        // hiddenRequired('filewordcount_min', '').appendTo(li);
1810
        // hiddenRequired('filewordcount_max', '').appendTo(li);
1811
1812
        return $a;
1813
    }
1814
1815
    /**
1816
     * @param \Zend\InputFilter\InputFilter $inputFilter
1817
     */
1818
    public function decorate($element, $attr, $inputFilter)
1819
    {
1820
        $factory = new InputFactory();
1821
        $element->setAttributes(
1822
            array(
1823
                'placeholder'   => $attr['placeholder'],
1824
                'required'      => $attr['required'],
1825
                'class'         => $attr['class'],
1826
                'id'            => $attr['id']
1827
            )
1828
        );
1829
1830
        $options = array();
1831
        $options['encoding'] = 'UTF-8';
1832
        if ($attr['lengthMin'] && $attr['lengthMin'] > 0) {
1833
            $options['min'] = $attr['lengthMin'];
1834
        }
1835
        if ($attr['lengthMax'] && $attr['lengthMax'] > $attr['lengthMin']) {
1836
            $options['max'] = $attr['lengthMax'];
1837
            $element->setAttribute('maxlength', $attr['lengthMax']);
1838
            $options['messages'] = array(
1839
                \Zend\Validator\StringLength::TOO_LONG => sprintf(
1840
                    $this->serviceLocator->get('MvcTranslator')->translate(
1841
                        'This field contains more than %s characters',
1842
                        'playgroundgame'
1843
                    ),
1844
                    $attr['lengthMax']
1845
                )
1846
            );
1847
        }
1848
1849
        $validators = array(
1850
            array(
1851
                'name'    => 'StringLength',
1852
                'options' => $options,
1853
            ),
1854
        );
1855
        if ($attr['validator']) {
1856
            $regex = "/.*\(([^)]*)\)/";
1857
            preg_match($regex, $attr['validator'], $matches);
1858
            $valArray = array(
1859
                'name' => str_replace(
1860
                    '('.$matches[1].')',
1861
                    '',
1862
                    $attr['validator']
1863
                ),
1864
                'options' => array($matches[1])
1865
            );
1866
            $validators[] = $valArray;
1867
        }
1868
1869
        $inputFilter->add($factory->createInput(array(
1870
            'name'     => $attr['name'],
1871
            'required' => $attr['required'],
1872
            'filters'  => array(
1873
                array('name' => 'StripTags'),
1874
                array('name' => 'StringTrim'),
1875
            ),
1876
            'validators' => $validators,
1877
        )));
1878
1879
        return $element;
1880
    }
1881
    /**
1882
     * Create a ZF2 Form from json data
1883
     * @return Form
1884
     */
1885
    public function createFormFromJson($jsonForm, $id = 'jsonForm')
1886
    {
1887
        $formPV = json_decode($jsonForm);
1888
        
1889
        $form = new Form();
1890
        $form->setAttribute('id', $id);
1891
        $form->setAttribute('enctype', 'multipart/form-data');
1892
        
1893
        $inputFilter = new \Zend\InputFilter\InputFilter();
1894
        $factory = new InputFactory();
1895
        
1896
        foreach ($formPV as $element) {
1897 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...
1898
                $attr  = $this->getAttributes($element->line_text[0]);
1899
                $element = new Element\Text($attr['name']);
1900
                $element = $this->decorate($element, $attr, $inputFilter);
1901
                $form->add($element);
1902
            }
1903 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...
1904
                $attr = $this->getAttributes($element->line_password[0]);
1905
                $element = new Element\Password($attr['name']);
1906
                $element = $this->decorate($element, $attr, $inputFilter);
1907
                $form->add($element);
1908
            }
1909 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...
1910
                $attr = $this->getAttributes($element->line_hidden[0]);
1911
                $element = new Element\Hidden($attr['name']);
1912
                $element = $this->decorate($element, $attr, $inputFilter);
1913
                $form->add($element);
1914
            }
1915 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...
1916
                $attr = $this->getAttributes($element->line_email[0]);
1917
                $element = new Element\Email($attr['name']);
1918
                $element = $this->decorate($element, $attr, $inputFilter);
1919
                $form->add($element);
1920
            }
1921 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...
1922
                $attr = $this->getAttributes($element->line_radio[0]);
1923
                $element = new Element\Radio($attr['name']);
1924
1925
                $element->setLabel($attr['label']);
1926
                $element->setAttributes(
1927
                    array(
1928
                        'name'      => $attr['name'],
1929
                        'required'  => $attr['required'],
1930
                        'allowEmpty'=> !$attr['required'],
1931
                        'class'     => $attr['class'],
1932
                        'id'        => $attr['id']
1933
                    )
1934
                );
1935
                $values = array();
1936
                foreach ($attr['innerData'] as $value) {
1937
                    $values[] = $value->label;
1938
                }
1939
                $element->setValueOptions($values);
1940
        
1941
                $options = array();
1942
                $options['encoding'] = 'UTF-8';
1943
                $options['disable_inarray_validator'] = true;
1944
        
1945
                $element->setOptions($options);
1946
        
1947
                $form->add($element);
1948
        
1949
                $inputFilter->add($factory->createInput(array(
1950
                    'name'     => $attr['name'],
1951
                    'required' => $attr['required'],
1952
                    'allowEmpty' => !$attr['required'],
1953
                )));
1954
            }
1955 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...
1956
                $attr = $this->getAttributes($element->line_checkbox[0]);
1957
                $element = new Element\MultiCheckbox($attr['name']);
1958
        
1959
                $element->setLabel($attr['label']);
1960
                $element->setAttributes(
1961
                    array(
1962
                        'name'      => $attr['name'],
1963
                        'required'  => $attr['required'],
1964
                        'allowEmpty'=> !$attr['required'],
1965
                        'class'     => $attr['class'],
1966
                        'id'        => $attr['id']
1967
                    )
1968
                );
1969
1970
                $values = array();
1971
                foreach ($attr['innerData'] as $value) {
1972
                    $values[] = $value->label;
1973
                }
1974
                $element->setValueOptions($values);
1975
                $form->add($element);
1976
        
1977
                $options = array();
1978
                $options['encoding'] = 'UTF-8';
1979
                $options['disable_inarray_validator'] = true;
1980
        
1981
                $element->setOptions($options);
1982
        
1983
                $inputFilter->add($factory->createInput(array(
1984
                    'name'      => $attr['name'],
1985
                    'required'  => $attr['required'],
1986
                    'allowEmpty'=> !$attr['required'],
1987
                )));
1988
            }
1989 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...
1990
                $attr = $this->getAttributes($element->line_dropdown[0]);
1991
                $element = new Element\Select($attr['name']);
1992
1993
                $element->setLabel($attr['label']);
1994
                $element->setAttributes(
1995
                    array(
1996
                        'name'      => $attr['name'],
1997
                        'required'  => $attr['required'],
1998
                        'allowEmpty'=> !$attr['required'],
1999
                        'class'     => $attr['class'],
2000
                        'id'        => $attr['id']
2001
                    )
2002
                );
2003
                $values = array();
2004
                foreach ($attr['dropdownValues'] as $value) {
2005
                    $values[] = $value->dropdown_label;
2006
                }
2007
                $element->setValueOptions($values);
2008
                $form->add($element);
2009
        
2010
                $options = array();
2011
                $options['encoding'] = 'UTF-8';
2012
                $options['disable_inarray_validator'] = true;
2013
        
2014
                $element->setOptions($options);
2015
        
2016
                $inputFilter->add($factory->createInput(array(
2017
                    'name'     => $attr['name'],
2018
                    'required' => $attr['required'],
2019
                    'allowEmpty' => !$attr['required'],
2020
                )));
2021
            }
2022 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...
2023
                $attr = $this->getAttributes($element->line_paragraph[0]);
2024
                $element = new Element\Textarea($attr['name']);
2025
                $element = $this->decorate($element, $attr, $inputFilter);
2026
                $form->add($element);
2027
            }
2028
            if (isset($element->line_upload)) {
2029
                $attr = $this->getAttributes($element->line_upload[0]);
2030
                $element = new Element\File($attr['name']);
2031
2032
                $element->setLabel($attr['label']);
2033
                $element->setAttributes(
2034
                    array(
2035
                        'name'      => $attr['name'],
2036
                        'required'  => $attr['required'],
2037
                        'class'     => $attr['class'],
2038
                        'id'        => $attr['id']
2039
                    )
2040
                );
2041
                $form->add($element);
2042
2043
                $inputFilter->add($factory->createInput(array(
2044
                    'name'     => $attr['name'],
2045
                    'required' => $attr['required'],
2046
                    'validators' => array(
2047
                        array(
2048
                            'name' => '\Zend\Validator\File\Size',
2049
                            'options' => array('min' => $attr['filesizeMin'], 'max' => $attr['filesizeMax'])
2050
                        ),
2051
                        array(
2052
                            'name' => '\Zend\Validator\File\Extension',
2053
                            'options'  => array(
2054
                                $attr['fileextension'],
2055
                                'messages' => array(
2056
                                    \Zend\Validator\File\Extension::FALSE_EXTENSION =>'Veuillez télécharger un fichier avec la bonne extension'
2057
                                )
2058
                            )
2059
                        ),
2060
                    ),
2061
                )));
2062
            }
2063
        }
2064
        
2065
        $form->setInputFilter($inputFilter);
2066
        
2067
        return $form;
2068
    }
2069
2070
    /**
2071
     * Send mail for winner and/or loser
2072
     * @param \PlaygroundGame\Entity\Game $game
2073
     * @param \PlaygroundUser\Entity\User $user
2074
     * @param \PlaygroundGame\Entity\Entry $lastEntry
2075
     * @param \PlaygroundGame\Entity\Prize $prize
2076
     */
2077
    public function sendMail($game, $user, $lastEntry, $prize = null)
2078
    {
2079 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...
2080
            $game->getMailWinner() &&
2081
            $lastEntry->getWinner()
2082
        ) {
2083
            $this->sendResultMail($game, $user, $lastEntry, 'winner', $prize);
2084
        }
2085
2086 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...
2087
            $game->getMailLooser() &&
2088
            !$lastEntry->getWinner()
2089
        ) {
2090
            $this->sendResultMail($game, $user, $lastEntry, 'looser');
2091
        }
2092
    }
2093
2094
    public function getPlayerFormMapper()
2095
    {
2096
        if (null === $this->playerformMapper) {
2097
            $this->playerformMapper = $this->serviceLocator->get('playgroundgame_playerform_mapper');
2098
        }
2099
2100
        return $this->playerformMapper;
2101
    }
2102
2103
    public function setPlayerFormMapper($playerformMapper)
2104
    {
2105
        $this->playerformMapper = $playerformMapper;
2106
2107
        return $this;
2108
    }
2109
2110
    public function getInvitationMapper()
2111
    {
2112
        if (null === $this->invitationMapper) {
2113
            $this->invitationMapper = $this->serviceLocator->get('playgroundgame_invitation_mapper');
2114
        }
2115
2116
        return $this->invitationMapper;
2117
    }
2118
2119
    public function setInvitationMapper($invitationMapper)
2120
    {
2121
        $this->invitationMapper = $invitationMapper;
2122
2123
        return $this;
2124
    }
2125
2126
    /**
2127
     * getUserMapper
2128
     *
2129
     * @return UserMapperInterface
2130
     */
2131
    public function getUserMapper()
2132
    {
2133
        if (null === $this->userMapper) {
2134
            $this->userMapper = $this->serviceLocator->get('zfcuser_user_mapper');
2135
        }
2136
2137
        return $this->userMapper;
2138
    }
2139
2140
    /**
2141
     * getUserMapper
2142
     *
2143
     * @return ServiceManager
2144
     */
2145
    public function getServiceManager()
2146
    {
2147
        return $this->serviceLocator;
2148
    }
2149
}
2150