Completed
Push — master ( 64789b...259751 )
by greg
03:57
created

Game   F

Complexity

Total Complexity 345

Size/Duplication

Total Lines 2432
Duplicated Lines 21.71 %

Coupling/Cohesion

Components 1
Dependencies 27

Importance

Changes 0
Metric Value
wmc 345
lcom 1
cbo 27
dl 528
loc 2432
rs 0.8
c 0
b 0
f 0

71 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getEventManager() 7 7 2
A getGameUserPath() 14 14 3
A getGameUserMediaUrl() 7 7 1
F createOrUpdate() 121 273 55
B getNextGames() 11 65 9
A getAvailableGames() 0 21 1
A getEntriesQuery() 36 37 1
B getEntriesHeader() 7 50 7
B getGameEntries() 11 23 7
A getActiveSliderGames() 11 32 4
A getPrizeCategoryGames() 12 12 1
A getGameIdentifierFromFacebook() 0 11 3
B checkGame() 0 53 9
A checkExistingEntry() 0 25 5
B updateEntryPlayerForm() 0 40 9
A checkIsFan() 0 18 3
A getAnonymousIdentifier() 0 14 4
B getActiveGames() 11 64 7
B setTermsOptin() 0 44 6
D play() 0 95 15
A hasReachedPlayLimit() 0 15 3
A canPayToPlay() 0 22 5
A payToPlay() 0 28 4
B findLastEntries() 8 23 7
B getLimitDate() 19 35 6
A findLastActiveEntry() 0 4 1
A findLastInactiveEntry() 0 4 1
A findLastEntry() 0 4 1
B inviteToTeam() 0 63 6
D sendShareMail() 0 87 14
A sendResultMail() 0 29 3
A sendGameMail() 0 23 1
A postFbWall() 24 24 2
A postFbRequest() 0 23 2
A postTwitter() 24 24 2
A postGoogle() 24 24 2
B allowBonus() 0 20 6
A addAnotherEntry() 0 14 1
A addAnotherChance() 0 10 2
A playAgain() 0 13 3
C uploadFile() 0 76 11
A fileNewname() 0 19 3
B getQueryGamesOrderBy() 0 48 5
A draw() 0 22 2
A getGameMapper() 8 8 2
A setGameMapper() 0 6 1
A getEntryMapper() 0 8 2
A setEntryMapper() 0 6 1
A setOptions() 0 6 1
A getOptions() 0 9 2
A getExtension() 0 9 1
A getSrc() 0 20 5
A resize() 0 33 2
A getGameEntity() 0 4 1
A isAllowed() 0 6 1
B getIp() 0 21 7
A getGeoloc() 0 14 3
A getAnonymousId() 0 9 3
A createForm() 30 30 5
A getCSV() 0 11 2
F getAttributes() 0 40 16
B decorate() 0 63 6
F createFormFromJson() 131 184 14
C sendMail() 12 22 15
A getPlayerFormMapper() 0 8 2
A setPlayerFormMapper() 0 6 1
A getInvitationMapper() 0 8 2
A setInvitationMapper() 0 6 1
A getUserMapper() 0 8 2
A getServiceManager() 0 4 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Game often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Game, and based on these observations, apply Extract Interface, too.

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
     * getNextGames
379
     *
380
     * @return Array of PlaygroundGame\Entity\Game
381
     */
382
    public function getNextGames($dateStart = null, $dateEnd = null, $classType = null, $cost = null, $order = null, $dir = 'DESC')
383
    {
384
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
385
        if ($dateStart === null) {
386
            $today = new \DateTime("now");
387
        } else {
388
            $today = new \DateTime($dateStart);
389
        }
390
        
391
        $today = $today->format('Y-m-d H:i:s');
392
        $orderBy = 'g.startDate';
393
        if ($order != null) {
394
            $orderBy = 'g.'.$order;
395
        }
396
397
        $qb = $em->createQueryBuilder();
398
        $and = $qb->expr()->andx();
399
        $and->add($qb->expr()->gte('g.startDate', ':date'));
400
        $qb->setParameter('date', $today);
401
        if ($dateEnd != null) {
402
            $dateEnd = new \DateTime($dateEnd);
403
            $end = $dateEnd->format('Y-m-d H:i:s');
404
            $and->add($qb->expr()->lte('g.endDate', ':datefin'));
405
            $qb->setParameter('datefin', $end);
406
        }
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 ($cost !== null) {
417
            $and->add($qb->expr()->eq('g.costToPlay', ':cost'));
418
            $qb->setParameter('cost', $cost);
419
        }
420
        
421
        $qb->select('g')
422
            ->from('PlaygroundGame\Entity\Game', 'g')
423
            ->where($and)
424
            ->orderBy($orderBy, $dir);
425
        
426
        $query = $qb->getQuery();
427
        //echo $query->getSql();
428
        $games = $query->getResult();
429
        
430
        // je les classe par date de publication (date comme clé dans le tableau afin de pouvoir merger les objets
431
        // de type article avec le même procédé en les classant naturellement par date asc ou desc
432
        $arrayGames = array();
433 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...
434
            if ($game->getPublicationDate()) {
435
                $key = $game->getPublicationDate()->format('Ymd');
436
            } elseif ($game->getStartDate()) {
437
                $key = $game->getStartDate()->format('Ymd');
438
            } else {
439
                $key = $game->getUpdatedAt()->format('Ymd');
440
            }
441
            $key .= $game->getUpdatedAt()->format('Ymd') . '-' . $game->getId();
442
            $arrayGames[$key] = $game;
443
        }
444
445
        return $arrayGames;
446
    }
447
448
    /**
449
     * getActiveGames
450
     *
451
     * @return Array of PlaygroundGame\Entity\Game
452
     */
453
    public function getActiveGames($displayHome = null, $classType = '', $order = '', $dir = 'DESC')
454
    {
455
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
456
        $today = new \DateTime("now");
457
        $today = $today->format('Y-m-d H:i:s');
458
        $orderBy = 'g.publicationDate';
459
        if ($order != '') {
460
            $orderBy = 'g.'.$order;
461
        }
462
463
        $qb = $em->createQueryBuilder();
464
        $and = $qb->expr()->andx();
465
        $and->add(
466
            $qb->expr()->orX(
467
                $qb->expr()->lte('g.publicationDate', ':date'),
468
                $qb->expr()->isNull('g.publicationDate')
469
            )
470
        );
471
        $and->add(
472
            $qb->expr()->orX(
473
                $qb->expr()->gte('g.closeDate', ':date'),
474
                $qb->expr()->isNull('g.closeDate')
475
            )
476
        );
477
        $qb->setParameter('date', $today);
478
        
479
        $and->add($qb->expr()->eq('g.active', '1'));
480
        $and->add($qb->expr()->eq('g.broadcastPlatform', '1'));
481
        
482
        if ($classType != '') {
483
            $and->add($qb->expr()->eq('g.classType', ':classType'));
484
            $qb->setParameter('classType', $classType);
485
        }
486
        
487
        if ($displayHome !== null) {
488
            $and->add($qb->expr()->eq('g.displayHome', ':key'));
489
            $qb->setParameter('key', $displayHome);
490
        }
491
        
492
        $qb->select('g')
493
            ->from('PlaygroundGame\Entity\Game', 'g')
494
            ->where($and)
495
            ->orderBy($orderBy, $dir);
496
        
497
        $query = $qb->getQuery();
498
        $games = $query->getResult();
499
        
500
        // je les classe par date de publication (date comme clé dans le tableau afin de pouvoir merger les objets
501
        // de type article avec le même procédé en les classant naturellement par date asc ou desc
502
        $arrayGames = array();
503 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...
504
            if ($game->getPublicationDate()) {
505
                $key = $game->getPublicationDate()->format('Ymd');
506
            } elseif ($game->getStartDate()) {
507
                $key = $game->getStartDate()->format('Ymd');
508
            } else {
509
                $key = $game->getUpdatedAt()->format('Ymd');
510
            }
511
            $key .= $game->getUpdatedAt()->format('Ymd') . '-' . $game->getId();
512
            $arrayGames[$key] = $game;
513
        }
514
515
        return $arrayGames;
516
    }
517
518
    /**
519
     * getAvailableGames : Games OnLine and not already played by $user
520
     *
521
     * @return Array of PlaygroundGame\Entity\Game
522
     */
523
    public function getAvailableGames($user, $maxResults = 2)
