Completed
Push — master ( 989cd3...c05280 )
by greg
167:19 queued 125:26
created

Game::findLastEntries()   B

Complexity

Conditions 7
Paths 4

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 8.6186
c 0
b 0
f 0
cc 7
nc 4
nop 3
1
<?php
2
namespace PlaygroundGame\Service;
3
4
use PlaygroundGame\Entity\Entry;
5
use Zend\Session\Container;
6
use Zend\ServiceManager\ServiceManager;
7
use Zend\EventManager\EventManagerAwareTrait;
8
use Zend\EventManager\EventManager;
9
use PlaygroundGame\Options\ModuleOptions;
10
use PlaygroundGame\Mapper\GameInterface as GameMapperInterface;
11
use DoctrineModule\Validator\NoObjectExists as NoObjectExistsValidator;
12
use Zend\Validator\File\Size;
13
use Zend\Validator\File\IsImage;
14
use Zend\Stdlib\ErrorHandler;
15
use PlaygroundCore\Filter\Sanitize;
16
use Zend\Form\Element;
17
use Zend\Form\Form;
18
use Zend\InputFilter\Factory as InputFactory;
19
use Zend\ServiceManager\ServiceLocatorInterface;
20
21
class Game
22
{
23
    use EventManagerAwareTrait;
24
25
    /**
26
     *
27
     * @var GameMapperInterface
28
     */
29
    protected $gameMapper;
30
31
    /**
32
     *
33
     * @var EntryMapperInterface
34
     */
35
    protected $entryMapper;
36
37
    /**
38
     *
39
     * @var UserServiceOptionsInterface
40
     */
41
    protected $options;
42
43
    protected $playerformMapper;
44
45
    protected $invitationMapper;
46
47
    protected $userMapper;
48
    
49
    protected $anonymousIdentifier = null;
50
51
    /**
52
     *
53
     * @var ServiceManager
54
     */
55
    protected $serviceLocator;
56
57
    protected $event;
58
59
    public function __construct(ServiceLocatorInterface $locator)
60
    {
61
        $this->serviceLocator = $locator;
0 ignored issues
show
Documentation Bug introduced by
$locator is of type object<Zend\ServiceManag...erviceLocatorInterface>, but the property $serviceLocator was declared to be of type object<Zend\ServiceManager\ServiceManager>. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

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

class Alien {}

class Dalek extends Alien {}

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

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
62
    }
63
64 View Code Duplication
    public function getEventManager() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
65
        if (null === $this->event) {
66
            $this->event = new EventManager($this->serviceLocator->get('SharedEventManager'), [get_class($this)]);
67
        }
68
69
        return $this->event;
70
    }
71
72 View Code Duplication
    public function getGameUserPath($game, $user)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
73
    {
74
        $path = $this->getOptions()->getMediaPath() . DIRECTORY_SEPARATOR;
75
        $path .= 'game' . $game->getId() . DIRECTORY_SEPARATOR;
76
        if (!is_dir($path)) {
77
            mkdir($path, 0777, true);
78
        }
79
        $path .= 'user'. $user->getId() . DIRECTORY_SEPARATOR;
80
        if (!is_dir($path)) {
81
            mkdir($path, 0777, true);
82
        }
83
84
        return $path;
85
    }
86
87 View Code Duplication
    public function getGameUserMediaUrl($game, $user)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
88
    {
89
        $media_url = $this->getOptions()->getMediaUrl() . '/';
90
        $media_url .= 'game' . $game->getId() . '/' . 'user'. $user->getId() . '/';
91
92
        return $media_url;
93
    }
94
95
    /**
96
     *
97
     * This service is ready for all types of games
98
     *
99
     * @param array $data
100
     * @param string $formClass
101
     * @return \PlaygroundGame\Entity\Game
102
     */
103
    public function createOrUpdate(array $data, $game, $formClass)
