Completed
Push — develop ( 760d2e...051c16 )
by greg
02:36
created

Game::getEntriesQuery()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 37

Duplication

Lines 36
Ratio 97.3 %

Importance

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