524
    {
525
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
526
        $today = new \DateTime("now");
527
        $today = $today->format('Y-m-d H:i:s');
528
529
        // Game active with a start_date before today (or without start_date)
530
        // and end_date after today (or without end-date)
531
        $query = $em->createQuery('SELECT g FROM PlaygroundGame\Entity\Game g
532
                WHERE NOT EXISTS (SELECT l FROM PlaygroundGame\Entity\Entry l WHERE l.game = g AND l.user = :user)
533
                AND (g.startDate <= :date OR g.startDate IS NULL)
534
                AND (g.endDate >= :date OR g.endDate IS NULL)
535
                AND g.active = 1 AND g.broadcastPlatform = 1
536
                ORDER BY g.startDate ASC');
537
        $query->setParameter('date', $today);
538
        $query->setParameter('user', $user);
539
        $query->setMaxResults($maxResults);
540
        $games = $query->getResult();
541
542
        return $games;
543
    }
544
545 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...
546
    {
547
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
548
549
        $qb = $em->createQueryBuilder();
550
        $qb->select('
551
            e.id,
552
            u.username,
553
            u.title,
554
            u.firstname,
555
            u.lastname,
556
            u.email,
557
            u.optin,
558
            u.optinPartner,
559
            u.address,
560
            u.address2,
561
            u.postalCode,
562
            u.city,
563
            u.country,
564
            u.telephone,
565
            u.mobile,
566
            u.created_at,
567
            u.dob,
568
            e.winner,
569
            e.socialShares,
570
            e.playerData,
571
            e.geoloc,
572
            e.updated_at
573
            ')
574
            ->from('PlaygroundGame\Entity\Entry', 'e')
575
            ->leftJoin('e.user', 'u')
576
            ->where($qb->expr()->eq('e.game', ':game'));
577
        
578
        $qb->setParameter('game', $game);
579
580
        return $qb->getQuery();
581
    }
582
583
    public function getEntriesHeader($game)
584
    {
585
        if ($game->getAnonymousAllowed() && $game->getPlayerForm()) {
586
            $formPV = json_decode($game->getPlayerForm()->getForm(), true);
587
            $header = array('id'=> 1);
588 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...
589
                foreach ($element as $k => $v) {
590
                    if ($k !== 'form_properties') {
591
                        $header[$v[0]['name']] = 1;
592
                    }
593
                }
594
            }
595
        } elseif ($game->getAnonymousAllowed()) {
596
            $header = array(
597
                'id' => 1,
598
                'ip' => 1,
599
                'geoloc' => 1,
600
                'winner' => 1,
601
                'socialShares' => 1,
602
                'updated_at' => 1,
603
            );
604
        } else {
605
            $header = array(
606
                'id' => 1,
607
                'username' => 1,
608
                'title' => 1,
609
                'firstname' => 1,
610
                'lastname' => 1,
611
                'email' => 1,
612
                'optin' => 1,
613
                'optinPartner' => 1,
614
                'address' => 1,
615
                'address2' => 1,
616
                'postalCode' => 1,
617
                'city' => 1,
618
                'country' => 1,
619
                'telephone' => 1,
620
                'mobile' => 1,
621
                'created_at' => 1,
622
                'dob' => 1,
623
                'winner' => 1
624
            );
625
        }
626
        $header['geoloc'] = 1;
627
        $header['winner'] = 1;
628
        $header['socialShares'] = 1;
629
        $header['updated_at'] = 1;
630
631
        return $header;
632
    }
633
634
    /**
635
    * getGameEntries : I create an array of entries based on playerData + header
636
    *
637
    * @return Array of PlaygroundGame\Entity\Game
638
    */
639
    public function getGameEntries($header, $entries, $game)
640
    {
641
        $header = $this->getEntriesHeader($game);
642
643
        $results = array();
644
645
        foreach ($entries as $k => $entry) {
646
            $entryData = json_decode($entry['playerData'], true);
647 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...
648
                if (isset($entryData[$key])) {
649
                    $results[$k][$key] = (is_array($entryData[$key]))?implode(', ', $entryData[$key]):$entryData[$key];
650
                } elseif (array_key_exists($key, $entry)) {
651
                    $results[$k][$key] = ($entry[$key] instanceof \DateTime)?
652
                        $entry[$key]->format('Y-m-d H:i:s'):
653
                        $entry[$key];
654
                } else {
655
                    $results[$k][$key] = '';
656
                }
657
            }
658
        }
659
660
        return $results;
661
    }
662
663
    /**
664
     * getActiveSliderGames
665
     *
666
     * @return Array of PlaygroundGame\Entity\Game
667
     */
668
    public function getActiveSliderGames()
669
    {
670
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
671
        $today = new \DateTime("now");
672
        $today = $today->format('Y-m-d H:i:s');
673
674
        // Game active with a start_date before today (or without start_date)
675
        // and end_date after today (or without end-date)
676
        $query = $em->createQuery('SELECT g FROM PlaygroundGame\Entity\Game g
677
            WHERE (g.publicationDate <= :date OR g.publicationDate IS NULL)
678
            AND (g.closeDate >= :date OR g.closeDate IS NULL)
679
            AND g.active = true AND g.broadcastPlatform = 1 AND g.pushHome = true');
680
        $query->setParameter('date', $today);
681
        $games = $query->getResult();
682
683
        // je les classe par date de publication (date comme clé dans le tableau afin de pouvoir merger les objets
684
        // de type article avec le même procédé en les classant naturellement par date asc ou desc
685
        $arrayGames = array();
686 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...
687
            if ($game->getPublicationDate()) {
688
                $key = $game->getPublicationDate()->format('Ymd');
689
            } elseif ($game->getStartDate()) {
690
                $key = $game->getStartDate()->format('Ymd');
691
            } else {
692
                $key = $game->getUpdatedAt()->format('Ymd');
693
            }
694
            $key .= $game->getUpdatedAt()->format('Ymd') . '-' . $game->getId();
695
            $arrayGames[$key] = $game;
696
        }
697
698
        return $arrayGames;
699
    }
700
701
    /**
702
     * getPrizeCategoryGames
703
     *
704
     * @return Array of PlaygroundGame\Entity\Game
705
     */
706 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...
707
    {
708
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
709
710
        $query = $em->createQuery('SELECT g FROM PlaygroundGame\Entity\Game g
711
            WHERE (g.prizeCategory = :categoryid AND g.broadcastPlatform = 1)
712
            ORDER BY g.publicationDate DESC');
713
        $query->setParameter('categoryid', $categoryid);
714
        $games = $query->getResult();
715
716
        return $games;
717
    }
718
719
    public function getGameIdentifierFromFacebook($fbPageId)
720
    {
721
        $identifier = null;
722
        $game = $this->getGameMapper()->findOneBy(array('fbPageId' => $fbPageId, 'broadcastFacebook' => 1));
723
724
        if($game && $game->getIdentifier() !== null) {
725
            $identifier = $game->getIdentifier();
726
        }
727
728
        return $identifier;
729
    }
730
731
    public function checkGame($identifier, $checkIfStarted = true)
732
    {
733
        $gameMapper = $this->getGameMapper();
734
735
        if (! $identifier) {
736
            return false;
737
        }
738
739
        $game = $gameMapper->findByIdentifier($identifier);
740
741
        // the game has not been found
742
        if (! $game) {
743
            return false;
744
        }
745
746
        // for preview stuff as admin
747
        if ($this->isAllowed('game', 'edit')) {
748
            $r =$this->serviceLocator->get('request');
749
            if ($r->getQuery()->get('preview')) {
750
                $game->setActive(true);
751
                $game->setStartDate(null);
752
                $game->setEndDate(null);
753
                $game->setPublicationDate(null);
754
                $game->setBroadcastPlatform(true);
755
756
                // I don't want the game to be updated through any update during the preview mode.
757
                // I mark it as readonly for Doctrine
758
                $this->serviceLocator
759
                    ->get('doctrine.entitymanager.orm_default')
760
                    ->getUnitOfWork()
761
                    ->markReadOnly($game);
762
                    
763
                return $game;
764
            }
765
        }
766
767
        // The game is inactive
768
        if (! $game->getActive()) {
769
            return false;
770
        }
771
772
        // the game has not begun yet
773
        if (! $game->isOpen()) {
774
            return false;
775
        }
776
777
        // the game is finished and closed
778
        if (! $game->isStarted() && $checkIfStarted) {
779
            return false;
780
        }
781
782
        return $game;
783
    }
784
785
    /**
786
     * Return the last entry of the user on this game, if it exists.
787
     * An entry can be associated to :
788
     * - A user account (a real one, linked to PlaygroundUser
789
     * - An anonymous Identifier (based on one value of playerData (generally email))
790
     * - A cookie set on the player device (the less secure)
791
     * If the active param is set, it can check if the entry is active or not.
792
     * If the bonus param is set, it can check if the entry is a bonus or not.
793
     *
794
     * @param unknown $game
795
     * @param string $user
796
     * @param boolean $active
797
     * @param boolean $bonus
798
     * @return boolean
799
     */
800
    public function checkExistingEntry($game, $user = null, $active = null, $bonus = null)
801
    {
802
        $search = array('game'  => $game);
803
804
        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...
805
            $search['user'] = $user;
806
        } elseif ($this->getAnonymousIdentifier()) {
807
            $search['anonymousIdentifier'] = $this->getAnonymousIdentifier();
808
            $search['user'] = null;
809
        } else {
810
            $search['anonymousId'] = $this->getAnonymousId();
811
            $search['user'] = null;
812
        }
813
        
814
        if (! is_null($active)) {
815
            $search['active'] = $active;
816
        }
817
        if (! is_null($bonus)) {
818
            $search['bonus'] = $bonus;
819
        }
820
821
        $entry = $this->getEntryMapper()->findOneBy($search, array('updated_at' => 'desc'));
822
823
        return $entry;
824
    }
825
826
    /*
827
    * This function updates the entry with the player data after checking
828
    * that the data are compliant with the formUser Game attribute
829
    *
830
    * The $data has to be a json object
831
    */
832
    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...
833
    {
834
        $form = $this->createFormFromJson($game->getPlayerForm()->getForm(), 'playerForm');
835
        $form->setData($data);
836
837
        if (!$mandatory) {
838
            $filter = $form->getInputFilter();
839
            foreach ($form->getElements() as $element) {
840
                try {
841
                    $elementInput = $filter->get($element->getName());
842
                    $elementInput->setRequired(false);
843
                    $form->get($element->getName())->setAttribute('required', false);
844
                } 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...
845
                }
846
            }
847
        }
