Completed
Push — develop ( 365d8c...a11766 )
by greg
02:35
created

Game::payToPlay()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

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