Completed
Pull Request — master (#380)
by greg
04:29 queued 02:01
created

Game::sendMail()   C

Complexity

Conditions 15
Paths 8

Size

Total Lines 22

Duplication

Lines 12
Ratio 54.55 %

Importance

Changes 0
Metric Value
dl 12
loc 22
rs 5.9166
c 0
b 0
f 0
cc 15
nc 8
nop 4

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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