848
849
        if ($form->isValid()) {
850
            $dataJson = json_encode($form->getData());
851
852
            if ($game->getAnonymousAllowed() &&
853
                $game->getAnonymousIdentifier() &&
854
                isset($data[$game->getAnonymousIdentifier()])
855
            ) {
856
                $session = new \Zend\Session\Container('anonymous_identifier');
857
                $anonymousIdentifier = $data[$game->getAnonymousIdentifier()];
858
                $entry->setAnonymousIdentifier($anonymousIdentifier);
859
                if (empty($session->offsetGet('anonymous_identifier'))) {
860
                    $session->offsetSet('anonymous_identifier', $anonymousIdentifier);
861
                }
862
            }
863
864
            $entry->setPlayerData($dataJson);
865
            $this->getEntryMapper()->update($entry);
866
        } else {
867
            return false;
868
        }
869
870
        return true;
871
    }
872
873
874
    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...
875
    {
876
        // If on Facebook, check if you have to be a FB fan to play the game
877
        $session = new Container('facebook');
878
879
        if ($session->offsetExists('signed_request')) {
880
            // I'm on Facebook
881
            $sr = $session->offsetGet('signed_request');
882
            if ($sr['page']['liked'] == 1) {
883
                return true;
884
            }
885
        } else {
886
            // I'm not on Facebook
887
            return true;
888
        }
889
890
        return false;
891
    }
892
    
893
    public function getAnonymousIdentifier()
894
    {
895
        if (is_null($this->anonymousIdentifier) || $this->anonymousIdentifier === false) {
896
            $session = new Container('anonymous_identifier');
897
            
898
            if ($session->offsetExists('anonymous_identifier')) {
899
                $this->anonymousIdentifier = $session->offsetGet('anonymous_identifier');
900
            } else {
901
                $this->anonymousIdentifier = false;
902
            }
903
        }
904
    
905
        return $this->anonymousIdentifier;
906
    }
907
908
    /**
909
     * setTermsOptin
910
     *
911
     * @return Boolean the result of the terms optin update
912
     */
913
    public function setTermsOptin($optin, $game, $user)