104
    {
105
        $entityManager = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
106
107
        $form = $this->serviceLocator->get($formClass);
108
        $form->get('publicationDate')->setOptions(array(
109
            'format' => 'Y-m-d H:i:s'
110
        ));
111
        $form->get('startDate')->setOptions(array(
112
            'format' => 'Y-m-d H:i:s'
113
        ));
114
        $form->get('endDate')->setOptions(array(
115
            'format' => 'Y-m-d H:i:s'
116
        ));
117
        $form->get('closeDate')->setOptions(array(
118
            'format' => 'Y-m-d H:i:s'
119
        ));
120
121
        $form->bind($game);
122
123
        $path = $this->getOptions()->getMediaPath() . '/';
124
        if (!is_dir($path)) {
125
            mkdir($path, 0777, true);
126
        }
127
        $media_url = $this->getOptions()->getMediaUrl() . '/';
128
129
        $identifierInput = $form->getInputFilter()->get('identifier');
130
        $noObjectExistsValidator = new NoObjectExistsValidator(array(
131
            'object_repository' => $entityManager->getRepository('PlaygroundGame\Entity\Game'),
132
            'fields' => 'identifier',
133
            'messages' => array(
134
                'objectFound' => 'This url already exists !'
135
            )
136
        ));
137
138
        if ($game->getIdentifier() != $data['identifier']) {
139
            $identifierInput->getValidatorChain()->addValidator($noObjectExistsValidator);
140
        }
141
142
        // I must switch from original format to the Y-m-d format because
143
        // this is the only one accepted by new DateTime($value)
144 View Code Duplication
        if (isset($data['publicationDate']) && $data['publicationDate']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
145
            $tmpDate = \DateTime::createFromFormat('d/m/Y H:i:s', $data['publicationDate']);
146
            $data['publicationDate'] = $tmpDate->format('Y-m-d H:i:s');
147
        }
148 View Code Duplication
        if (isset($data['startDate']) && $data['startDate']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
149
            $tmpDate = \DateTime::createFromFormat('d/m/Y H:i:s', $data['startDate']);
150
            $data['startDate'] = $tmpDate->format('Y-m-d H:i:s');
151
        }
152 View Code Duplication
        if (isset($data['endDate']) && $data['endDate']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
153
            $tmpDate = \DateTime::createFromFormat('d/m/Y H:i:s', $data['endDate']);
154
            $data['endDate'] = $tmpDate->format('Y-m-d H:i:s');
155
        }
156 View Code Duplication
        if (isset($data['closeDate']) && $data['closeDate']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
157
            $tmpDate = \DateTime::createFromFormat('d/m/Y H:i:s', $data['closeDate']);
158
            $data['closeDate'] = $tmpDate->format('Y-m-d H:i:s');
159
        }
160
161
        // If publicationDate is null, I update it with the startDate if not null neither
162
        if ((! isset($data['publicationDate']) || $data['publicationDate'] == '') &&
163
            (isset($data['startDate']) && $data['startDate'] != '')
164
        ) {
165
            $data['publicationDate'] = $data['startDate'];
166
        }
167
168
        // If the identifier has not been set, I use the title to create one.
169 View Code Duplication
        if ((! isset($data['identifier']) || empty($data['identifier'])) && isset($data['title'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
170
            $data['identifier'] = $data['title'];
171
        }
172
173
        $form->setData($data);
174
175
        // If someone want to claim... It's time to do it ! used for exemple by PlaygroundFacebook Module
176
        $result = $this->getEventManager()->trigger(__FUNCTION__ . '.validate', $this, array(
177
            'game' => $game,
178
            'data' => $data
179
        ));
180
        if (is_array($result) && ! $result[0]) {
181
            $form->get('fbAppId')->setMessages(array(
182
                'Vous devez d\'abord désinstaller l\'appli Facebook'
183
            ));
184
185
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by PlaygroundGame\Service\Game::createOrUpdate of type PlaygroundGame\Entity\Game.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
186
        }
187
188
        if (! $form->isValid()) {
189 View Code Duplication
            if (isset($data['publicationDate']) && $data['publicationDate']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
190
                $tmpDate = \DateTime::createFromFormat('Y-m-d H:i:s', $data['publicationDate']);
191
                $data['publicationDate'] = $tmpDate->format('d/m/Y H:i:s');
192
                $form->setData(array(
193
                    'publicationDate' => $data['publicationDate']
194
                ));
195
            }
196 View Code Duplication
            if (isset($data['startDate']) && $data['startDate']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
197
                $tmpDate = \DateTime::createFromFormat('Y-m-d H:i:s', $data['startDate']);
198
                $data['startDate'] = $tmpDate->format('d/m/Y H:i:s');
199
                $form->setData(array(
200
                    'startDate' => $data['startDate']
201
                ));
202
            }
203 View Code Duplication
            if (isset($data['endDate']) && $data['endDate']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
204
                $tmpDate = \DateTime::createFromFormat('Y-m-d H:i:s', $data['endDate']);
205
                $data['endDate'] = $tmpDate->format('d/m/Y H:i:s');
206
                $form->setData(array(
207
                    'endDate' => $data['endDate']
208
                ));
209
            }
210 View Code Duplication
            if (isset($data['closeDate']) && $data['closeDate']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
211
                $tmpDate = \DateTime::createFromFormat('Y-m-d H:i:s', $data['closeDate']);
212
                $data['closeDate'] = $tmpDate->format('d/m/Y H:i:s');
213
                $form->setData(array(
214
                    'closeDate' => $data['closeDate']
215
                ));
216
            }
217
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by PlaygroundGame\Service\Game::createOrUpdate of type PlaygroundGame\Entity\Game.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
218
        }
219
220
        $game = $form->getData();
221
        $game = $this->getGameMapper()->insert($game);
222
223
        // I wait for the game to be saved to obtain its ID.
224 View Code Duplication
        if (! empty($data['uploadMainImage']['tmp_name'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
225
            ErrorHandler::start();
226
            $data['uploadMainImage']['name'] = $this->fileNewname(
227
                $path,
228
                $game->getId() . "-" . $data['uploadMainImage']['name']
229
            );
230
            move_uploaded_file($data['uploadMainImage']['tmp_name'], $path . $data['uploadMainImage']['name']);
231
            $game->setMainImage($media_url . $data['uploadMainImage']['name']);
232
            ErrorHandler::stop(true);
233
        }
234
235 View Code Duplication
        if (isset($data['deleteMainImage']) &&
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
236
            $data['deleteMainImage'] &&
237
            empty($data['uploadMainImage']['tmp_name'])
238
        ) {
239
            ErrorHandler::start();
240
            $image = $game->getMainImage();
241
            $image = str_replace($media_url, '', $image);
242
            unlink($path . $image);
243
            $game->setMainImage(null);
244
            ErrorHandler::stop(true);
245
        }
246
247 View Code Duplication
        if (! empty($data['uploadSecondImage']['tmp_name'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
248
            ErrorHandler::start();
249
            $data['uploadSecondImage']['name'] = $this->fileNewname(
250
                $path,
251
                $game->getId() . "-" . $data['uploadSecondImage']['name']
252
            );
253
            move_uploaded_file($data['uploadSecondImage']['tmp_name'], $path . $data['uploadSecondImage']['name']);
254
            $game->setSecondImage($media_url . $data['uploadSecondImage']['name']);
255
            ErrorHandler::stop(true);
256
        }
257
258 View Code Duplication
        if (isset($data['deleteSecondImage']) &&
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
259
            $data['deleteSecondImage'] &&
260
            empty($data['uploadSecondImage']['tmp_name'])
261
        ) {
262
            ErrorHandler::start();
263
            $image = $game->getSecondImage();
264
            $image = str_replace($media_url, '', $image);
265
            unlink($path . $image);
266
            $game->setSecondImage(null);
267
            ErrorHandler::stop(true);
268
        }
269
270
        if (! empty($data['uploadStylesheet']['tmp_name'])) {
271
            ErrorHandler::start();
272
            move_uploaded_file($data['uploadStylesheet']['tmp_name'], $path . 'stylesheet_' . $game->getId() . '.css');
273
            $game->setStylesheet($media_url . 'stylesheet_' . $game->getId() . '.css');
274
            ErrorHandler::stop(true);
275
        }
276
277 View Code Duplication
        if (! empty($data['uploadFbShareImage']['tmp_name'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
278
            ErrorHandler::start();
279
            $data['uploadFbShareImage']['name'] = $this->fileNewname(
280
                $path,
281
                $game->getId() . "-" . $data['uploadFbShareImage']['name']
282
            );
283
            move_uploaded_file($data['uploadFbShareImage']['tmp_name'], $path . $data['uploadFbShareImage']['name']);
284
            $game->setFbShareImage($media_url . $data['uploadFbShareImage']['name']);
285
            ErrorHandler::stop(true);
286
        }
287
288 View Code Duplication
        if (isset($data['deleteFbShareImage']) &&
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
289
            $data['deleteFbShareImage'] &&
290
            empty($data['uploadFbShareImage']['tmp_name'])
291
        ) {
292
            ErrorHandler::start();
293
            $image = $game->getFbShareImage();
294
            $image = str_replace($media_url, '', $image);
295
            unlink($path . $image);
296
            $game->setFbShareImage(null);
297
            ErrorHandler::stop(true);
298
        }
299
300
        if (! empty($data['uploadFbPageTabImage']['tmp_name'])) {
301
            ErrorHandler::start();
302
            $extension = $this->getExtension(strtolower($data['uploadFbPageTabImage']['name']));
303
            $src = $this->getSrc($extension, $data['uploadFbPageTabImage']['tmp_name']);
304
            $this->resize(
305
                $data['uploadFbPageTabImage']['tmp_name'],
306
                $extension,
307
                $path . $game->getId() . "-" . $data['uploadFbPageTabImage']['name'],
308
                $src,
309
                111,
310
                74
311
            );
312
313
            $game->setFbPageTabImage($media_url . $game->getId() . "-" . $data['uploadFbPageTabImage']['name']);
314
            ErrorHandler::stop(true);
315
        }
316
317 View Code Duplication
        if (isset($data['deleteFbPageTabImage']) &&
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
318
            $data['deleteFbPageTabImage'] &&
319
            empty($data['uploadFbPageTabImage']['tmp_name'])
320
        ) {
321
            ErrorHandler::start();
322
            $image = $game->getFbPageTabImage();
323
            $image = str_replace($media_url, '', $image);
324
            unlink($path . $image);
325
            $game->setFbPageTabImage(null);
326
            ErrorHandler::stop(true);
327
        }
328
329
        // Let's remove the fbPostId if there is no post to send anymore
330
        if ($data['broadcastPostFacebook'] == 0) {
331
            $game->setFbPostId(null);
332
        }
333
334
        $game = $this->getGameMapper()->update($game);
335
336
        $prize_mapper = $this->serviceLocator->get('playgroundgame_prize_mapper');
337
        if (isset($data['prizes'])) {
338
            foreach ($data['prizes'] as $prize_data) {
339
                if (! empty($prize_data['picture_file']['tmp_name']) && ! $prize_data['picture_file']['error']) {
340
                    if ($prize_data['id']) {
341
                        $prize = $prize_mapper->findById($prize_data['id']);
342
                    } else {
343
                        $some_prizes = $prize_mapper->findBy(array(
344
                            'game' => $game,
345
                            'title' => $prize_data['title']
346
                        ));
347
                        if (count($some_prizes) == 1) {
348
                            $prize = $some_prizes[0];
349
                        } else {
350
                            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by PlaygroundGame\Service\Game::createOrUpdate of type PlaygroundGame\Entity\Game.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
351
                        }
352
                    }
353
                    // Remove if existing image
354
                    if ($prize->getPicture() && file_exists($prize->getPicture())) {
355
                        unlink($prize->getPicture());
356
                        $prize->getPicture(null);
357
                    }
358
                    // Upload and set new
359
                    ErrorHandler::start();
360
                    $filename = "game-" . $game->getId() . "-prize-";
361
                    $filename .= $prize->getId() . "-" . $prize_data['picture_file']['name'];
362
                    move_uploaded_file($prize_data['picture_file']['tmp_name'], $path . $filename);
363
                    $prize->setPicture($media_url . $filename);
364
                    ErrorHandler::stop(true);
365
                    $prize_mapper->update($prize);
366
                }
367
            }
368
        }
369
        // If I receive false, it means that the FB Id was not available anymore
370
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
371
            'game' => $game
372
        ));
373
374
        return $game;
375
    }
376
    
377
    /**
378
     * getActiveGames
379
     *
380
     * @return Array of PlaygroundGame\Entity\Game
381
     */
382
    public function getActiveGames($displayHome = true, $classType = '', $order = '')
383
    {
384
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
385
        $today = new \DateTime("now");
386
        $today = $today->format('Y-m-d H:i:s');
387
        $orderBy = 'g.publicationDate';
388
        if ($order != '') {
389
            $orderBy = 'g.'.$order;
390
        }
391
392
        $qb = $em->createQueryBuilder();
393
        $and = $qb->expr()->andx();
394
        $and->add(
395
            $qb->expr()->orX(
396
                $qb->expr()->lte('g.publicationDate', ':date'),
397
                $qb->expr()->isNull('g.publicationDate')
398
            )
399
        );
400
        $and->add(
401
            $qb->expr()->orX(
402
                $qb->expr()->gte('g.closeDate', ':date'),
403
                $qb->expr()->isNull('g.closeDate')
404
            )
405
        );
406
        $qb->setParameter('date', $today);
407
        
408
        $and->add($qb->expr()->eq('g.active', '1'));
409
        $and->add($qb->expr()->eq('g.broadcastPlatform', '1'));
410
        
411
        if ($classType != '') {
412
            $and->add($qb->expr()->eq('g.classType', ':classType'));
413
            $qb->setParameter('classType', $classType);
414
        }
415
        
416
        if ($displayHome) {
417
            $and->add($qb->expr()->eq('g.displayHome', true));
418
        }
419
        
420
        $qb->select('g')
421
        ->from('PlaygroundGame\Entity\Game', 'g')
422
        ->where($and)
423
        ->orderBy($orderBy, 'DESC');
424
        
425
        $query = $qb->getQuery();
426
        $games = $query->getResult();
427
        
428
        // je les classe par date de publication (date comme clé dans le tableau afin de pouvoir merger les objets
429
        // de type article avec le même procédé en les classant naturellement par date asc ou desc
430
        $arrayGames = array();
431 View Code Duplication
        foreach ($games as $game) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
432
            if ($game->getPublicationDate()) {
433
                $key = $game->getPublicationDate()->format('Ymd');
434
            } elseif ($game->getStartDate()) {
435
                $key = $game->getStartDate()->format('Ymd');
436
            } else {
437
                $key = $game->getUpdatedAt()->format('Ymd');
438
            }
439
            $key .= $game->getUpdatedAt()->format('Ymd') . '-' . $game->getId();
440
            $arrayGames[$key] = $game;
441
        }
442
443
        return $arrayGames;
444
    }
445
446
    /**
447
     * getAvailableGames : Games OnLine and not already played by $user
448
     *
449
     * @return Array of PlaygroundGame\Entity\Game
450
     */
451
    public function getAvailableGames($user, $maxResults = 2)
452
    {
453
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
454
        $today = new \DateTime("now");
455
        $today = $today->format('Y-m-d H:i:s');
456
457
        // Game active with a start_date before today (or without start_date)
458
        // and end_date after today (or without end-date)
459
        $query = $em->createQuery('SELECT g FROM PlaygroundGame\Entity\Game g
460
                WHERE NOT EXISTS (SELECT l FROM PlaygroundGame\Entity\Entry l WHERE l.game = g AND l.user = :user)
461
                AND (g.startDate <= :date OR g.startDate IS NULL)
462
                AND (g.endDate >= :date OR g.endDate IS NULL)
463
                AND g.active = 1 AND g.broadcastPlatform = 1
464
                ORDER BY g.startDate ASC');
465
        $query->setParameter('date', $today);
466
        $query->setParameter('user', $user);
467
        $query->setMaxResults($maxResults);
468
        $games = $query->getResult();
469
470
        return $games;
471
    }
472
473 View Code Duplication
    public function getEntriesQuery($game)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
474
    {
475
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
476
477
        $qb = $em->createQueryBuilder();
478
        $qb->select('
479
            e.id,
480
            u.username,
481
            u.title,
482
            u.firstname,
483
            u.lastname,
484
            u.email,
485
            u.optin,
486
            u.optinPartner,
487
            u.address,
488
            u.address2,
489
            u.postalCode,
490
            u.city,
491
            u.country,
492
            u.telephone,
493
            u.mobile,
494
            u.created_at,
495
            u.dob,
496
            e.winner,
497
            e.socialShares,
498
            e.playerData,
499
            e.geoloc,
500
            e.updated_at
501
            ')
502
            ->from('PlaygroundGame\Entity\Entry', 'e')
503
            ->leftJoin('e.user', 'u')
504
            ->where($qb->expr()->eq('e.game', ':game'));
505
        
506
        $qb->setParameter('game', $game);
507
508
        return $qb->getQuery();
509
    }
510
511
    public function getEntriesHeader($game)
512
    {
513
        if ($game->getPlayerForm()) {
514
            $formPV = json_decode($game->getPlayerForm()->getForm(), true);
515
            $header = array('id'=> 1);
516 View Code Duplication
            foreach ($formPV as $element) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
517
                foreach ($element as $k => $v) {
518
                    if ($k !== 'form_properties') {
519
                        $header[$v[0]['name']] = 1;
520
                    }
521
                }
522
            }
523
        } else {
524
            $header = array(
525
                'id' => 1,
526
                'username' => 1,
527
                'title' => 1,
528
                'firstname' => 1,
529
                'lastname' => 1,
530
                'email' => 1,
531
                'optin' => 1,
532
                'optinPartner' => 1,
533
                'address' => 1,
534
                'address2' => 1,
535
                'postalCode' => 1,
536
                'city' => 1,
537
                'country' => 1,
538
                'telephone' => 1,
539
                'mobile' => 1,
540
                'created_at' => 1,
541
                'dob' => 1,
542
                'winner' => 1
543
            );
544
        }
545
        $header['geoloc'] = 1;
546
        $header['winner'] = 1;
547
        $header['socialShares'] = 1;
548
        $header['updated_at'] = 1;
549
550
        return $header;
551
    }
552
553
    /**
554
    * getGameEntries : I create an array of entries based on playerData + header
555
    *
556
    * @return Array of PlaygroundGame\Entity\Game
557
    */
558
    public function getGameEntries($header, $entries, $game)
559
    {
560
        $header = $this->getEntriesHeader($game);
561
562
        $results = array();
563
564
        foreach ($entries as $k => $entry) {
565
            $entryData = json_decode($entry['playerData'], true);
566 View Code Duplication
            foreach ($header as $key => $v) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
567
                if (isset($entryData[$key])) {
568
                    $results[$k][$key] = (is_array($entryData[$key]))?implode(', ', $entryData[$key]):$entryData[$key];
569
                } elseif (array_key_exists($key, $entry)) {
570
                    $results[$k][$key] = ($entry[$key] instanceof \DateTime)?
571
                        $entry[$key]->format('Y-m-d H:i:s'):
572
                        $entry[$key];
573
                } else {
574
                    $results[$k][$key] = '';
575
                }
576
            }
577
        }
578
579
        return $results;
580
    }
581
582
    /**
583
     * getActiveSliderGames
584
     *
585
     * @return Array of PlaygroundGame\Entity\Game
586
     */
587
    public function getActiveSliderGames()
588
    {
589
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
590
        $today = new \DateTime("now");
591
        $today = $today->format('Y-m-d H:i:s');
592
593
        // Game active with a start_date before today (or without start_date)
594
        // and end_date after today (or without end-date)
595
        $query = $em->createQuery('SELECT g FROM PlaygroundGame\Entity\Game g
596
            WHERE (g.publicationDate <= :date OR g.publicationDate IS NULL)
597
            AND (g.closeDate >= :date OR g.closeDate IS NULL)
598
            AND g.active = true AND g.broadcastPlatform = 1 AND g.pushHome = true');
599
        $query->setParameter('date', $today);
600
        $games = $query->getResult();
601
602
        // je les classe par date de publication (date comme clé dans le tableau afin de pouvoir merger les objets
603
        // de type article avec le même procédé en les classant naturellement par date asc ou desc
604
        $arrayGames = array();
605 View Code Duplication
        foreach ($games as $game) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
606
            if ($game->getPublicationDate()) {
607
                $key = $game->getPublicationDate()->format('Ymd');
608
            } elseif ($game->getStartDate()) {
609
                $key = $game->getStartDate()->format('Ymd');
610
            } else {
611
                $key = $game->getUpdatedAt()->format('Ymd');
612
            }
613
            $key .= $game->getUpdatedAt()->format('Ymd') . '-' . $game->getId();
614
            $arrayGames[$key] = $game;
615
        }
616
617
        return $arrayGames;
618
    }
619
620
    /**
621
     * getPrizeCategoryGames
622
     *
623
     * @return Array of PlaygroundGame\Entity\Game
624
     */
625 View Code Duplication
    public function getPrizeCategoryGames($categoryid)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
626
    {
627
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
628
629
        $query = $em->createQuery('SELECT g FROM PlaygroundGame\Entity\Game g
630
            WHERE (g.prizeCategory = :categoryid AND g.broadcastPlatform = 1)
631
            ORDER BY g.publicationDate DESC');
632
        $query->setParameter('categoryid', $categoryid);
633
        $games = $query->getResult();
634
635
        return $games;
636
    }
637
638
    public function getGameIdentifierFromFacebook($fbPageId)
639
    {
640
        $identifier = null;
641
        $game = $this->getGameMapper()->findOneBy(array('fbPageId' => $fbPageId, 'broadcastFacebook' => 1));
642
643
        if($game && $game->getIdentifier() !== null) {
644
            $identifier = $game->getIdentifier();
645
        }
646
647
        return $identifier;
648
    }
649
650
    public function checkGame($identifier, $checkIfStarted = true)
651
    {
652
        $gameMapper = $this->getGameMapper();
653
654
        if (! $identifier) {
655
            return false;
656
        }
657
658
        $game = $gameMapper->findByIdentifier($identifier);
659
660
        // the game has not been found
661
        if (! $game) {
662
            return false;
663
        }
664
665
        // for preview stuff as admin
666
        if ($this->isAllowed('game', 'edit')) {
667
            $r =$this->serviceLocator->get('request');
668
            if ($r->getQuery()->get('preview')) {
669
                $game->setActive(true);
670
                $game->setStartDate(null);
671
                $game->setEndDate(null);
672
                $game->setPublicationDate(null);
673
                $game->setBroadcastPlatform(true);
674
675
                // I don't want the game to be updated through any update during the preview mode.
676
                // I mark it as readonly for Doctrine
677
                $this->serviceLocator
678
                    ->get('doctrine.entitymanager.orm_default')
679
                    ->getUnitOfWork()
680
                    ->markReadOnly($game);
681
                    
682
                return $game;
683
            }
684
        }
685
686
        // The game is inactive
687
        if (! $game->getActive()) {
688
            return false;
689
        }
690
691
        // the game has not begun yet
692
        if (! $game->isOpen()) {
693
            return false;
694
        }
695
696
        // the game is finished and closed
697
        if (! $game->isStarted() && $checkIfStarted) {
698
            return false;
699
        }
700
701
        return $game;
702
    }
703
704
    /**
705
     * Return the last entry of the user on this game, if it exists.
706
     * An entry can be associated to :
707
     * - A user account (a real one, linked to PlaygroundUser
708
     * - An anonymous Identifier (based on one value of playerData (generally email))
709
     * - A cookie set on the player device (the less secure)
710
     * If the active param is set, it can check if the entry is active or not.
711
     * If the bonus param is set, it can check if the entry is a bonus or not.
712
     *
713
     * @param unknown $game
714
     * @param string $user
715
     * @param boolean $active
716
     * @param boolean $bonus
717
     * @return boolean
718
     */
719
    public function checkExistingEntry($game, $user = null, $active = null, $bonus = null)
720
    {
721
        $search = array('game'  => $game);
722
723
        if ($user) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $user of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
724
            $search['user'] = $user;
725
        } elseif ($this->getAnonymousIdentifier()) {
726
            $search['anonymousIdentifier'] = $this->getAnonymousIdentifier();
727
            $search['user'] = null;
728
        } else {
729
            $search['anonymousId'] = $this->getAnonymousId();
730
            $search['user'] = null;
731
        }
732
        
733
        if (! is_null($active)) {
734
            $search['active'] = $active;
735
        }
736
        if (! is_null($bonus)) {
737
            $search['bonus'] = $bonus;
738
        }
739
740
        $entry = $this->getEntryMapper()->findOneBy($search, array('updated_at' => 'desc'));
741
742
        return $entry;
743
    }
744
745
    /*
746
    * This function updates the entry with the player data after checking
747
    * that the data are compliant with the formUser Game attribute
748
    *
749
    * The $data has to be a json object
750
    */
751
    public function updateEntryPlayerForm($data, $game, $user, $entry, $mandatory = true)
0 ignored issues
show
Unused Code introduced by
The parameter $user is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
752
    {
753
        $form = $this->createFormFromJson($game->getPlayerForm()->getForm(), 'playerForm');
754
        $form->setData($data);
755
756
        if (!$mandatory) {
757
            $filter = $form->getInputFilter();
758
            foreach ($form->getElements() as $element) {
759
                try {
760
                    $elementInput = $filter->get($element->getName());
761
                    $elementInput->setRequired(false);
762
                    $form->get($element->getName())->setAttribute('required', false);
763
                } catch (\Zend\Form\Exception\InvalidElementException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
764
                }
765
            }
766
        }
767
768
        if ($form->isValid()) {
769
            $dataJson = json_encode($form->getData());
770
771
            if ($game->getAnonymousAllowed() &&
772
                $game->getAnonymousIdentifier() &&
773
                isset($data[$game->getAnonymousIdentifier()])
774
            ) {
775
                $session = new \Zend\Session\Container('anonymous_identifier');
776
                $anonymousIdentifier = $data[$game->getAnonymousIdentifier()];
777
                $entry->setAnonymousIdentifier($anonymousIdentifier);
778
                if (empty($session->offsetGet('anonymous_identifier'))) {
779
                    $session->offsetSet('anonymous_identifier', $anonymousIdentifier);
780
                }
781
            }
782
783
            $entry->setPlayerData($dataJson);
784
            $this->getEntryMapper()->update($entry);
785
        } else {
786
            return false;
787
        }
788
789
        return true;
790
    }
791
792
793
    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...
794
    {
795
        // If on Facebook, check if you have to be a FB fan to play the game
796
        $session = new Container('facebook');
797
798
        if ($session->offsetExists('signed_request')) {
799
            // I'm on Facebook
800
            $sr = $session->offsetGet('signed_request');
801
            if ($sr['page']['liked'] == 1) {
802
                return true;
803
            }
804
        } else {
805
            // I'm not on Facebook
806
            return true;
807
        }
808
809
        return false;
810
    }
811
    
812
    public function getAnonymousIdentifier()
813
    {
814
        if (is_null($this->anonymousIdentifier) || $this->anonymousIdentifier === false) {
815
            $session = new Container('anonymous_identifier');
816
            
817
            if ($session->offsetExists('anonymous_identifier')) {
818
            //if(isset($_SESSION['anonymous_identifier'])) {
819
                //$this->anonymousIdentifier = $_SESSION['anonymous_identifier']['anonymous_identifier'];
820
                $this->anonymousIdentifier = $session->offsetGet('anonymous_identifier');
821
            } else {
822
                $this->anonymousIdentifier = false;
823
            }
824
        }
825
    
826
        return $this->anonymousIdentifier;
827
    }
828
829
    /**
830
     * errors :
831
     * -1 : user not connected
832
     * -2 : limit entry games for this user reached
833
     *
834
     * @param \PlaygroundGame\Entity\Game $game
835
     * @param \PlaygroundUser\Entity\UserInterface $user
836
     * @return number unknown
837
     */
838
    public function play($game, $user)
839
    {
840
841
        // certaines participations peuvent rester ouvertes.
842
        // On autorise alors le joueur à reprendre là ou il en était
843
        // par exemple les postvote...
844
        $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...
845
846
        if (! $entry) {
847
            if ($this->hasReachedPlayLimit($game, $user)) {
848
                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...
849
            }
850
851
            $ip = $this->getIp();
852
            $geoloc = $this->getGeoloc($ip);
853
            $entry = new Entry();
854
            $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...
855
            $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...
856
            $entry->setPoints(0);
857
            $entry->setIp($ip);
858
            $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...
859
            $entry->setAnonymousId($this->getAnonymousId());
860
            if ($this->getAnonymousIdentifier()) {
861
                $entry->setAnonymousIdentifier($this->getAnonymousIdentifier());
862
            }
863
864
            $entry = $this->getEntryMapper()->insert($entry);
865
            $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
866
                'user' => $user,
867
                'game' => $game,
868
                'entry' => $entry
869
            ));
870
        }
871
872
        return $entry;
873
    }
874
875
    /**
876
     * @param \PlaygroundGame\Entity\Game $game
877
     * @param \PlaygroundUser\Entity\UserInterface $user
878
     */
879
    public function hasReachedPlayLimit($game, $user)
880
    {
881
        // Is there a limitation on the game ?
882
        $limitAmount = $game->getPlayLimit();
883
        if ($limitAmount) {
884
            $limitScale = $game->getPlayLimitScale();
885
            $userEntries = $this->findLastEntries($game, $user, $limitScale);
886
887
            // player has reached the game limit
888
            if ($userEntries >= $limitAmount) {
889
                return true;
890
            }
891
        }
892
        return false;
893
    }
894
    
895
    /**
896
     * @param \PlaygroundGame\Entity\Game $game
897
     * @param \PlaygroundUser\Entity\UserInterface $user
898
     */
899
    public function findLastEntries($game, $user, $limitScale)
900
    {
901
        $limitDate = $this->getLimitDate($limitScale);
902
903
        if ($user) {
904
            return $this->getEntryMapper()->findLastEntriesByUser($game, $user, $limitDate);
905
        } elseif ($this->getAnonymousIdentifier()) {
906
            $entries = $this->getEntryMapper()->findLastEntriesByAnonymousIdentifier(
907
                $game,
908
                $this->getAnonymousIdentifier(),
909
                $limitDate
910
            );
911
912
            return $entries;
913
        } else {
914
            // If the game is supposed to be a reguler user game or an anonymous identified game,
915
            // it means that the registration/login is at the end of the game
916
            if((!$user &&  !$game->getAnonymousAllowed()) || ($game->getAnonymousAllowed() && $game->getAnonymousIdentifier())) {
917
                return 0;
918
            }
919
            return $this->getEntryMapper()->findLastEntriesByIp($game, $this->getIp(), $limitDate);
920
        }
921
    }
922
923
    /**
924
    *
925
    *
926
    */
927
    public function getLimitDate($limitScale)
928
    {
929
        $now = new \DateTime("now");
930
        switch ($limitScale) {
931
            case 'always':
932
                $interval = 'P100Y';
933
                $now->sub(new \DateInterval($interval));
934
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
935
                break;
936
            case 'day':
937
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
938
                break;
939 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...
940
                $interval = 'P7D';
941
                $now->sub(new \DateInterval($interval));
942
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
943
                break;
944 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...
945
                $interval = 'P1M';
946
                $now->sub(new \DateInterval($interval));
947
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
948
                break;
949 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...
950
                $interval = 'P1Y';
951
                $now->sub(new \DateInterval($interval));
952
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
953
                break;
954 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...
955
                $interval = 'P100Y';
956
                $now->sub(new \DateInterval($interval));
957
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
958
        }
959
960
        return $dateLimit;
961
    }
962
963
    public function findLastActiveEntry($game, $user)
964
    {
965
        return $this->checkExistingEntry($game, $user, true);
966
    }
967
968
    public function findLastInactiveEntry($game, $user)
969
    {
970
        return $this->checkExistingEntry($game, $user, false, false);
971
    }
972
973
    public function findLastEntry($game, $user)
974
    {
975
        return $this->checkExistingEntry($game, $user, null, false);
976
    }
977
978
    public function inviteToTeam($data, $game, $user)
979
    {
980
        $mailService = $this->serviceLocator->get('playgroundgame_message');
981
        $invitationMapper = $this->serviceLocator->get('playgroundgame_invitation_mapper');
982
983
        $sentInvitations = $invitationMapper->findBy(array('host' => $user, 'game' => $game));
984
        $nbInvitations = count($sentInvitations);
985
        $to = $data['email'];
986
        if (empty($to)) {
987
            return ['result'=>false, 'message'=>'no email'];
988
        }
989
990
        if ($nbInvitations < 20) {
991
            $alreadyInvited = $invitationMapper->findBy(array('requestKey' => $to, 'game' => $game));
992
            if (!$alreadyInvited) {
993
                $alreadyInvited = $this->getUserMapper()->findByEmail($to);
994
            }
995
996
            if (empty($alreadyInvited)) {
997
                $invitation = new \PlaygroundGame\Entity\Invitation();
998
                $invitation->setRequestKey($to);
999
                $invitation->setGame($game);
1000
                $invitation->setHost($user);
1001
                $invitationMapper->insert($invitation);
1002
1003
                $from = $this->getOptions()->getEmailFromAddress();
1004
                $subject = $this->serviceLocator->get('MvcTranslator')->translate(
1005
                    $this->getOptions()->getInviteToTeamSubjectLine(),
1006
                    'playgroundgame'
1007
                );
1008
                $message = $mailService->createHtmlMessage(
1009
                    $from,
1010
                    $to,
1011
                    $subject,
1012
                    'playground-game/email/invite_team',
1013
                    array(
1014
                        'game' => $game,
1015
                        'user' => $user,
1016
                        'data' => $data,
1017
                        'from' => $from
1018
                    )
1019
                );
1020
                try {
1021
                    $mailService->send($message);
1022
                } 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...
1023
                    return ['result' => true, 'message' => $this->serviceLocator->get('MvcTranslator')->translate(
1024
                        'mail error'
1025
                    )];
1026
                }
1027
1028
                return ['result' => true, 'message' => ''];
1029
            } else {
1030
                return ['result' => false, 'message' => 'already invited'];
1031
            }
1032
        } else {
1033
            return [
1034
                'result' => false,
1035
                'message' => $this->serviceLocator->get('MvcTranslator')->translate(
1036
                    'Too many invitations for this user'
1037
                )
1038
            ];
1039
        }
1040
    }
1041
1042
    public function sendShareMail(
1043
        $data,
1044
        $game,
1045
        $user,
1046
        $entry,
1047
        $template = 'share_game',
1048
        $topic = null,
1049
        $userTimer = array(),
1050
        $subject = ''
1051
    ) {
1052
        $mailService = $this->serviceLocator->get('playgroundgame_message');
1053
        $mailSent = false;
1054
        $from = $this->getOptions()->getEmailFromAddress();
1055
1056
        if (empty($subject)) {
1057
            $subject = $this->serviceLocator->get('MvcTranslator')->translate(
1058
                $this->getOptions()->getShareSubjectLine(),
1059
                'playgroundgame'
1060
            );
1061
        } else {
1062
            $subject = $this->serviceLocator->get('MvcTranslator')->translate(
1063
                $subject,
1064
                'playgroundgame'
1065
            );
1066
        }
1067
1068
        $renderer = $this->serviceLocator->get('Zend\View\Renderer\RendererInterface');
1069
        $skinUrl = $renderer->url(
1070
            'frontend',
1071
            array(),
1072
            array('force_canonical' => true)
1073
        );
1074
        $secretKey = strtoupper(substr(sha1(uniqid('pg_', true) . '####' . time()), 0, 15));
1075
1076
        if (! $topic) {
1077
            $topic = $game->getTitle();
1078
        }
1079
1080
        if (isset($data['email']) && !is_array($data['email'])) {
1081
            $data['email'] = array($data['email']);
1082
        }
1083
        
1084
        foreach ($data['email'] as $to) {
1085
            $mailSent = true;
1086
            if (!empty($to)) {
1087
                $message = $mailService->createHtmlMessage(
1088
                    $from,
1089
                    $to,
1090
                    $subject,
1091
                    'playground-game/email/' . $template,
1092
                    array(
1093
                        'game' => $game,
1094
                        'data' => $data,
1095
                        'from' => $from,
1096
                        'to' => $to,
1097
                        'secretKey' => $secretKey,
1098
                        'skinUrl' => $skinUrl,
1099
                        'userTimer' => $userTimer
1100
                    )
1101
                );
1102
                try {
1103
                    $mailService->send($message);
1104
                } 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...
1105
                }
1106
                
1107
                if ($entry) {
1108
                    $shares = json_decode($entry->getSocialShares(), true);
1109
                    (!isset($shares['mail']))? $shares['mail'] = 1:$shares['mail'] += 1;
1110
                }
1111
            }
1112
        }
1113
1114
        if ($mailSent) {
1115
            if ($entry) {
1116
                $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...
1117
                $entry->setSocialShares($sharesJson);
1118
                $entry = $this->getEntryMapper()->update($entry);
1119
            }
1120
            
1121
            $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1122
                'user' => $user,
1123
                'topic' => $topic,
1124
                'secretKey' => $secretKey,
1125
                'data' => $data,
1126
                'game' => $game,
1127
                'entry' => $entry
1128
            ));
1129
1130
            return true;
1131
        }
