Completed
Push — master ( 8a3179...d462e2 )
by greg
24:52 queued 21:12
created

Game::getGameIdentifierFromFacebook()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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