914
    {
915
        $entry = $this->checkExistingEntry($game, $user, true);
916
917
        if ($entry) {
918
            $entry->setTermsOptin($optin);
0 ignored issues
show
Bug introduced by
The method setTermsOptin cannot be called on $entry (of type boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
919
            $entry = $this->getEntryMapper()->update($entry);
920
        } else {
921
            if (!$this->hasReachedPlayLimit($game, $user)
922
                && $this->canPayToPlay($game, $user)
923
            ) {
924
                $ip = $this->getIp();
925
                $geoloc = $this->getGeoloc($ip);
926
                $entry = new Entry();
927
                $entry->setGame($game);
928
                $entry->setUser($user);
929
                $entry->setPoints(0);
930
                $entry->setIp($ip);
931
                $entry->setGeoloc($geoloc);
0 ignored issues
show
Documentation introduced by
$geoloc is of type string, but the function expects a object<PlaygroundGame\Entity\field_type>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
932
                $entry->setAnonymousId($this->getAnonymousId());
933
                if ($this->getAnonymousIdentifier()) {
934
                    $entry->setAnonymousIdentifier($this->getAnonymousIdentifier());
935
                }
936
                $entry->setTermsOptin($optin);
937
                $entry = $this->getEntryMapper()->insert($entry);
938
            }
939
        }
940
941
        if ($entry) {
942
            $this->getEventManager()->trigger(
943
                __FUNCTION__ . '.post',
944
                $this,
945
                [
946
                    'user' => $user,
947
                    'game' => $game,
948
                    'entry' => $entry,
949
                ]
950
            );
951
952
            return true;
953
        }
954
955
        return false;
956
    }
957
958
    /**
959
     * errors :
960
     * -1 : limit entry games for this user reached
961
     * -2 : no terms optin
962
     * -3 : no payment
963
     *
964
     * @param \PlaygroundGame\Entity\Game $game
965
     * @param \PlaygroundUser\Entity\UserInterface $user
966
     * @return number unknown
967
     */
968
    public function play($game, $user, &$error=null)
969
    {
970
        //some entries can stay open during days.
971
        // The player can take back the entry to go on playing
972
        // like in a postvote or for quizzes
973
        // We create also an entry before the game when an optin is needed
974
        $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...
975
976
        // If the game needs an optin and the player has not opted in
977
        if ($entry && $game->getTermsOptin() && !$entry->getTermsOptin()) {
0 ignored issues
show
Bug introduced by
The method getTermsOptin cannot be called on $entry (of type boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
978
            $error = -2;
979
            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...
980
        }
981
982
        // If the game has a cost and the player has not paid yet
983
        // (this case occurs when the entry has been created by the termsOptin
984
        // and the game has a price to play)
985
        if ($entry && !$entry->getPaid() && $game->getCostToPlay() > 0) {
0 ignored issues
show
Bug introduced by
The method getPaid cannot be called on $entry (of type boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
986
            if (!$this->payToPlay($game, $user, $entry)) {
987
                $error = -3;
988
                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...
989
            } else {
990
                $entry->setPaid(1);
0 ignored issues
show
Bug introduced by
The method setPaid cannot be called on $entry (of type boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
991
                $entry->setPaidAmount($game->getCostToPlay());
0 ignored issues
show
Bug introduced by
The method setPaidAmount cannot be called on $entry (of type boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
992
                $entry = $this->getEntryMapper()->update($entry);
993
            }
994
        }
995
996
        if (! $entry) {
997
            // Play limit reached
998
            if ($this->hasReachedPlayLimit($game, $user)) {
999
                $error = -1;
1000
                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...
1001
            }
1002
            // Can't pay for the game
1003
            if (!$this->canPayToPlay($game, $user)) {
1004
                $error = -3;
1005
                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...
1006
            }
1007
            // Terms optin not checked
1008
            if ($game->getTermsOptin()) {
1009
                $error = -2;
1010
                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...
1011
            }
1012
1013
            $ip = $this->getIp();
1014
            $geoloc = $this->getGeoloc($ip);
1015
            $entry = new Entry();
1016
            $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...
1017
            $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...
1018
            $entry->setPoints(0);
1019
            $entry->setIp($ip);
1020
            $entry->setGeoloc($geoloc);
0 ignored issues
show
Documentation introduced by
$geoloc is of type string, but the function expects a object<PlaygroundGame\Entity\field_type>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1021
            $entry->setAnonymousId($this->getAnonymousId());
1022
            
1023
            if ($this->getAnonymousIdentifier()) {
1024
                $entry->setAnonymousIdentifier($this->getAnonymousIdentifier());
1025
            }
1026
            if ($game->getCostToPlay() === 0) {
1027
                $entry->setPaid(true);
1028
                $entry = $this->getEntryMapper()->insert($entry);
1029
                $this->getEventManager()->trigger(
1030
                    __FUNCTION__ . '.post',
1031
                    $this,
1032
                    [
1033
                        'user' => $user,
1034
                        'game' => $game,
1035
                        'entry' => $entry,
1036
                    ]
1037
                );
1038
            } else {
1039
                $entry = $this->getEntryMapper()->insert($entry);
1040
                $entryPaid = $this->payToPlay($game, $user, $entry);
1041
                if ($entryPaid) {
1042
                    $entry = $this->getEntryMapper()->update($entryPaid);
1043
                    $this->getEventManager()->trigger(
1044
                        __FUNCTION__ . '.post',
1045
                        $this,
1046
                        [
1047
                            'user' => $user,
1048
                            'game' => $game,
1049
                            'entry' => $entry,
1050
                        ]
1051
                    );
1052
                } else {
1053
                    $entry->setActive(false);
1054
                    $entry = $this->getEntryMapper()->update($entry);
0 ignored issues
show
Unused Code introduced by
$entry 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...
1055
                    $error = -3;
1056
                    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...
1057
                }
1058
            }
1059
        }
1060
1061
        return $entry;
1062
    }
1063
1064
    /**
1065
     * @param \PlaygroundGame\Entity\Game $game
1066
     * @param \PlaygroundUser\Entity\UserInterface $user
1067
     */
1068
    public function hasReachedPlayLimit($game, $user)
1069
    {
1070
        // Is there a limitation on the game ?
1071
        $limitAmount = $game->getPlayLimit();
1072
        if ($limitAmount) {
1073
            $limitScale = $game->getPlayLimitScale();
1074
            $userEntries = $this->findLastEntries($game, $user, $limitScale);
1075
1076
            // player has reached the game limit
1077
            if ($userEntries >= $limitAmount) {
1078
                return true;
1079
            }
1080
        }
1081
        return false;
1082
    }
1083
1084
    /**
1085
     * If the game has a cost to be played (costToPlay>0)
1086
     * I check and decrement the price from the leaderboard all of the user
1087
     * 
1088
     * @param \PlaygroundGame\Entity\Game $game
1089
     * @param \PlaygroundUser\Entity\UserInterface $user
1090
     */
1091
    public function canPayToPlay($game, $user)
1092
    {
1093
        // Is there a limitation on the game ?
1094
        $cost = $game->getCostToPlay();
1095
        if ($cost && $cost > 0) {
1096
            $availableAmount = $this->getEventManager()->trigger(
1097
                'leaderboardUserTotal',
1098
                $this,
1099
                [
1100
                    'user' => $user,
1101
                ]
1102
            )->last();
1103
            if ($availableAmount && $availableAmount >= $cost) {
1104
                
1105
                return true;
1106
            }
1107
        } else {
1108
            return true;
1109
        }
1110
1111
        return false;
1112
    }
1113
1114
    /**
1115
     * If the game has a cost to be played (costToPlay>0)
1116
     * I check and decrement the price from the leaderboard all of the user
1117
     * 
1118
     * @param \PlaygroundGame\Entity\Game $game
1119
     * @param \PlaygroundUser\Entity\UserInterface $user
1120
     */
1121
    public function payToPlay($game, $user, $entry)
1122
    {
1123
        // Is there a limitation on the game ?
1124
        $cost = $game->getCostToPlay();
1125
        if ($cost && $cost > 0) {
1126
            if ($this->canPayToPlay($game, $user)) {
1127
                $entry->setPaid(true);
1128
                $entry->setPaidAmount(-$cost);
1129
                $leaderboard = $this->getEventManager()->trigger(
0 ignored issues
show
Unused Code introduced by
$leaderboard 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...
1130
                    'leaderboardUserUpdate',
1131
                    $this,
1132
                    [
1133
                        'user' => $user,
1134
                        'game' => $game,
1135
                        'points' => -$cost,
1136
                        'entry' => $entry,
1137
                    ]
1138
                )->last();
1139
1140
                return $entry;
1141
            }
1142
        } else {
1143
            $entry->setPaid(true);
1144
            return $entry;
1145
        }
1146
1147
        return false;
1148
    }
1149
    
1150
    /**
1151
     * @param \PlaygroundGame\Entity\Game $game
1152
     * @param \PlaygroundUser\Entity\UserInterface $user
1153
     */
1154
    public function findLastEntries($game, $user, $limitScale)
1155
    {
1156
        $limitDate = $this->getLimitDate($limitScale);
1157
1158
        if ($user) {
1159
            return $this->getEntryMapper()->countLastEntriesByUser($game, $user, $limitDate);
1160
        } elseif ($this->getAnonymousIdentifier()) {
1161
            $entries = $this->getEntryMapper()->countLastEntriesByAnonymousIdentifier(
1162
                $game,
1163
                $this->getAnonymousIdentifier(),
1164
                $limitDate
1165
            );
1166
1167
            return $entries;
1168 View Code Duplication
        } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
1169
            // If the game is supposed to be a reguler user game or an anonymous identified game,
1170
            // it means that the registration/login is at the end of the game
1171
            if((!$user &&  !$game->getAnonymousAllowed()) || ($game->getAnonymousAllowed() && $game->getAnonymousIdentifier())) {
1172
                return 0;
1173
            }
1174
            return $this->getEntryMapper()->countLastEntriesByIp($game, $this->getIp(), $limitDate);
1175
        }
1176
    }
1177
1178
    /**
1179
    *
1180
    *
1181
    */
1182
    public function getLimitDate($limitScale)
1183
    {
1184
        $now = new \DateTime("now");
1185
        switch ($limitScale) {
1186
            case 'always':
1187
                $interval = 'P100Y';
1188
                $now->sub(new \DateInterval($interval));
1189
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
1190
                break;
1191
            case 'day':
1192
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
1193
                break;
1194 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...
1195
                $interval = 'P7D';
1196
                $now->sub(new \DateInterval($interval));
1197
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
1198
                break;
1199 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...
1200
                $interval = 'P1M';
1201
                $now->sub(new \DateInterval($interval));
1202
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
1203
                break;
1204 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...
1205
                $interval = 'P1Y';
1206
                $now->sub(new \DateInterval($interval));
1207
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
1208
                break;
1209 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...
1210
                $interval = 'P100Y';
1211
                $now->sub(new \DateInterval($interval));
1212
                $dateLimit = $now->format('Y-m-d') . ' 0:0:0';
1213
        }
1214
1215
        return $dateLimit;
1216
    }
1217
1218
    public function findLastActiveEntry($game, $user)
1219
    {
1220
        return $this->checkExistingEntry($game, $user, true);
1221
    }
1222
1223
    public function findLastInactiveEntry($game, $user)
1224
    {
1225
        return $this->checkExistingEntry($game, $user, false, false);
1226
    }
1227
1228
    public function findLastEntry($game, $user)
1229
    {
1230
        return $this->checkExistingEntry($game, $user, null, false);
1231
    }
1232
1233
    public function inviteToTeam($data, $game, $user)
1234
    {
1235
        $mailService = $this->serviceLocator->get('playgroundgame_message');
1236
        $invitationMapper = $this->serviceLocator->get('playgroundgame_invitation_mapper');
1237
1238
        $sentInvitations = $invitationMapper->findBy(array('host' => $user, 'game' => $game));
1239
        $nbInvitations = count($sentInvitations);
1240
        $to = $data['email'];
1241
        if (empty($to)) {
1242
            return ['result'=>false, 'message'=>'no email'];
1243
        }
1244
1245
        if ($nbInvitations < 20) {
1246
            $alreadyInvited = $invitationMapper->findBy(array('requestKey' => $to, 'game' => $game));
1247
            if (!$alreadyInvited) {
1248
                $alreadyInvited = $this->getUserMapper()->findByEmail($to);
1249
            }
1250
1251
            if (empty($alreadyInvited)) {
1252
                $invitation = new \PlaygroundGame\Entity\Invitation();
1253
                $invitation->setRequestKey($to);
1254
                $invitation->setGame($game);
1255
                $invitation->setHost($user);
1256
                $invitationMapper->insert($invitation);
1257
1258
                $from = $this->getOptions()->getEmailFromAddress();
1259
                $subject = $this->serviceLocator->get('MvcTranslator')->translate(
1260
                    $this->getOptions()->getInviteToTeamSubjectLine(),
1261
                    'playgroundgame'
1262
                );
1263
                $message = $mailService->createHtmlMessage(
1264
                    $from,
1265
                    $to,
1266
                    $subject,
1267
                    'playground-game/email/invite_team',
1268
                    array(
1269
                        'game' => $game,
1270
                        'user' => $user,
1271
                        'data' => $data,
1272
                        'from' => $from
1273
                    )
1274
                );
1275
                try {
1276
                    $mailService->send($message);
1277
                } 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...
1278
                    return ['result' => true, 'message' => $this->serviceLocator->get('MvcTranslator')->translate(
1279
                        'mail error'
1280
                    )];
1281
                }
1282
1283
                return ['result' => true, 'message' => ''];
1284
            } else {
1285
                return ['result' => false, 'message' => 'already invited'];
1286
            }
1287
        } else {
1288
            return [
1289
                'result' => false,
1290
                'message' => $this->serviceLocator->get('MvcTranslator')->translate(
1291
                    'Too many invitations for this user'
1292
                )
1293
            ];
1294
        }
1295
    }
1296
1297
    public function sendShareMail(
1298
        $data,
1299
        $game,
1300
        $user,
1301
        $entry,
1302
        $template = 'share_game',
1303
        $subject = ''
1304
    ) {
1305
        $mailService = $this->serviceLocator->get('playgroundgame_message');
1306
        $mailSent = false;
1307
        $from = $this->getOptions()->getEmailFromAddress();
1308
1309
        if (empty($subject) && $game) {
1310
            $subject = $game->getEmailShareSubject();
1311
        }
1312
1313
        $message = '';
1314
        if ($game && !empty($game->getEmailShareMessage())) {
1315
            $message = $game->getEmailShareMessage();
1316
        }
1317
1318
        $renderer = $this->serviceLocator->get('Zend\View\Renderer\RendererInterface');
1319
        $skinUrl = $renderer->url(
1320
            'frontend',
1321
            array(),
1322
            array('force_canonical' => true)
1323
        );
1324
        $secretKey = strtoupper(substr(sha1(uniqid('pg_', true) . '####' . time()), 0, 15));
1325
1326
        if (isset($data['email']) && !is_array($data['email'])) {
1327
            $data['email'] = array($data['email']);
1328
        }
1329
        
1330
        foreach ($data['email'] as $to) {
1331
            $mailSent = true;
1332
            if (!empty($to)) {
1333
                $message = $mailService->createHtmlMessage(
1334
                    $from,
1335
                    $to,
1336
                    $subject,
1337
                    'playground-game/email/' . $template,
1338
                    array(
1339
                        'game' => $game,
1340
                        'data' => $data,
1341
                        'from' => $from,
1342
                        'to' => $to,
1343
                        'secretKey' => $secretKey,
1344
                        'skinUrl' => $skinUrl,
1345
                        'message' => $message,
1346
                    )
1347
                );
1348
                try {
1349
                    $mailService->send($message);
1350
                } 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...
1351
                }
1352
                
1353
                if ($entry) {
1354
                    $shares = json_decode($entry->getSocialShares(), true);
1355
                    (!isset($shares['mail']))? $shares['mail'] = 1:$shares['mail'] += 1;
1356
                }
1357
                $this->getEventManager()->trigger(
1358
                    __FUNCTION__ . '.post',
1359
                    $this, array(
1360
                        'user' => $user,
1361
                        'secretKey' => $secretKey,
1362
                        'data' => $data,
1363
                        'game' => $game,
1364
                        'entry' => $entry,
1365
                        'message' => $message,
1366
                        'to' => $to,
1367
                    )
1368
                );
1369
            }
1370
        }
1371
1372
        if ($mailSent) {
1373
            if ($entry) {
1374
                $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...
1375
                $entry->setSocialShares($sharesJson);
1376
                $entry = $this->getEntryMapper()->update($entry);
0 ignored issues
show
Unused Code introduced by
$entry 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...
1377
            }
1378
1379
            return true;
1380
        }
1381
1382
        return false;
1383
    }
1384
1385
    /**
1386
     * @param \PlaygroundGame\Entity\Game $game
1387
     * @param \PlaygroundUser\Entity\User $user
1388
     * @param Entry $entry
1389
     * @param \PlaygroundGame\Entity\Prize $prize
1390
     */
1391
    public function sendResultMail($game, $user, $entry, $template = 'entry', $prize = null)
1392
    {
1393
        $mailService = $this->serviceLocator->get('playgroundgame_message');
1394
        $from = $this->getOptions()->getEmailFromAddress();
1395
        if ($entry->getAnonymousIdentifier()) {
1396
            $to = $entry->getAnonymousIdentifier();
1397
        } elseif ($user) {
1398
            $to = $user->getEmail();
1399
        } else {
1400
            return false;
1401
        }
1402
        $subject = $this->serviceLocator->get('MvcTranslator')->translate(
1403
            $this->getOptions()->getParticipationSubjectLine(),
1404
            'playgroundgame'
1405
        );
1406
        $renderer = $this->serviceLocator->get('Zend\View\Renderer\RendererInterface');
1407
        $skinUrl = $renderer->url(
1408
            'frontend',
1409
            array(),
1410
            array('force_canonical' => true)
1411
        );
1412
        $message = $mailService->createHtmlMessage($from, $to, $subject, 'playground-game/email/' . $template, array(
1413
            'game' => $game,
1414
            'entry' => $entry,
1415
            'skinUrl' => $skinUrl,
1416
            'prize' => $prize
1417
        ));
1418
        $mailService->send($message);
1419
    }
1420
1421
    public function sendGameMail($game, $user, $post, $template = 'postvote')
1422
    {
1423
        $mailService = $this->serviceLocator->get('playgroundgame_message');
1424
        $from = $this->getOptions()->getEmailFromAddress();
1425
        $to = $user->getEmail();
1426
        $subject = $this->serviceLocator->get('MvcTranslator')->translate(
1427
            $this->getOptions()->getParticipationSubjectLine(),
1428
            'playgroundgame'
1429
        );
1430
        $renderer = $this->serviceLocator->get('Zend\View\Renderer\RendererInterface');
1431
        $skinUrl = $renderer->url(
1432
            'frontend',
1433
            array(),
1434
            array('force_canonical' => true)
1435
        );
1436
1437
        $message = $mailService->createHtmlMessage($from, $to, $subject, 'playground-game/email/' . $template, array(
1438
            'game' => $game,
1439
            'post' => $post,
1440
            'skinUrl' => $skinUrl
1441
        ));
1442
        $mailService->send($message);
1443
    }
1444
1445 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...
1446
    {
1447
        $topic = $game->getTitle();
1448
        
1449
        $shares = json_decode($entry->getSocialShares(), true);
1450
        if (!isset($shares['fbwall'])) {
1451
            $shares['fbwall'] = 1;
1452
        } else {
1453
            $shares['fbwall'] += 1;
1454
        }
1455
        $sharesJson = json_encode($shares);
1456
        $entry->setSocialShares($sharesJson);
1457
        $entry = $this->getEntryMapper()->update($entry);
1458
        
1459
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1460
            'user' => $user,
1461
            'game' => $game,
1462
            'secretKey' => $secretKey,
1463
            'topic' => $topic,
1464
            'entry' => $entry
1465
        ));
1466
1467
        return true;
1468
    }