1132
1133
        return false;
1134
    }
1135
1136
    /**
1137
     * @param \PlaygroundGame\Entity\Game $game
1138
     * @param \PlaygroundUser\Entity\User $user
1139
     * @param Entry $entry
1140
     * @param \PlaygroundGame\Entity\Prize $prize
1141
     */
1142
    public function sendResultMail($game, $user, $entry, $template = 'entry', $prize = null)
1143
    {
1144
        $mailService = $this->serviceLocator->get('playgroundgame_message');
1145
        $from = $this->getOptions()->getEmailFromAddress();
1146
        if ($entry->getAnonymousIdentifier()) {
1147
            $to = $entry->getAnonymousIdentifier();
1148
        } elseif ($user) {
1149
            $to = $user->getEmail();
1150
        } else {
1151
            return false;
1152
        }
1153
        $subject = $this->serviceLocator->get('MvcTranslator')->translate(
1154
            $this->getOptions()->getParticipationSubjectLine(),
1155
            'playgroundgame'
1156
        );
1157
        $renderer = $this->serviceLocator->get('Zend\View\Renderer\RendererInterface');
1158
        $skinUrl = $renderer->url(
1159
            'frontend',
1160
            array(),
1161
            array('force_canonical' => true)
1162
        );
1163
        $message = $mailService->createHtmlMessage($from, $to, $subject, 'playground-game/email/' . $template, array(
1164
            'game' => $game,
1165
            'entry' => $entry,
1166
            'skinUrl' => $skinUrl,
1167
            'prize' => $prize
1168
        ));
1169
        $mailService->send($message);
1170
    }