1469
1470
    public function postFbRequest($secretKey, $game, $user, $entry, $to)
1471
    {
1472
        $shares = json_decode($entry->getSocialShares(), true);
1473
        $to = explode(',', $to);
1474
        if (!isset($shares['fbrequest'])) {
1475
            $shares['fbrequest'] = count($to);
1476
        } else {
1477
            $shares['fbrequest'] += count($to);
1478
        }
1479
        $sharesJson = json_encode($shares);
1480
        $entry->setSocialShares($sharesJson);
1481
        $entry = $this->getEntryMapper()->update($entry);
1482
        
1483
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1484
            'user' => $user,
1485
            'game' => $game,
1486
            'secretKey' => $secretKey,
1487
            'entry' => $entry,
1488
            'invites' => count($to)
1489
        ));
1490
1491
        return true;
1492
    }
1493
1494 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...
1495
    {
1496
        $topic = $game->getTitle();
1497
1498
        $shares = json_decode($entry->getSocialShares(), true);
1499
        if (!isset($shares['fbrequest'])) {
1500
            $shares['tweet'] = 1;
1501
        } else {
1502
            $shares['tweet'] += 1;
1503
        }
1504
        $sharesJson = json_encode($shares);
1505
        $entry->setSocialShares($sharesJson);
1506
        $entry = $this->getEntryMapper()->update($entry);
1507
        
1508
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1509
            'user' => $user,
1510
            'game' => $game,
1511
            'secretKey' => $secretKey,
1512
            'topic' => $topic,
1513
            'entry' => $entry
1514
        ));
1515
1516
        return true;
1517
    }
1518
1519 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...
1520
    {
1521
        $topic = $game->getTitle();
1522
        
1523
        $shares = json_decode($entry->getSocialShares(), true);
1524
        if (!isset($shares['fbrequest'])) {
1525
            $shares['google'] = 1;
1526
        } else {
1527
            $shares['google'] += 1;
1528
        }
1529
        $sharesJson = json_encode($shares);
1530
        $entry->setSocialShares($sharesJson);
1531
        $entry = $this->getEntryMapper()->update($entry);
1532
1533
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
1534
            'user' => $user,
1535
            'game' => $game,
1536
            'secretKey' => $secretKey,
1537
            'topic' => $topic,
1538
            'entry' => $entry
1539
        ));
1540
1541
        return true;
1542
    }
1543
1544
    /**
1545
     * Is it possible to trigger a bonus entry ?
1546
     *
1547
     * @param unknown_type $game
1548
     * @param unknown_type $user
1549
     */
1550
    public function allowBonus($game, $user)
1551
    {
1552
        if (! $game->getPlayBonus() || $game->getPlayBonus() == 'none') {
1553
            return false;
1554
        } elseif ($game->getPlayBonus() == 'one') {
1555
            if ($this->getEntryMapper()->findOneBy(array(
1556
                'game' => $game,
1557
                'user' => $user,
1558
                'bonus' => 1
1559
            ))) {
1560
                return false;
1561
            } else {
1562
                return true;
1563
            }
1564
        } elseif ($game->getPlayBonus() == 'per_entry') {
1565
            return $this->getEntryMapper()->checkBonusEntry($game, $user);
1566
        }
1567
1568
        return false;
1569
    }
1570
1571
    public function addAnotherEntry($game, $user, $winner = 0)
1572
    {
1573
        $entry = new Entry();
1574
        $entry->setGame($game);
1575
        $entry->setUser($user);
1576
        $entry->setPoints(0);
1577
        $entry->setIp($this->getIp());
1578
        $entry->setActive(0);
0 ignored issues
show
Documentation introduced by
0 is of type integer, but the function expects a boolean.

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...
1579
        $entry->setBonus(1);
1580
        $entry->setWinner($winner);
1581
        $entry = $this->getEntryMapper()->insert($entry);
1582
1583
        return $entry;
1584
    }
1585
1586
    /**
1587
     * This bonus entry doesn't give points nor badges
1588
     * It's just there to increase the chances during the Draw
1589
     * Old Name playBonus
1590
     *
1591
     * @param PlaygroundGame\Entity\Game $game
1592
     * @param unknown $user
1593
     * @return boolean unknown
1594
     */
1595
    public function addAnotherChance($game, $user, $winner = 0)
1596
    {
1597
        if ($this->allowBonus($game, $user)) {
1598
            $this->addAnotherEntry($game, $user, $winner);
1599
1600
            return true;
1601
        }
1602
1603
        return false;
1604
    }
1605
1606
    /**
1607
     * This bonus entry doesn't give points nor badges but can play again
1608
     *
1609
     * @param PlaygroundGame\Entity\Game $game
1610
     * @param user $user
1611
     * @return boolean unknown
1612
     */
1613
    public function playAgain($game, $user, $winner = 0)
1614
    {
1615
        if ($this->allowBonus($game, $user)) {
1616
            $entry = $this->addAnotherEntry($game, $user, $winner);
1617
            $entry->setActive(1);
1618
            $entry = $this->getEntryMapper()->update($entry);
1619
            if ($entry->getActive() == 1) {
1620
                return true;
1621
            }
1622
        }
1623
1624
        return false;
1625
    }
1626
1627
    /**
1628
     * @param string $path
1629
     * @param boolean $noReplace : If the image name already exist, don't replace it but change the name
1630
     */
1631
    public function uploadFile($path, $file, $noReplace = true)
1632
    {
1633
        $err = $file["error"];
1634
        $message = '';
1635
        if ($err > 0) {
1636
            switch ($err) {
1637
                case '1':
1638
                    $message .= 'Max file size exceeded. (php.ini)';
1639
                    break;
1640
                case '2':
1641
                    $message .= 'Max file size exceeded.';
1642
                    break;
1643
                case '3':
1644
                    $message .= 'File upload was only partial.';
1645
                    break;
1646
                case '4':
1647
                    $message .= 'No file was attached.';
1648
                    break;
1649
                case '7':
1650
                    $message .= 'File permission denied.';
1651
                    break;
1652
                default:
1653
                    $message .= 'Unexpected error occurs.';
1654
            }
1655
1656
            return $err;
1657
        } else {
1658
            $fileNewname = $this->fileNewname($path, $file['name'], $noReplace);
1659
1660
            if (isset($file["base64"])) {
1661
                list(, $img) = explode(',', $file["base64"]);
1662
                $img = str_replace(' ', '+', $img);
1663
                $im = base64_decode($img);
1664
                if ($im !== false) {
1665
                    // getimagesizefromstring
1666
                    file_put_contents($path . $fileNewname, $im);
1667
                } else {
1668
                    return 1;
1669
                }
1670
1671
                return $fileNewname;
1672
            } else {
1673
                $adapter = new \Zend\File\Transfer\Adapter\Http();
1674
                // 1Mo
1675
                $size = new Size(array(
1676
                    'max' => 1024000
1677
                ));
1678
                $is_image = new IsImage('jpeg,png,gif,jpg');
1679
                $adapter->setValidators(array(
1680
                    $size,
1681
                    $is_image
1682
                ), $fileNewname);
1683
1684
                if (! $adapter->isValid()) {
1685
                    return false;
1686
                }
1687
1688
                @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...
1689
            }
1690
1691
            
1692
            if (class_exists("Imagick")) {
1693
                $ext = pathinfo($fileNewname, PATHINFO_EXTENSION);
1694
                $img = new \Imagick($path . $fileNewname);
1695
                $img->cropThumbnailImage(100, 100);
1696
                $img->setImageCompression(\Imagick::COMPRESSION_JPEG);
1697
                $img->setImageCompressionQuality(75);
1698
                // Strip out unneeded meta data
1699
                $img->stripImage();
1700
                $img->writeImage($path . str_replace('.'.$ext, '-thumbnail.'.$ext, $fileNewname));
1701
                ErrorHandler::stop(true);
1702
            }
1703
        }
1704
1705
        return $fileNewname;
1706
    }
1707
1708
    /**
1709
     * @param string $path
1710
     */
1711
    public function fileNewname($path, $filename, $generate = false)
1712
    {
1713
        $sanitize = new Sanitize();
1714
        $name = $sanitize->filter($filename);
1715
        $newpath = $path . $name;
1716
1717
        if ($generate) {
1718
            if (file_exists($newpath)) {
1719
                $filename = pathinfo($name, PATHINFO_FILENAME);
1720
                $ext = pathinfo($name, PATHINFO_EXTENSION);
1721
1722
                $name = $filename . '_' . rand(0, 99) . '.' . $ext;
1723
            }
1724
        }
1725
1726
        unset($sanitize);
1727
1728
        return $name;
1729
    }
1730
1731
    /**
1732
     * This function returns the list of games, ordered by $type
1733
     */
1734
    public function getQueryGamesOrderBy($type = 'createdAt', $order = 'DESC')
1735
    {
1736
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
1737
        $today = new \DateTime("now");
1738
        $today = $today->format('Y-m-d H:i:s');
1739
1740
        $onlineGames = '(
1741
            (
1742
                CASE WHEN (
1743
                    g.active = 1
1744
                    AND g.broadcastPlatform = 1
1745
                    AND (g.startDate <= :date OR g.startDate IS NULL)
1746
                    AND (g.closeDate >= :date OR g.closeDate IS NULL)
1747
                ) THEN 1 ELSE 0 END
1748
            ) +
1749
            (
1750
                CASE WHEN (
1751
                    g.active = 0
1752
                    AND (g.broadcastPlatform = 0 OR g.broadcastPlatform IS NULL)
1753
                    AND g.startDate > :date
1754
                    AND g.closeDate < :date
1755
                ) THEN 1 ELSE 0 END
1756
            )
1757
        )';
1758
1759
        $qb = $em->createQueryBuilder();
1760
        $qb->select('g')->from('PlaygroundGame\Entity\Game', 'g');
1761
        
1762
        switch ($type) {
1763
            case 'startDate':
1764
                $qb->orderBy('g.startDate', $order);
1765
                break;
1766
            case 'activeGames':
1767
                $qb->orderBy('g.active', $order);
1768
                break;
1769
            case 'onlineGames':
1770
                $qb->orderBy($onlineGames, $order);
1771
                $qb->setParameter('date', $today);
1772
                break;
1773
            case 'createdAt':
1774
                $qb->orderBy('g.createdAt', $order);
1775
                break;
1776
        }
1777
1778
        $query = $qb->getQuery();
1779
1780
        return $query;
1781
    }
1782
1783
    public function draw($game)
1784
    {
1785
        $total = $game->getWinners();
1786
1787
        // I Have to know what is the User Class used
1788
        $zfcUserOptions = $this->serviceLocator->get('zfcuser_module_options');
1789
        $userClass = $zfcUserOptions->getUserEntityClass();
1790
1791
        $result = $this->getEntryMapper()->draw($game, $userClass, $total);
1792
1793
        foreach ($result as $e) {
1794
            $e->setWinner(1);
1795
            $e = $this->getEntryMapper()->update($e);
1796
            $this->getEventManager()->trigger('win_lottery.post', $this, array(
1797
                'user' => $e->getUser(),
1798
                'game' => $game,
1799
                'entry' => $e
1800
            ));
1801
        }
1802
1803
        return $result;
1804
    }
1805
1806
    /**
1807
     * getGameMapper
1808
     *
1809
     * @return GameMapperInterface
1810
     */
1811 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...
1812
    {
1813
        if (null === $this->gameMapper) {
1814
            $this->gameMapper = $this->serviceLocator->get('playgroundgame_game_mapper');
1815
        }
1816
1817
        return $this->gameMapper;
1818
    }
1819
1820
    /**
1821
     * setGameMapper
1822
     *
1823
     * @param GameMapperInterface $gameMapper
1824
     * @return Game
1825
     */
1826
    public function setGameMapper(GameMapperInterface $gameMapper)
1827
    {
1828
        $this->gameMapper = $gameMapper;
1829
1830
        return $this;
1831
    }
1832
1833
    /**
1834
     * getEntryMapper
1835
     *
1836
     * @return EntryMapperInterface
1837
     */
1838
    public function getEntryMapper()
1839
    {
1840
        if (null === $this->entryMapper) {
1841
            $this->entryMapper = $this->serviceLocator->get('playgroundgame_entry_mapper');
1842
        }
1843
1844
        return $this->entryMapper;
1845
    }
1846
1847
    /**
1848
     * setEntryMapper
1849
     *
1850
     * @param EntryMapperInterface $entryMapper
1851
     * @return Game
1852
     */
1853
    public function setEntryMapper($entryMapper)
1854
    {
1855
        $this->entryMapper = $entryMapper;
1856
1857
        return $this;
1858
    }
1859
1860
    public function setOptions(ModuleOptions $options)
1861
    {
1862
        $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...
1863
1864
        return $this;
1865
    }
1866
1867
    public function getOptions()
1868
    {
1869
        if (! $this->options instanceof ModuleOptions) {
1870
            $this->setOptions($this->serviceLocator
1871
                ->get('playgroundgame_module_options'));
1872
        }
1873
1874
        return $this->options;
1875
    }
1876
1877
    /**
1878
     * @param string $str
1879
     */
1880
    public function getExtension($str)
1881
    {
1882
        $i = strrpos($str, '.');
1883
1884
        $l = strlen($str) - $i;
1885
        $ext = substr($str, $i + 1, $l);
1886
1887
        return $ext;
1888
    }
1889
1890
    /**
1891
     * @param string $extension
1892
     */
1893
    public function getSrc($extension, $temp_path)
1894
    {
1895
        $image_src = '';
1896
        switch ($extension) {
1897
            case 'jpg':
1898
                $image_src = imagecreatefromjpeg($temp_path);
1899
                break;
1900
            case 'jpeg':
1901
                $image_src = imagecreatefromjpeg($temp_path);
1902
                break;
1903
            case 'png':
1904
                $image_src = imagecreatefrompng($temp_path);
1905
                break;
1906
            case 'gif':
1907
                $image_src = imagecreatefromgif($temp_path);
1908
                break;
1909
        }
1910
1911
        return $image_src;
1912
    }
1913
1914
    /**
1915
     * @param string $extension
1916
     * @param string $rep
1917
     * @param integer $mini_width
1918
     * @param integer $mini_height
1919
     */
1920
    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...
1921
    {
1922
        list($src_width, $src_height) = getimagesize($tmp_file);
1923
1924
        $ratio_src = $src_width / $src_height;
1925
        $ratio_mini = $mini_width / $mini_height;
1926
1927
        if ($ratio_src >= $ratio_mini) {
1928
            $new_height_mini = $mini_height;
1929
            $new_width_mini = $src_width / ($src_height / $mini_height);
1930
        } else {
1931
            $new_width_mini = $mini_width;
1932
            $new_height_mini = $src_height / ($src_width / $mini_width);
1933
        }
1934
1935
        $new_image_mini = imagecreatetruecolor($mini_width, $mini_height);
1936
1937
        imagecopyresampled(
1938
            $new_image_mini,
1939
            $src,
1940
            0 - ($new_width_mini - $mini_width) / 2,
1941
            0 - ($new_height_mini - $mini_height) / 2,
1942
            0,
1943
            0,
1944
            $new_width_mini,
1945
            $new_height_mini,
1946
            $src_width,
1947
            $src_height
1948
        );
1949
        imagejpeg($new_image_mini, $rep);
1950
1951
        imagedestroy($new_image_mini);
1952
    }