1171
1172
    public function sendGameMail($game, $user, $post, $template = 'postvote')
1173
    {
1174
        $mailService = $this->serviceLocator->get('playgroundgame_message');
1175
        $from = $this->getOptions()->getEmailFromAddress();
1176
        $to = $user->getEmail();
1177
        $subject = $this->serviceLocator->get('MvcTranslator')->translate(
1178
            $this->getOptions()->getParticipationSubjectLine(),
1179
            'playgroundgame'
1180
        );
1181
        $renderer = $this->serviceLocator->get('Zend\View\Renderer\RendererInterface');
1182
        $skinUrl = $renderer->url(
1183
            'frontend',
1184
            array(),
1185
            array('force_canonical' => true)
1186
        );
1187
1188
        $message = $mailService->createHtmlMessage($from, $to, $subject, 'playground-game/email/' . $template, array(
1189
            'game' => $game,
1190
            'post' => $post,
1191
            'skinUrl' => $skinUrl
1192
        ));
1193
        $mailService->send($message);
1194
    }
1195
1196 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...
1197
    {
1198
        $topic = $game->getTitle();
1199
        
1200
        $shares = json_decode($entry->getSocialShares(), true);
1201
        if (!isset($shares['fbwall'])) {
1202
            $shares['fbwall'] = 1;
1203
        } else {
1204
            $shares['fbwall'] += 1;
1205
        }
1206
        $sharesJson = json_encode($shares);
1207
        $entry->setSocialShares($sharesJson);
1208
        $entry = $this->getEntryMapper()->update($entry);
1209
        
1210
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1211
            'user' => $user,
1212
            'game' => $game,
1213
            'secretKey' => $secretKey,
1214
            'topic' => $topic,
1215
            'entry' => $entry
1216
        ));