1953
1954
    public function getGameEntity()
1955
    {
1956
        return new \PlaygroundGame\Entity\Game();
1957
    }
1958
1959
    /**
1960
     * @param string $resource
1961
     * @param string $privilege
1962
     */
1963
    public function isAllowed($resource, $privilege = null)
1964
    {
1965
        $auth = $this->serviceLocator->get('BjyAuthorize\Service\Authorize');
1966
1967
        return $auth->isAllowed($resource, $privilege);
1968
    }
1969
1970
    public function getIp()
1971
    {
1972
        $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...
1973
        if (isset($_SERVER['HTTP_CLIENT_IP'])) {
1974
            $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
1975
        } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1976
            $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
1977
        } elseif (isset($_SERVER['HTTP_X_FORWARDED'])) {
1978
            $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
1979
        } elseif (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
1980
            $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
1981
        } elseif (isset($_SERVER['HTTP_FORWARDED'])) {
1982
            $ipaddress = $_SERVER['HTTP_FORWARDED'];
1983
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
1984
            $ipaddress = $_SERVER['REMOTE_ADDR'];
1985
        } else {
1986
            $ipaddress = 'UNKNOWN';
1987
        }
1988
1989
        return $ipaddress;
1990
    }
1991
1992
    public function getGeoloc($ip)
1993
    {
1994
        $geoloc = '';
1995
        try {
1996
            $res = unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip='.$ip));
1997
            if($res['geoplugin_latitude'] != '') {
1998
                $geoloc = $res['geoplugin_latitude'] . ',' . $res['geoplugin_longitude'];
1999
            }
2000
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
2001
2002
        } 
2003
2004
        return $geoloc;
2005
    }
2006
2007
    public function getAnonymousId()
2008
    {
2009
        $anonymousId = '';
2010
        if ($_COOKIE && array_key_exists('pg_anonymous', $_COOKIE)) {
2011
            $anonymousId = $_COOKIE['pg_anonymous'];
2012
        }
2013
2014
        return $anonymousId;
2015
    }
2016
2017
    /**
2018
     *
2019
     *
2020
     * This service is ready for all types of games
2021
     *
2022
     * @param array $data
2023
     * @return \PlaygroundGame\Entity\Game
2024
     */
2025 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...
2026
    {
2027
        $title = '';
2028
        $description = '';
2029
2030
        if ($data['form_jsonified']) {
2031
            $jsonPV = json_decode($data['form_jsonified']);
2032
            foreach ($jsonPV as $element) {
2033
                if ($element->form_properties) {
2034
                    $attributes = $element->form_properties[0];
2035
                    $title = $attributes->title;
2036
                    $description = $attributes->description;
2037
2038
                    break;
2039
                }
2040
            }
2041
        }
2042
        if (! $form) {
2043
            $form = new \PlaygroundGame\Entity\PlayerForm();
2044
        }
2045
        $form->setGame($game);
2046
        $form->setTitle($title);
2047
        $form->setDescription($description);
2048
        $form->setForm($data['form_jsonified']);
2049
        $form->setFormTemplate($data['form_template']);
2050
2051
        $form = $this->getPlayerFormMapper()->insert($form);
2052
2053
        return $form;
2054
    }
2055
2056
    /**
2057
     *  getCSV creates lines of CSV and returns it.
2058
     */
2059
    public function getCSV($array)
2060
    {
2061
        ob_start(); // buffer the output ...
2062
        $out = fopen('php://output', 'w');
2063
        fputcsv($out, array_keys($array[0]), ";");
2064
        foreach ($array as $line) {
2065
            fputcsv($out, $line, ";");
2066
        }
2067
        fclose($out);
2068
        return ob_get_clean(); // ... then return it as a string!
2069
    }
2070
    
2071
    public function getAttributes($attributes)
2072
    {
2073
        $a = array();
2074
2075
        $a['name']          = isset($attributes->name)? $attributes->name : '';
2076
        $a['placeholder']   = isset($attributes->data->placeholder)? $attributes->data->placeholder : '';
2077
        $a['label']         = isset($attributes->data->label)? $attributes->data->label : '';
2078
        $a['required']      = (isset($attributes->data->required) && $attributes->data->required == 'true')?
2079
            true:
2080
            false;
2081
        $a['class']         = isset($attributes->data->class)? $attributes->data->class : '';
2082
        $a['id']            = isset($attributes->data->id)? $attributes->data->id : '';
2083
        $a['lengthMin']     = isset($attributes->data->length)? $attributes->data->length->min : '';
2084
        $a['lengthMax']     = isset($attributes->data->length)? $attributes->data->length->max : '';
2085
        $a['validator']     = isset($attributes->data->validator)? $attributes->data->validator : '';
2086
        $a['innerData']     = isset($attributes->data->innerData)? $attributes->data->innerData : array();
2087
        $a['dropdownValues']= isset($attributes->data->dropdownValues)?
2088
            $attributes->data->dropdownValues :
2089
            array();
2090
        $a['filesizeMin']   = isset($attributes->data->filesize)? $attributes->data->filesize->min : 0;
2091
        $a['filesizeMax']   = isset($attributes->data->filesize)? $attributes->data->filesize->max : 10*1024*1024;
2092
        $a['fileextension']   = isset($attributes->data->fileextension)?
2093
            str_replace(', ', ',', $attributes->data->fileextension) :
2094
            'png,jpg,jpeg,gif';
2095
2096
        // hiddenRequired('fileexcludeextension', '').appendTo(li);
2097
        // hiddenRequired('filemimetype', '').appendTo(li);
2098
        // hiddenRequired('fileexcludemimetype', '').appendTo(li);
2099
        // hiddenRequired('fileexists', '').appendTo(li);
2100
        // hiddenRequired('fileimagesize_minheight', '').appendTo(li);
2101
        // hiddenRequired('fileimagesize_maxheight', '').appendTo(li);
2102
        // hiddenRequired('fileimagesize_minwidth', '').appendTo(li);
2103
        // hiddenRequired('fileimagesize_maxwidth', '').appendTo(li);
2104
        // hiddenRequired('fileiscompressed', '').appendTo(li);
2105
        // hiddenRequired('fileisimage', '').appendTo(li);
2106
        // hiddenRequired('filewordcount_min', '').appendTo(li);
2107
        // hiddenRequired('filewordcount_max', '').appendTo(li);
2108
2109
        return $a;
2110
    }
2111
2112
    /**
2113
     * @param \Zend\InputFilter\InputFilter $inputFilter
2114
     */
2115
    public function decorate($element, $attr, $inputFilter)
2116
    {
2117
        $factory = new InputFactory();
2118
        $element->setAttributes(
2119
            array(
2120
                'placeholder'   => $attr['placeholder'],
2121
                'required'      => $attr['required'],
2122
                'class'         => $attr['class'],
2123
                'id'            => $attr['id']
2124
            )
2125
        );
2126
2127
        $options = array();
2128
        $options['encoding'] = 'UTF-8';
2129
        if ($attr['lengthMin'] && $attr['lengthMin'] > 0) {
2130
            $options['min'] = $attr['lengthMin'];
2131
        }
2132
        if ($attr['lengthMax'] && $attr['lengthMax'] > $attr['lengthMin']) {
2133
            $options['max'] = $attr['lengthMax'];
2134
            $element->setAttribute('maxlength', $attr['lengthMax']);
2135
            $options['messages'] = array(
2136
                \Zend\Validator\StringLength::TOO_LONG => sprintf(
2137
                    $this->serviceLocator->get('MvcTranslator')->translate(
2138
                        'This field contains more than %s characters',
2139
                        'playgroundgame'
2140
                    ),
2141
                    $attr['lengthMax']
2142
                )
2143
            );
2144
        }
2145
2146
        $validators = array(
2147
            array(
2148
                'name'    => 'StringLength',
2149
                'options' => $options,
2150
            ),
2151
        );
2152
        if ($attr['validator']) {
2153
            $regex = "/.*\(([^)]*)\)/";
2154
            preg_match($regex, $attr['validator'], $matches);
2155
            $valArray = array(
2156
                'name' => str_replace(
2157
                    '('.$matches[1].')',
2158
                    '',
2159
                    $attr['validator']
2160
                ),
2161
                'options' => array($matches[1])
2162
            );
2163
            $validators[] = $valArray;
2164
        }
2165
2166
        $inputFilter->add($factory->createInput(array(
2167
            'name'     => $attr['name'],
2168
            'required' => $attr['required'],
2169
            'filters'  => array(
2170
                array('name' => 'StripTags'),
2171
                array('name' => 'StringTrim'),
2172
            ),
2173
            'validators' => $validators,
2174
        )));
2175
2176
        return $element;
2177
    }
2178
    /**
2179
     * Create a ZF2 Form from json data
2180
     * @return Form
2181
     */
2182
    public function createFormFromJson($jsonForm, $id = 'jsonForm')
2183
    {
2184
        $formPV = json_decode($jsonForm);
2185
        
2186
        $form = new Form();
2187
        $form->setAttribute('id', $id);
2188
        $form->setAttribute('enctype', 'multipart/form-data');
2189
        
2190
        $inputFilter = new \Zend\InputFilter\InputFilter();
2191
        $factory = new InputFactory();
2192
        
2193
        foreach ($formPV as $element) {
2194 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...
2195
                $attr  = $this->getAttributes($element->line_text[0]);
2196
                $element = new Element\Text($attr['name']);
2197
                $element = $this->decorate($element, $attr, $inputFilter);
2198
                $form->add($element);
2199
            }
2200 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...
2201
                $attr = $this->getAttributes($element->line_password[0]);
2202
                $element = new Element\Password($attr['name']);
2203
                $element = $this->decorate($element, $attr, $inputFilter);
2204
                $form->add($element);
2205
            }
2206 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...
2207
                $attr = $this->getAttributes($element->line_hidden[0]);
2208
                $element = new Element\Hidden($attr['name']);
2209
                $element = $this->decorate($element, $attr, $inputFilter);
2210
                $form->add($element);
2211
            }
2212 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...
2213
                $attr = $this->getAttributes($element->line_email[0]);
2214
                $element = new Element\Email($attr['name']);
2215
                $element = $this->decorate($element, $attr, $inputFilter);
2216
                $form->add($element);
2217
            }
2218 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...
2219
                $attr = $this->getAttributes($element->line_radio[0]);
2220
                $element = new Element\Radio($attr['name']);
2221
2222
                $element->setLabel($attr['label']);
2223
                $element->setAttributes(
2224
                    array(
2225
                        'name'      => $attr['name'],
2226
                        'required'  => $attr['required'],
2227
                        'allowEmpty'=> !$attr['required'],
2228
                        'class'     => $attr['class'],
2229
                        'id'        => $attr['id']
2230
                    )
2231
                );
2232
                $values = array();
2233
                foreach ($attr['innerData'] as $value) {
2234
                    $values[] = $value->label;
2235
                }
2236
                $element->setValueOptions($values);
2237
        
2238
                $options = array();
2239
                $options['encoding'] = 'UTF-8';
2240
                $options['disable_inarray_validator'] = true;
2241
        
2242
                $element->setOptions($options);
2243
        
2244
                $form->add($element);
2245
        
2246
                $inputFilter->add($factory->createInput(array(
2247
                    'name'     => $attr['name'],
2248
                    'required' => $attr['required'],
2249
                    'allowEmpty' => !$attr['required'],
2250
                )));
2251
            }
2252 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...
2253
                $attr = $this->getAttributes($element->line_checkbox[0]);
2254
                $element = new Element\MultiCheckbox($attr['name']);
2255
        
2256
                $element->setLabel($attr['label']);
2257
                $element->setAttributes(
2258
                    array(
2259
                        'name'      => $attr['name'],
2260
                        'required'  => $attr['required'],
2261
                        'allowEmpty'=> !$attr['required'],
2262
                        'class'     => $attr['class'],
2263
                        'id'        => $attr['id']
2264
                    )
2265
                );
2266
2267
                $values = array();
2268
                foreach ($attr['innerData'] as $value) {
2269
                    $values[] = $value->label;
2270
                }
2271
                $element->setValueOptions($values);
2272
                $form->add($element);
2273
        
2274
                $options = array();
2275
                $options['encoding'] = 'UTF-8';
2276
                $options['disable_inarray_validator'] = true;
2277
        
2278
                $element->setOptions($options);
2279
        
2280
                $inputFilter->add($factory->createInput(array(
2281
                    'name'      => $attr['name'],
2282
                    'required'  => $attr['required'],
2283
                    'allowEmpty'=> !$attr['required'],
2284
                )));
2285
            }
2286 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...
2287
                $attr = $this->getAttributes($element->line_dropdown[0]);
2288
                $element = new Element\Select($attr['name']);
2289
2290
                $element->setLabel($attr['label']);
2291
                $element->setAttributes(
2292
                    array(
2293
                        'name'      => $attr['name'],
2294
                        'required'  => $attr['required'],
2295
                        'allowEmpty'=> !$attr['required'],
2296
                        'class'     => $attr['class'],
2297
                        'id'        => $attr['id']
2298
                    )
2299
                );
2300
                $values = array();
2301
                foreach ($attr['dropdownValues'] as $value) {
2302
                    $values[] = $value->dropdown_label;
2303
                }
2304
                $element->setValueOptions($values);
2305
                $form->add($element);
2306
        
2307
                $options = array();
2308
                $options['encoding'] = 'UTF-8';
2309
                $options['disable_inarray_validator'] = true;
2310
        
2311
                $element->setOptions($options);
2312
        
2313
                $inputFilter->add($factory->createInput(array(
2314
                    'name'     => $attr['name'],
2315
                    'required' => $attr['required'],
2316
                    'allowEmpty' => !$attr['required'],
2317
                )));
2318
            }
2319 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...
2320
                $attr = $this->getAttributes($element->line_paragraph[0]);
2321
                $element = new Element\Textarea($attr['name']);
2322
                $element = $this->decorate($element, $attr, $inputFilter);
2323
                $form->add($element);
2324
            }
2325
            if (isset($element->line_upload)) {
2326
                $attr = $this->getAttributes($element->line_upload[0]);
2327
                $element = new Element\File($attr['name']);
2328
2329
                $element->setLabel($attr['label']);
2330
                $element->setAttributes(
2331
                    array(
2332
                        'name'      => $attr['name'],
2333
                        'required'  => $attr['required'],
2334
                        'class'     => $attr['class'],
2335
                        'id'        => $attr['id']
2336
                    )
2337
                );
2338
                $form->add($element);
2339
2340
                $inputFilter->add($factory->createInput(array(
2341
                    'name'     => $attr['name'],
2342
                    'required' => $attr['required'],
2343
                    'validators' => array(
2344
                        array(
2345
                            'name' => '\Zend\Validator\File\Size',
2346
                            'options' => array('min' => $attr['filesizeMin'], 'max' => $attr['filesizeMax'])
2347
                        ),
2348
                        array(
2349
                            'name' => '\Zend\Validator\File\Extension',
2350
                            'options'  => array(
2351
                                $attr['fileextension'],
2352
                                'messages' => array(
2353
                                    \Zend\Validator\File\Extension::FALSE_EXTENSION =>'Veuillez télécharger un fichier avec la bonne extension'
2354
                                )
2355
                            )
2356
                        ),
2357
                    ),
2358
                )));
2359
            }
2360
        }
2361
        
2362
        $form->setInputFilter($inputFilter);
2363
        
2364
        return $form;
2365
    }
2366
2367
    /**
2368
     * Send mail for winner and/or loser
2369
     * @param \PlaygroundGame\Entity\Game $game
2370
     * @param \PlaygroundUser\Entity\User $user
2371
     * @param \PlaygroundGame\Entity\Entry $lastEntry
2372
     * @param \PlaygroundGame\Entity\Prize $prize
2373
     */
2374
    public function sendMail($game, $user, $lastEntry, $prize = null)
2375
    {
2376 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...
2377
            $game->getMailWinner() &&
2378
            $lastEntry->getWinner()
2379
        ) {
2380
            $this->sendResultMail($game, $user, $lastEntry, 'winner', $prize);
2381
        }
2382
2383 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...
2384
            $game->getMailLooser() &&
2385
            !$lastEntry->getWinner()
2386
        ) {
2387
            $this->sendResultMail($game, $user, $lastEntry, 'looser');
2388
        }
2389
2390
        if (($user || ($game->getAnonymousAllowed() && $game->getAnonymousIdentifier())) &&
2391
            $game->getMailEntry()
2392
        ) {
2393
            $this->sendResultMail($game, $user, $lastEntry);
2394
        }
2395
    }
2396
2397
    public function getPlayerFormMapper()
2398
    {
2399
        if (null === $this->playerformMapper) {
2400
            $this->playerformMapper = $this->serviceLocator->get('playgroundgame_playerform_mapper');
2401
        }
2402
2403
        return $this->playerformMapper;
2404
    }
2405
2406
    public function setPlayerFormMapper($playerformMapper)
2407
    {
2408
        $this->playerformMapper = $playerformMapper;
2409
2410
        return $this;
2411
    }
2412
2413
    public function getInvitationMapper()
2414
    {
2415
        if (null === $this->invitationMapper) {
2416
            $this->invitationMapper = $this->serviceLocator->get('playgroundgame_invitation_mapper');
2417
        }
2418
2419
        return $this->invitationMapper;
2420
    }
2421
2422
    public function setInvitationMapper($invitationMapper)
2423
    {
2424
        $this->invitationMapper = $invitationMapper;
2425
2426
        return $this;
2427
    }
2428
2429
    /**
2430
     * getUserMapper
2431
     *
2432
     * @return UserMapperInterface
2433
     */
2434
    public function getUserMapper()
2435
    {
2436
        if (null === $this->userMapper) {
2437
            $this->userMapper = $this->serviceLocator->get('zfcuser_user_mapper');
2438
        }
2439
2440
        return $this->userMapper;
2441
    }
2442
2443
    /**
2444
     * getUserMapper
2445
     *
2446
     * @return ServiceManager
2447
     */
2448
    public function getServiceManager()
2449
    {
2450
        return $this->serviceLocator;
2451
    }
2452
}
2453