1217
1218
        return true;
1219
    }
1220
1221
    public function postFbRequest($secretKey, $game, $user, $entry, $to)
1222
    {
1223
        $shares = json_decode($entry->getSocialShares(), true);
1224
        $to = explode(',', $to);
1225
        if (!isset($shares['fbrequest'])) {
1226
            $shares['fbrequest'] = count($to);
1227
        } else {
1228
            $shares['fbrequest'] += count($to);
1229
        }
1230
        $sharesJson = json_encode($shares);
1231
        $entry->setSocialShares($sharesJson);
1232
        $entry = $this->getEntryMapper()->update($entry);
1233
        
1234
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1235
            'user' => $user,
1236
            'game' => $game,
1237
            'secretKey' => $secretKey,
1238
            'entry' => $entry,
1239
            'invites' => count($to)
1240
        ));
1241
1242
        return true;
1243
    }
1244
1245 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...
1246
    {
1247
        $topic = $game->getTitle();
1248
1249
        $shares = json_decode($entry->getSocialShares(), true);
1250
        if (!isset($shares['fbrequest'])) {
1251
            $shares['tweet'] = 1;
1252
        } else {
1253
            $shares['tweet'] += 1;
1254
        }
1255
        $sharesJson = json_encode($shares);
1256
        $entry->setSocialShares($sharesJson);
1257
        $entry = $this->getEntryMapper()->update($entry);
1258
        
1259
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1260
            'user' => $user,
1261
            'game' => $game,
1262
            'secretKey' => $secretKey,
1263
            'topic' => $topic,
1264
            'entry' => $entry
1265
        ));
1266
1267
        return true;
1268
    }
1269
1270 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...
1271
    {
1272
        $topic = $game->getTitle();
1273
        
1274
        $shares = json_decode($entry->getSocialShares(), true);
1275
        if (!isset($shares['fbrequest'])) {
1276
            $shares['google'] = 1;
1277
        } else {
1278
            $shares['google'] += 1;
1279
        }
1280
        $sharesJson = json_encode($shares);
1281
        $entry->setSocialShares($sharesJson);
1282
        $entry = $this->getEntryMapper()->update($entry);
1283
1284
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1285
            'user' => $user,
1286
            'game' => $game,
1287
            'secretKey' => $secretKey,
1288
            'topic' => $topic,
1289
            'entry' => $entry
1290
        ));
1291
1292
        return true;
1293
    }
1294
1295
    /**
1296
     * Is it possible to trigger a bonus entry ?
1297
     *
1298
     * @param unknown_type $game
1299
     * @param unknown_type $user
1300
     */
1301
    public function allowBonus($game, $user)
1302
    {
1303
        if (! $game->getPlayBonus() || $game->getPlayBonus() == 'none') {
1304
            return false;
1305
        } elseif ($game->getPlayBonus() == 'one') {
1306
            if ($this->getEntryMapper()->findOneBy(array(
1307
                'game' => $game,
1308
                'user' => $user,
1309
                'bonus' => 1
1310
            ))) {
1311
                return false;
1312
            } else {
1313
                return true;
1314
            }
1315
        } elseif ($game->getPlayBonus() == 'per_entry') {
1316
            return $this->getEntryMapper()->checkBonusEntry($game, $user);
1317
        }
1318
1319
        return false;
1320
    }
1321
1322
    public function addAnotherEntry($game, $user, $winner = 0)
1323
    {
1324
        $entry = new Entry();
1325
        $entry->setGame($game);
1326
        $entry->setUser($user);
1327
        $entry->setPoints(0);
1328
        $entry->setIp($this->getIp());
1329
        $entry->setActive(0);
1330
        $entry->setBonus(1);
1331
        $entry->setWinner($winner);
1332
        $entry = $this->getEntryMapper()->insert($entry);
1333
1334
        return $entry;
1335
    }
1336
1337
    /**
1338
     * This bonus entry doesn't give points nor badges
1339
     * It's just there to increase the chances during the Draw
1340
     * Old Name playBonus
1341
     *
1342
     * @param PlaygroundGame\Entity\Game $game
1343
     * @param unknown $user
1344
     * @return boolean unknown
1345
     */
1346
    public function addAnotherChance($game, $user, $winner = 0)
1347
    {
1348
        if ($this->allowBonus($game, $user)) {
1349
            $this->addAnotherEntry($game, $user, $winner);
1350
1351
            return true;
1352
        }
1353
1354
        return false;
1355
    }
1356
1357
    /**
1358
     * This bonus entry doesn't give points nor badges but can play again
1359
     *
1360
     * @param PlaygroundGame\Entity\Game $game
1361
     * @param user $user
1362
     * @return boolean unknown
1363
     */
1364
    public function playAgain($game, $user, $winner = 0)
1365
    {
1366
        if ($this->allowBonus($game, $user)) {
1367
            $entry = $this->addAnotherEntry($game, $user, $winner);
1368
            $entry->setActive(1);
1369
            $entry = $this->getEntryMapper()->update($entry);
1370
            if ($entry->getActive() == 1) {
1371
                return true;
1372
            }
1373
        }
1374
1375
        return false;
1376
    }
1377
1378
    /**
1379
     * @param string $path
1380
     * @param boolean $noReplace : If the image name already exist, don't replace it but change the name
1381
     */
1382
    public function uploadFile($path, $file, $noReplace = true)
1383
    {
1384
        $err = $file["error"];
1385
        $message = '';
1386
        if ($err > 0) {
1387
            switch ($err) {
1388
                case '1':
1389
                    $message .= 'Max file size exceeded. (php.ini)';
1390
                    break;
1391
                case '2':
1392
                    $message .= 'Max file size exceeded.';
1393
                    break;
1394
                case '3':
1395
                    $message .= 'File upload was only partial.';
1396
                    break;
1397
                case '4':
1398
                    $message .= 'No file was attached.';
1399
                    break;
1400
                case '7':
1401
                    $message .= 'File permission denied.';
1402
                    break;
1403
                default:
1404
                    $message .= 'Unexpected error occurs.';
1405
            }
1406
1407
            return $err;
1408
        } else {
1409
            $fileNewname = $this->fileNewname($path, $file['name'], $noReplace);
1410
1411
            if (isset($file["base64"])) {
1412
                list(, $img) = explode(',', $file["base64"]);
1413
                $img = str_replace(' ', '+', $img);
1414
                $im = base64_decode($img);
1415
                if ($im !== false) {
1416
                    // getimagesizefromstring
1417
                    file_put_contents($path . $fileNewname, $im);
1418
                } else {
1419
                    return 1;
1420
                }
1421
1422
                return $fileNewname;
1423
            } else {
1424
                $adapter = new \Zend\File\Transfer\Adapter\Http();
1425
                // 1Mo
1426
                $size = new Size(array(
1427
                    'max' => 1024000
1428
                ));
1429
                $is_image = new IsImage('jpeg,png,gif,jpg');
1430
                $adapter->setValidators(array(
1431
                    $size,
1432
                    $is_image
1433
                ), $fileNewname);
1434
1435
                if (! $adapter->isValid()) {
1436
                    return false;
1437
                }
1438
1439
                @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...
1440
            }
1441
1442
            
1443
            if (class_exists("Imagick")) {
1444
                $ext = pathinfo($fileNewname, PATHINFO_EXTENSION);
1445
                $img = new \Imagick($path . $fileNewname);
1446
                $img->cropThumbnailImage(100, 100);
1447
                $img->setImageCompression(\Imagick::COMPRESSION_JPEG);
1448
                $img->setImageCompressionQuality(75);
1449
                // Strip out unneeded meta data
1450
                $img->stripImage();
1451
                $img->writeImage($path . str_replace('.'.$ext, '-thumbnail.'.$ext, $fileNewname));
1452
                ErrorHandler::stop(true);
1453
            }
1454
        }
1455
1456
        return $fileNewname;
1457
    }
1458
1459
    /**
1460
     * @param string $path
1461
     */
1462
    public function fileNewname($path, $filename, $generate = false)
1463
    {
1464
        $sanitize = new Sanitize();
1465
        $name = $sanitize->filter($filename);
1466
        $newpath = $path . $name;
1467
1468
        if ($generate) {
1469
            if (file_exists($newpath)) {
1470
                $filename = pathinfo($name, PATHINFO_FILENAME);
1471
                $ext = pathinfo($name, PATHINFO_EXTENSION);
1472
1473
                $name = $filename . '_' . rand(0, 99) . '.' . $ext;
1474
            }
1475
        }
1476
1477
        unset($sanitize);
1478
1479
        return $name;
1480
    }
1481
1482
    /**
1483
     * This function returns the list of games, order by $type
1484
     */
1485
    public function getQueryGamesOrderBy($type = 'createdAt', $order = 'DESC')
1486
    {
1487
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
1488
        $today = new \DateTime("now");
1489
        $today = $today->format('Y-m-d H:i:s');
1490
1491
        $onlineGames = '(
1492
            (
1493
                CASE WHEN (
1494
                    g.active = 1
1495
                    AND g.broadcastPlatform = 1
1496
                    AND (g.startDate <= :date OR g.startDate IS NULL)
1497
                    AND (g.closeDate >= :date OR g.closeDate IS NULL)
1498
                ) THEN 1 ELSE 0 END
1499
            ) +
1500
            (
1501
                CASE WHEN (
1502
                    g.active = 0
1503
                    AND (g.broadcastPlatform = 0 OR g.broadcastPlatform IS NULL)
1504
                    AND g.startDate > :date
1505
                    AND g.closeDate < :date
1506
                ) THEN 1 ELSE 0 END
1507
            )
1508
        )';
1509
1510
        $qb = $em->createQueryBuilder();
1511
        $qb->select('g')->from('PlaygroundGame\Entity\Game', 'g');
1512
        
1513
        switch ($type) {
1514
            case 'startDate':
1515
                $qb->orderBy('g.startDate', $order);
1516
                break;
1517
            case 'activeGames':
1518
                $qb->orderBy('g.active', $order);
1519
                break;
1520
            case 'onlineGames':
1521
                $qb->orderBy($onlineGames, $order);
1522
                $qb->setParameter('date', $today);
1523
                break;
1524
            case 'createdAt':
1525
                $qb->orderBy('g.createdAt', $order);
1526
                break;
1527
        }
1528
1529
        $query = $qb->getQuery();
1530
1531
        return $query;
1532
    }
1533
1534
    public function draw($game)
1535
    {
1536
        $total = $game->getWinners();
1537
1538
        // I Have to know what is the User Class used
1539
        $zfcUserOptions = $this->serviceLocator->get('zfcuser_module_options');
1540
        $userClass = $zfcUserOptions->getUserEntityClass();
1541
1542
        $result = $this->getEntryMapper()->draw($game, $userClass, $total);
1543
1544
        foreach ($result as $e) {
1545
            $e->setWinner(1);
1546
            $e = $this->getEntryMapper()->update($e);
1547
            $this->getEventManager()->trigger('win_lottery.post', $this, array(
1548
                'user' => $e->getUser(),
1549
                'game' => $game,
1550
                'entry' => $e
1551
            ));
1552
        }
1553
1554
        return $result;
1555
    }
1556
1557
    /**
1558
     * getGameMapper
1559
     *
1560
     * @return GameMapperInterface
1561
     */
1562 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...
1563
    {
1564
        if (null === $this->gameMapper) {
1565
            $this->gameMapper = $this->serviceLocator->get('playgroundgame_game_mapper');
1566
        }
1567
1568
        return $this->gameMapper;
1569
    }
1570
1571
    /**
1572
     * setGameMapper
1573
     *
1574
     * @param GameMapperInterface $gameMapper
1575
     * @return Game
1576
     */
1577
    public function setGameMapper(GameMapperInterface $gameMapper)
1578
    {
1579
        $this->gameMapper = $gameMapper;
1580
1581
        return $this;
1582
    }
1583
1584
    /**
1585
     * getEntryMapper
1586
     *
1587
     * @return EntryMapperInterface
1588
     */
1589
    public function getEntryMapper()
1590
    {
1591
        if (null === $this->entryMapper) {
1592
            $this->entryMapper = $this->serviceLocator->get('playgroundgame_entry_mapper');
1593
        }
1594
1595
        return $this->entryMapper;
1596
    }
1597
1598
    /**
1599
     * setEntryMapper
1600
     *
1601
     * @param EntryMapperInterface $entryMapper
1602
     * @return Game
1603
     */
1604
    public function setEntryMapper($entryMapper)
1605
    {
1606
        $this->entryMapper = $entryMapper;
1607
1608
        return $this;
1609
    }
1610
1611
    public function setOptions(ModuleOptions $options)
1612
    {
1613
        $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...
1614
1615
        return $this;
1616
    }
1617
1618
    public function getOptions()
1619
    {
1620
        if (! $this->options instanceof ModuleOptions) {
1621
            $this->setOptions($this->serviceLocator
1622
                ->get('playgroundgame_module_options'));
1623
        }
1624
1625
        return $this->options;
1626
    }
1627
1628
    /**
1629
     * @param string $str
1630
     */
1631
    public function getExtension($str)
1632
    {
1633
        $i = strrpos($str, '.');
1634
1635
        $l = strlen($str) - $i;
1636
        $ext = substr($str, $i + 1, $l);
1637
1638
        return $ext;
1639
    }
1640
1641
    /**
1642
     * @param string $extension
1643
     */
1644
    public function getSrc($extension, $temp_path)
1645
    {
1646
        $image_src = '';
1647
        switch ($extension) {
1648
            case 'jpg':
1649
                $image_src = imagecreatefromjpeg($temp_path);
1650
                break;
1651
            case 'jpeg':
1652
                $image_src = imagecreatefromjpeg($temp_path);
1653
                break;
1654
            case 'png':
1655
                $image_src = imagecreatefrompng($temp_path);
1656
                break;
1657
            case 'gif':
1658
                $image_src = imagecreatefromgif($temp_path);
1659
                break;
1660
        }
1661
1662
        return $image_src;
1663
    }
1664
1665
    /**
1666
     * @param string $extension
1667
     * @param string $rep
1668
     * @param integer $mini_width
1669
     * @param integer $mini_height
1670
     */
1671
    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...
1672
    {
1673
        list($src_width, $src_height) = getimagesize($tmp_file);
1674
1675
        $ratio_src = $src_width / $src_height;
1676
        $ratio_mini = $mini_width / $mini_height;
1677
1678
        if ($ratio_src >= $ratio_mini) {
1679
            $new_height_mini = $mini_height;
1680
            $new_width_mini = $src_width / ($src_height / $mini_height);
1681
        } else {
1682
            $new_width_mini = $mini_width;
1683
            $new_height_mini = $src_height / ($src_width / $mini_width);
1684
        }
1685
1686
        $new_image_mini = imagecreatetruecolor($mini_width, $mini_height);
1687
1688
        imagecopyresampled(
1689
            $new_image_mini,
1690
            $src,
1691
            0 - ($new_width_mini - $mini_width) / 2,
1692
            0 - ($new_height_mini - $mini_height) / 2,
1693
            0,
1694
            0,
1695
            $new_width_mini,
1696
            $new_height_mini,
1697
            $src_width,
1698
            $src_height
1699
        );
1700
        imagejpeg($new_image_mini, $rep);
1701
1702
        imagedestroy($new_image_mini);
1703
    }
1704
1705
    public function getGameEntity()
1706
    {
1707
        return new \PlaygroundGame\Entity\Game();
1708
    }
1709
1710
    /**
1711
     * @param string $resource
1712
     * @param string $privilege
1713
     */
1714
    public function isAllowed($resource, $privilege = null)
1715
    {
1716
        $auth = $this->serviceLocator->get('BjyAuthorize\Service\Authorize');
1717
1718
        return $auth->isAllowed($resource, $privilege);
1719
    }
1720
1721
    public function getIp()
1722
    {
1723
        $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...
1724
        if (isset($_SERVER['HTTP_CLIENT_IP'])) {
1725
            $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
1726
        } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1727
            $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
1728
        } elseif (isset($_SERVER['HTTP_X_FORWARDED'])) {
1729
            $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
1730
        } elseif (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
1731
            $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
1732
        } elseif (isset($_SERVER['HTTP_FORWARDED'])) {
1733
            $ipaddress = $_SERVER['HTTP_FORWARDED'];
1734
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
1735
            $ipaddress = $_SERVER['REMOTE_ADDR'];
1736
        } else {
1737
            $ipaddress = 'UNKNOWN';
1738
        }
1739
1740
        return $ipaddress;
1741
    }
1742
1743
    public function getGeoloc($ip)
1744
    {
1745
        $geoloc = '';
1746
        try {
1747
            $res = unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip='.$ip));
1748
            if($res['geoplugin_latitude'] != '') {
1749
                $geoloc = $res['geoplugin_latitude'] . ',' . $res['geoplugin_longitude'];
1750
            }
1751
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
1752
1753
        } 
1754
1755
        return $geoloc;
1756
    }
1757
1758
    public function getAnonymousId()
1759
    {
1760
        $anonymousId = '';
1761
        if ($_COOKIE && array_key_exists('pg_anonymous', $_COOKIE)) {
1762
            $anonymousId = $_COOKIE['pg_anonymous'];
1763
        }
1764
1765
        return $anonymousId;
1766
    }
1767
1768
    /**
1769
     *
1770
     *
1771
     * This service is ready for all types of games
1772
     *
1773
     * @param array $data
1774
     * @return \PlaygroundGame\Entity\Game
1775
     */
1776 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...
1777
    {
1778
        $title = '';
1779
        $description = '';
1780
1781
        if ($data['form_jsonified']) {
1782
            $jsonPV = json_decode($data['form_jsonified']);
1783
            foreach ($jsonPV as $element) {
1784
                if ($element->form_properties) {
1785
                    $attributes = $element->form_properties[0];
1786
                    $title = $attributes->title;
1787
                    $description = $attributes->description;
1788
1789
                    break;
1790
                }
1791
            }
1792
        }
1793
        if (! $form) {
1794
            $form = new \PlaygroundGame\Entity\PlayerForm();
1795
        }
1796
        $form->setGame($game);
1797
        $form->setTitle($title);
1798
        $form->setDescription($description);
1799
        $form->setForm($data['form_jsonified']);
1800
        $form->setFormTemplate($data['form_template']);
1801
1802
        $form = $this->getPlayerFormMapper()->insert($form);
1803
1804
        return $form;
1805
    }
1806
1807
    /**
1808
     *  getCSV creates lines of CSV and returns it.
1809
     */
1810
    public function getCSV($array)
1811
    {
1812
        ob_start(); // buffer the output ...
1813
        $out = fopen('php://output', 'w');
1814
        fputcsv($out, array_keys($array[0]), ";");
1815
        foreach ($array as $line) {
1816
            fputcsv($out, $line, ";");
1817
        }
1818
        fclose($out);
1819
        return ob_get_clean(); // ... then return it as a string!
1820
    }
1821
    
1822
    public function getAttributes($attributes)
1823
    {
1824
        $a = array();
1825
1826
        $a['name']          = isset($attributes->name)? $attributes->name : '';
1827
        $a['placeholder']   = isset($attributes->data->placeholder)? $attributes->data->placeholder : '';
1828
        $a['label']         = isset($attributes->data->label)? $attributes->data->label : '';
1829
        $a['required']      = (isset($attributes->data->required) && $attributes->data->required == 'true')?
1830
            true:
1831
            false;
1832
        $a['class']         = isset($attributes->data->class)? $attributes->data->class : '';
1833
        $a['id']            = isset($attributes->data->id)? $attributes->data->id : '';
1834
        $a['lengthMin']     = isset($attributes->data->length)? $attributes->data->length->min : '';
1835
        $a['lengthMax']     = isset($attributes->data->length)? $attributes->data->length->max : '';
1836
        $a['validator']     = isset($attributes->data->validator)? $attributes->data->validator : '';
1837
        $a['innerData']     = isset($attributes->data->innerData)? $attributes->data->innerData : array();
1838
        $a['dropdownValues']= isset($attributes->data->dropdownValues)?
1839
            $attributes->data->dropdownValues :
1840
            array();
1841
        $a['filesizeMin']   = isset($attributes->data->filesize)? $attributes->data->filesize->min : 0;
1842
        $a['filesizeMax']   = isset($attributes->data->filesize)? $attributes->data->filesize->max : 10*1024*1024;
1843
        $a['fileextension']   = isset($attributes->data->fileextension)?
1844
            str_replace(', ', ',', $attributes->data->fileextension) :
1845
            'png,jpg,jpeg,gif';
1846
1847
        // hiddenRequired('fileexcludeextension', '').appendTo(li);
1848
        // hiddenRequired('filemimetype', '').appendTo(li);
1849
        // hiddenRequired('fileexcludemimetype', '').appendTo(li);
1850
        // hiddenRequired('fileexists', '').appendTo(li);
1851
        // hiddenRequired('fileimagesize_minheight', '').appendTo(li);
1852
        // hiddenRequired('fileimagesize_maxheight', '').appendTo(li);
1853
        // hiddenRequired('fileimagesize_minwidth', '').appendTo(li);
1854
        // hiddenRequired('fileimagesize_maxwidth', '').appendTo(li);
1855
        // hiddenRequired('fileiscompressed', '').appendTo(li);
1856
        // hiddenRequired('fileisimage', '').appendTo(li);
1857
        // hiddenRequired('filewordcount_min', '').appendTo(li);
1858
        // hiddenRequired('filewordcount_max', '').appendTo(li);
1859
1860
        return $a;
1861
    }
1862
1863
    /**
1864
     * @param \Zend\InputFilter\InputFilter $inputFilter
1865
     */
1866
    public function decorate($element, $attr, $inputFilter)
1867
    {
1868
        $factory = new InputFactory();
1869
        $element->setAttributes(
1870
            array(
1871
                'placeholder'   => $attr['placeholder'],
1872
                'required'      => $attr['required'],
1873
                'class'         => $attr['class'],
1874
                'id'            => $attr['id']
1875
            )
1876
        );
1877
1878
        $options = array();
1879
        $options['encoding'] = 'UTF-8';
1880
        if ($attr['lengthMin'] && $attr['lengthMin'] > 0) {
1881
            $options['min'] = $attr['lengthMin'];
1882
        }
1883
        if ($attr['lengthMax'] && $attr['lengthMax'] > $attr['lengthMin']) {
1884
            $options['max'] = $attr['lengthMax'];
1885
            $element->setAttribute('maxlength', $attr['lengthMax']);
1886
            $options['messages'] = array(
1887
                \Zend\Validator\StringLength::TOO_LONG => sprintf(
1888
                    $this->serviceLocator->get('MvcTranslator')->translate(
1889
                        'This field contains more than %s characters',
1890
                        'playgroundgame'
1891
                    ),
1892
                    $attr['lengthMax']
1893
                )
1894
            );
1895
        }
1896
1897
        $validators = array(
1898
            array(
1899
                'name'    => 'StringLength',
1900
                'options' => $options,
1901
            ),
1902
        );
1903
        if ($attr['validator']) {
1904
            $regex = "/.*\(([^)]*)\)/";
1905
            preg_match($regex, $attr['validator'], $matches);
1906
            $valArray = array(
1907
                'name' => str_replace(
1908
                    '('.$matches[1].')',
1909
                    '',
1910
                    $attr['validator']
1911
                ),
1912
                'options' => array($matches[1])
1913
            );
1914
            $validators[] = $valArray;
1915
        }
1916
1917
        $inputFilter->add($factory->createInput(array(
1918
            'name'     => $attr['name'],
1919
            'required' => $attr['required'],
1920
            'filters'  => array(
1921
                array('name' => 'StripTags'),
1922
                array('name' => 'StringTrim'),
1923
            ),
1924
            'validators' => $validators,
1925
        )));
1926
1927
        return $element;
1928
    }
1929
    /**
1930
     * Create a ZF2 Form from json data
1931
     * @return Form
1932
     */
1933
    public function createFormFromJson($jsonForm, $id = 'jsonForm')
1934
    {
1935
        $formPV = json_decode($jsonForm);
1936
        
1937
        $form = new Form();
1938
        $form->setAttribute('id', $id);
1939
        $form->setAttribute('enctype', 'multipart/form-data');
1940
        
1941
        $inputFilter = new \Zend\InputFilter\InputFilter();
1942
        $factory = new InputFactory();
1943
        
1944
        foreach ($formPV as $element) {
1945 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...
1946
                $attr  = $this->getAttributes($element->line_text[0]);
1947
                $element = new Element\Text($attr['name']);
1948
                $element = $this->decorate($element, $attr, $inputFilter);
1949
                $form->add($element);
1950
            }
1951 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...
1952
                $attr = $this->getAttributes($element->line_password[0]);
1953
                $element = new Element\Password($attr['name']);
1954
                $element = $this->decorate($element, $attr, $inputFilter);
1955
                $form->add($element);
1956
            }
1957 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...
1958
                $attr = $this->getAttributes($element->line_hidden[0]);
1959
                $element = new Element\Hidden($attr['name']);
1960
                $element = $this->decorate($element, $attr, $inputFilter);
1961
                $form->add($element);
1962
            }
1963 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...
1964
                $attr = $this->getAttributes($element->line_email[0]);
1965
                $element = new Element\Email($attr['name']);
1966
                $element = $this->decorate($element, $attr, $inputFilter);
1967
                $form->add($element);
1968
            }
1969 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...
1970
                $attr = $this->getAttributes($element->line_radio[0]);
1971
                $element = new Element\Radio($attr['name']);
1972
1973
                $element->setLabel($attr['label']);
1974
                $element->setAttributes(
1975
                    array(
1976
                        'name'      => $attr['name'],
1977
                        'required'  => $attr['required'],
1978
                        'allowEmpty'=> !$attr['required'],
1979
                        'class'     => $attr['class'],
1980
                        'id'        => $attr['id']
1981
                    )
1982
                );
1983
                $values = array();
1984
                foreach ($attr['innerData'] as $value) {
1985
                    $values[] = $value->label;
1986
                }
1987
                $element->setValueOptions($values);
1988
        
1989
                $options = array();
1990
                $options['encoding'] = 'UTF-8';
1991
                $options['disable_inarray_validator'] = true;
1992
        
1993
                $element->setOptions($options);
1994
        
1995
                $form->add($element);
1996
        
1997
                $inputFilter->add($factory->createInput(array(
1998
                    'name'     => $attr['name'],
1999
                    'required' => $attr['required'],
2000
                    'allowEmpty' => !$attr['required'],
2001
                )));
2002
            }
2003 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...
2004
                $attr = $this->getAttributes($element->line_checkbox[0]);
2005
                $element = new Element\MultiCheckbox($attr['name']);
2006
        
2007
                $element->setLabel($attr['label']);
2008
                $element->setAttributes(
2009
                    array(
2010
                        'name'      => $attr['name'],
2011
                        'required'  => $attr['required'],
2012
                        'allowEmpty'=> !$attr['required'],
2013
                        'class'     => $attr['class'],
2014
                        'id'        => $attr['id']
2015
                    )
2016
                );
2017
2018
                $values = array();
2019
                foreach ($attr['innerData'] as $value) {
2020
                    $values[] = $value->label;
2021
                }
2022
                $element->setValueOptions($values);
2023
                $form->add($element);
2024
        
2025
                $options = array();
2026
                $options['encoding'] = 'UTF-8';
2027
                $options['disable_inarray_validator'] = true;
2028
        
2029
                $element->setOptions($options);
2030
        
2031
                $inputFilter->add($factory->createInput(array(
2032
                    'name'      => $attr['name'],
2033
                    'required'  => $attr['required'],
2034
                    'allowEmpty'=> !$attr['required'],
2035
                )));
2036
            }
2037 View Code Duplication
            if (isset($element->line_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...
2038
                $attr = $this->getAttributes($element->line_dropdown[0]);
2039
                $element = new Element\Select($attr['name']);
2040
2041
                $element->setLabel($attr['label']);
2042
                $element->setAttributes(
2043
                    array(
2044
                        'name'      => $attr['name'],
2045
                        'required'  => $attr['required'],
2046
                        'allowEmpty'=> !$attr['required'],
2047
                        'class'     => $attr['class'],
2048
                        'id'        => $attr['id']
2049
                    )
2050
                );
2051
                $values = array();
2052
                foreach ($attr['dropdownValues'] as $value) {
2053
                    $values[] = $value->dropdown_label;
2054
                }
2055
                $element->setValueOptions($values);
2056
                $form->add($element);
2057
        
2058
                $options = array();
2059
                $options['encoding'] = 'UTF-8';
2060
                $options['disable_inarray_validator'] = true;
2061
        
2062
                $element->setOptions($options);
2063
        
2064
                $inputFilter->add($factory->createInput(array(
2065
                    'name'     => $attr['name'],
2066
                    'required' => $attr['required'],
2067
                    'allowEmpty' => !$attr['required'],
2068
                )));
2069
            }
2070 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...
2071
                $attr = $this->getAttributes($element->line_paragraph[0]);
2072
                $element = new Element\Textarea($attr['name']);
2073
                $element = $this->decorate($element, $attr, $inputFilter);
2074
                $form->add($element);
2075
            }
2076
            if (isset($element->line_upload)) {
2077
                $attr = $this->getAttributes($element->line_upload[0]);
2078
                $element = new Element\File($attr['name']);
2079
2080
                $element->setLabel($attr['label']);
2081
                $element->setAttributes(
2082
                    array(
2083
                        'name'      => $attr['name'],
2084
                        'required'  => $attr['required'],
2085
                        'class'     => $attr['class'],
2086
                        'id'        => $attr['id']
2087
                    )
2088
                );
2089
                $form->add($element);
2090
2091
                $inputFilter->add($factory->createInput(array(
2092
                    'name'     => $attr['name'],
2093
                    'required' => $attr['required'],
2094
                    'validators' => array(
2095
                        array(
2096
                            'name' => '\Zend\Validator\File\Size',
2097
                            'options' => array('min' => $attr['filesizeMin'], 'max' => $attr['filesizeMax'])
2098
                        ),
2099
                        array(
2100
                            'name' => '\Zend\Validator\File\Extension',
2101
                            'options'  => array(
2102
                                $attr['fileextension'],
2103
                                'messages' => array(
2104
                                    \Zend\Validator\File\Extension::FALSE_EXTENSION =>'Veuillez télécharger un fichier avec la bonne extension'
2105
                                )
2106
                            )
2107
                        ),
2108
                    ),
2109
                )));
2110
            }
2111
        }
2112
        
2113
        $form->setInputFilter($inputFilter);
2114
        
2115
        return $form;
2116
    }
2117
2118
    /**
2119
     * Send mail for winner and/or loser
2120
     * @param \PlaygroundGame\Entity\Game $game
2121
     * @param \PlaygroundUser\Entity\User $user
2122
     * @param \PlaygroundGame\Entity\Entry $lastEntry
2123
     * @param \PlaygroundGame\Entity\Prize $prize
2124
     */
2125
    public function sendMail($game, $user, $lastEntry, $prize = null)
2126
    {
2127 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...
2128
            $game->getMailWinner() &&
2129
            $lastEntry->getWinner()
2130
        ) {
2131
            $this->sendResultMail($game, $user, $lastEntry, 'winner', $prize);
2132
        }
2133
2134 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...
2135
            $game->getMailLooser() &&
2136
            !$lastEntry->getWinner()
2137
        ) {
2138
            $this->sendResultMail($game, $user, $lastEntry, 'looser');
2139
        }
2140
2141
        if (($user || ($game->getAnonymousAllowed() && $game->getAnonymousIdentifier())) &&
2142
            $game->getMailEntry()
2143
        ) {
2144
            $this->sendResultMail($game, $user, $lastEntry);
2145
        }
2146
    }
2147
2148
    public function getPlayerFormMapper()
2149
    {
2150
        if (null === $this->playerformMapper) {
2151
            $this->playerformMapper = $this->serviceLocator->get('playgroundgame_playerform_mapper');
2152
        }
2153
2154
        return $this->playerformMapper;
2155
    }
2156
2157
    public function setPlayerFormMapper($playerformMapper)
2158
    {
2159
        $this->playerformMapper = $playerformMapper;
2160
2161
        return $this;
2162
    }
2163
2164
    public function getInvitationMapper()
2165
    {
2166
        if (null === $this->invitationMapper) {
2167
            $this->invitationMapper = $this->serviceLocator->get('playgroundgame_invitation_mapper');
2168
        }
2169
2170
        return $this->invitationMapper;
2171
    }
2172
2173
    public function setInvitationMapper($invitationMapper)
2174
    {
2175
        $this->invitationMapper = $invitationMapper;
2176
2177
        return $this;
2178
    }
2179
2180
    /**
2181
     * getUserMapper
2182
     *
2183
     * @return UserMapperInterface
2184
     */
2185
    public function getUserMapper()
2186
    {
2187
        if (null === $this->userMapper) {
2188
            $this->userMapper = $this->serviceLocator->get('zfcuser_user_mapper');
2189
        }
2190
2191
        return $this->userMapper;
2192
    }
2193
2194
    /**
2195
     * getUserMapper
2196
     *
2197
     * @return ServiceManager
2198
     */
2199
    public function getServiceManager()
2200
    {
2201
        return $this->serviceLocator;
2202
    }
2203
}
2204