Completed
Push — master ( 58523e...56a418 )
by greg
37:25 queued 34:17
created

PostVote   F

Complexity

Total Complexity 115

Size/Duplication

Total Lines 798
Duplicated Lines 26.44 %

Coupling/Cohesion

Components 1
Dependencies 9

Importance

Changes 0
Metric Value
wmc 115
lcom 1
cbo 9
dl 211
loc 798
rs 1.802
c 0
b 0
f 0

32 Methods

Rating   Name   Duplication   Size   Complexity  
A getGameEntity() 0 4 1
A getPath() 14 14 3
A getMediaUrl() 7 7 1
A checkPost() 0 14 2
A uploadFileToPost() 0 32 4
A deleteFilePosted() 0 25 4
C createPost() 0 85 14
A confirmPost() 0 39 4
A createForm() 30 30 5
C findArrayOfValidatedPosts() 0 94 12
B toggleVote() 58 58 9
A removeVote() 0 35 5
B addVote() 57 57 9
A addComment() 0 27 3
A addShare() 0 12 1
A getCommentsForPostvote() 0 7 1
A removeComment() 0 17 2
A getEntriesHeader() 7 16 5
A getEntriesQuery() 38 38 1
B getGameEntries() 0 28 11
A getPostVoteFormMapper() 0 8 2
A setPostVoteFormMapper() 0 6 1
A getPostVotePostElementMapper() 0 10 2
A setPostVotePostElementMapper() 0 6 1
A getPostVoteVoteMapper() 0 8 2
A setPostVoteVoteMapper() 0 6 1
A getPostVoteCommentMapper() 0 8 2
A setPostVoteCommentMapper() 0 6 1
A getPostVotePostMapper() 0 8 2
A setPostVotePostMapper() 0 6 1
A getPostVoteMapper() 0 8 2
A setPostVoteMapper() 0 6 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 PostVote 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 PostVote, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace PlaygroundGame\Service;
4
5
use Zend\Stdlib\ErrorHandler;
6
7
class PostVote extends Game
8
{
9
    protected $postvoteMapper;
10
    protected $postvoteformMapper;
11
    protected $postVotePostMapper;
12
    protected $postVoteVoteMapper;
13
    protected $postVoteCommentMapper;
14
    protected $postVotePostElementMapper;
15
16
    public function getGameEntity()
17
    {
18
        return new \PlaygroundGame\Entity\PostVote;
19
    }
20
21 View Code Duplication
    public function getPath($post)
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...
22
    {
23
        $path = $this->getOptions()->getMediaPath() . DIRECTORY_SEPARATOR;
24
        $path .= 'game' . $post->getPostVote()->getId() . DIRECTORY_SEPARATOR;
25
        if (!is_dir($path)) {
26
            mkdir($path, 0777, true);
27
        }
28
        $path .= 'post'. $post->getId() . DIRECTORY_SEPARATOR;
29
        if (!is_dir($path)) {
30
            mkdir($path, 0777, true);
31
        }
32
33
        return $path;
34
    }
35
36 View Code Duplication
    public function getMediaUrl($post)
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...
37
    {
38
        $media_url = $this->getOptions()->getMediaUrl() . '/';
39
        $media_url .= 'game' . $post->getPostVote()->getId() . '/' . 'post'. $post->getId() . '/';
40
41
        return $media_url;
42
    }
43
44
    /**
45
     * @param boolean $entry
46
     */
47
    public function checkPost($entry)
48
    {
49
        $post = $this->getPostVotePostMapper()->findOneBy(array('entry' => $entry));
50
51
        if (! $post) {
52
            $post = new \PlaygroundGame\Entity\PostVotePost();
53
            $post->setPostvote($entry->getGame());
0 ignored issues
show
Bug introduced by
The method getGame 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...
54
            $post->setUser($entry->getUser());
0 ignored issues
show
Bug introduced by
The method getUser 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...
55
            $post->setEntry($entry);
56
            $post = $this->getPostVotePostMapper()->insert($post);
57
        }
58
59
        return $post;
60
    }
61
62
    public function uploadFileToPost($data, $game, $user)
63
    {
64
        $result = false;
65
        $entry = $this->findLastActiveEntry($game, $user);
66
67
        if (!$entry) {
68
            return '0';
69
        }
70
71
        $post = $this->checkPost($entry);
72
        $path = $this->getPath($post);
73
        $media_url = $this->getMediaUrl($post);
74
75
        $key = key($data);
76
        $uploadFile = $this->uploadFile($path, $data[$key]);
77
78
        if ($uploadFile) {
79
            $postElement = $this->getPostVotePostElementMapper()->findOneBy(array('post' => $post, 'name' => $key));
80
            if (! $postElement) {
81
                $postElement = new \PlaygroundGame\Entity\PostVotePostElement();
82
            }
83
            $postElement->setName($key);
84
            $postElement->setPosition(0);
85
            $postElement->setValue($media_url.$uploadFile);
86
            $postElement->setPost($post);
87
            $postElement = $this->getPostVotePostElementMapper()->insert($postElement);
0 ignored issues
show
Unused Code introduced by
$postElement 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...
88
89
            $result = $media_url.$uploadFile;
90
        }
91
92
        return $result;
93
    }
94
95
    public function deleteFilePosted($data, $game, $user)
96
    {
97
        $postvotePostMapper = $this->getPostVotePostMapper();
98
        $postVotePostElementMapper = $this->getPostVotePostElementMapper();
99
100
        $entry = $this->findLastActiveEntry($game, $user);
101
102
        if (!$entry) {
103
            return 'falsefin0';
104
        }
105
106
        $post = $postvotePostMapper->findOneBy(array('entry' => $entry));
107
        $element = $postVotePostElementMapper->findOneBy(array('post' => $post->getId(), 'name' => $data['name']));
108
109
        if ($element) {
110
            $element = $postVotePostElementMapper->remove($element);
111
            if ($element) {
112
                return true;
113
            } else {
114
                return false;
115
            }
116
        } else {
117
            return false;
118
        }
119
    }
120
121
    /**
122
     *
123
     * @param  array $data
124
     * @return \PlaygroundGame\Entity\Game
125
     */
126
    public function createPost(array $data, $game, $user, $form)
127
    {
128
        $postvotePostMapper = $this->getPostVotePostMapper();
129
        $postVotePostElementMapper = $this->getPostVotePostElementMapper();
130
131
        $entry = $this->findLastActiveEntry($game, $user);
132
133
        if (!$entry) {
134
            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\PostVote::createPost 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...
135
        }
136
137
        $post = $this->checkPost($entry);
138
        $path = $this->getPath($post);
139
        $media_url = $this->getMediaUrl($post);
140
        $position=1;
141
142
        foreach ($data as $name => $value) {
143
            $postElement = $postVotePostElementMapper->findOneBy(array('post' => $post, 'name' => $name));
144
            if (! $postElement) {
145
                $postElement = new \PlaygroundGame\Entity\PostVotePostElement();
146
            }
147
            $postElement->setName($name);
148
            $postElement->setPosition($position);
149
150
            if (is_array($value) && isset($value['tmp_name'])) {
151
                // The file upload has been done in ajax but some weird bugs remain without it
152
153
                if (! $value['error']) {
154
                    ErrorHandler::start();
155
                    $value['name'] = $this->fileNewname($path, $value['name'], true);
156
                    move_uploaded_file($value['tmp_name'], $path . $value['name']);
157
158
                    if (getimagesize($path . $value['name'])) {
159
                        $image = $this->serviceLocator->get('playgroundcore_image_service');
160
                        $image->setImage($path . $value['name']);
161
162
                        if ($image->canCorrectOrientation()) {
163
                            $image->correctOrientation()->save();
164
                        }
165
                        $postElement->setValue($media_url . $value['name']);
166
                        
167
                        if (class_exists("Imagick")) {
168
                            $ext = pathinfo($value['name'], PATHINFO_EXTENSION);
169
                            $img = new \Imagick($path . $value['name']);
170
                            $img->cropThumbnailImage(100, 100);
171
                            $img->setImageCompression(\Imagick::COMPRESSION_JPEG);
172
                            $img->setImageCompressionQuality(75);
173
                            // Strip out unneeded meta data
174
                            $img->stripImage();
175
                            $img->writeImage($path . str_replace('.'.$ext, '-thumbnail.'.$ext, $value['name']));
176
                            ErrorHandler::stop(true);
177
                        }
178
                    } else {
179
                        $postElement->setValue($media_url . $value['name']);
180
                    }
181
                }
182
            } elseif (is_array($value) || $form->get($name) instanceof \Zend\Form\Element\Select) {
183
                $arValues = $form->get($name)->getValueOptions();
184
                $postElement->setValue($arValues[$value[0]]);
185
            } elseif (!empty($value)) {
186
                $postElement->setValue($value);
187
            }
188
            $postElement->setPost($post);
189
            $postVotePostElementMapper->insert($postElement);
190
            $position++;
191
        }
192
193
        $postvotePostMapper->update($post);
194
195
        // If a preview step is not proposed, I confirmPost on this step
196
        $steps = $game->getStepsArray();
197
        $previewKey = array_search('preview', $steps);
198
        if (!$previewKey) {
199
            $post = $this->confirmPost($game, $user);
200
        }
201
202
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
203
            'user' => $user,
204
            'game' => $game,
205
            'post' => $post,
206
            'entry' => $entry
207
        ));
208
209
        return $post;
210
    }
211
212
    /**
213
     *
214
     * @return \PlaygroundGame\Entity\Game
215
     */
216
    public function confirmPost($game, $user)
217
    {
218
        $postvotePostMapper = $this->getPostVotePostMapper();
219
220
        $entryMapper = $this->getEntryMapper();
221
        $entry = $this->findLastActiveEntry($game, $user);
222
223
        if (!$entry) {
224
            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\PostVote::confirmPost 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...
225
        }
226
227
        $post = $postvotePostMapper->findOneBy(array('entry' => $entry));
228
229
        if (! $post) {
230
            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\PostVote::confirmPost 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...
231
        }
232
233
        // The post is confirmed by user. I update the status and close the associated entry
234
        // Post are validated by default, unless pre-moderation is enable for the game
235
        if ($game->getModerationType()) {
236
            $post->setStatus(1);
237
        } else {
238
            $post->setStatus(2);
239
        }
240
241
        $postvotePostMapper->update($post);
242
243
        $entry->setActive(0);
0 ignored issues
show
Bug introduced by
The method setActive 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...
244
        $entryMapper->update($entry);
245
246
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
247
            'user' => $user,
248
            'game' => $game,
249
            'entry' => $entry,
250
            'post' => $post
251
        ));
252
253
        return $post;
254
    }
255
256
    /**
257
     *
258
     * This service is ready for all types of games
259
     *
260
     * @param  array                  $data
261
     * @return \PlaygroundGame\Entity\Game
262
     */
263 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...
264
    {
265
        $title ='';
266
        $description = '';
267
268
        if ($data['form_jsonified']) {
269
            $jsonPV = json_decode($data['form_jsonified']);
270
            foreach ($jsonPV as $element) {
271
                if ($element->form_properties) {
272
                    $attributes  = $element->form_properties[0];
273
                    $title       = $attributes->title;
274
                    $description = $attributes->description;
275
276
                    break;
277
                }
278
            }
279
        }
280
        if (!$form) {
281
            $form = new \PlaygroundGame\Entity\PostVoteForm();
282
        }
283
        $form->setPostvote($game);
284
        $form->setTitle($title);
285
        $form->setDescription($description);
286
        $form->setForm($data['form_jsonified']);
287
        $form->setFormTemplate($data['form_template']);
288
289
        $form = $this->getPostVoteFormMapper()->insert($form);
290
291
        return $form;
292
    }
293
294
    public function findArrayOfValidatedPosts($game, $user, $filter, $search = '')
295
    {
296
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
297
        $qb = $em->createQueryBuilder();
298
        $and = $qb->expr()->andx();
299
        
300
        $and->add($qb->expr()->eq('p.status', 2));
301
302
        $and->add($qb->expr()->eq('g.id', ':game'));
303
        $qb->setParameter('game', $game);
304
        
305
        if ($search != '') {
306
            $and->add(
307
                $qb->expr()->orX(
308
                    $qb->expr()->like('u.username', $qb->expr()->literal('%:search%')),
309
                    $qb->expr()->like('u.firstname', $qb->expr()->literal('%:search%')),
310
                    $qb->expr()->like('u.lastname', $qb->expr()->literal('%:search%')),
311
                    $qb->expr()->like('e.value', $qb->expr()->literal('%:search%')),
312
                    $qb->expr()->isNull('g.publicationDate')
313
                )
314
            );
315
            $qb->setParameter('search', $search);
316
        }
317
        
318
        if ('push' == $filter) {
319
            $and->add(
320
                $qb->expr()->andX(
321
                    $qb->expr()->eq('p.pushed', 1)
322
                )
323
            );
324
        }
325
        
326
        $qb->select('p, COUNT(DISTINCT v) AS votesCount, COUNT(distinct av) AS voted')
327
            ->from('PlaygroundGame\Entity\PostVotePost', 'p')
328
            ->innerJoin('p.postvote', 'g')
329
            ->leftJoin('p.user', 'u')
330
            ->innerJoin('p.postElements', 'e')
331
            ->leftJoin('p.votes', 'v')
332
            ->leftJoin('p.votes', 'av', 'WITH', 'av.user = :user')
333
            ->where($and)
334
            ->groupBy('p.id');
335
 
336
        if ($user) {
337
            $qb->setParameter('user', $user);
338
        } else {
339
            $qb->setParameter('user', null);
340
        }
341
342
        switch ($filter) {
343
            case 'random':
344
                $qb->orderBy('e.value', 'ASC');
345
                break;
346
            case 'vote':
347
                $qb->orderBy('votesCount', 'DESC');
348
                break;
349
            case 'date':
350
                $qb->orderBy('p.createdAt', 'DESC');
351
                break;
352
            case 'push':
353
                $qb->orderBy('p.createdAt', 'DESC');
354
                break;
355
            case 'id':
356
                $qb->orderBy('p.createdAt', 'ASC');
357
                break;
358
            default:
359
                $qb->orderBy('p.createdAt', 'ASC');
360
                break;
361
        }
362
        
363
        $query = $qb->getQuery();
364
        
365
        $posts = $query->getResult();
366
        $arrayPosts = array();
367
        $i=0;
368
        foreach ($posts as $postRaw) {
369
            $data = array();
370
            $post = $postRaw[0];
371
            if ($post) {
372
                foreach ($post->getPostElements() as $element) {
373
                    $data[$element->getPosition()] = $element->getValue();
374
                }
375
                $arrayPosts[$i]['post']  = $post;
376
                $arrayPosts[$i]['data']  = $data;
377
                $arrayPosts[$i]['votes'] = count($post->getVotes());
378
                $arrayPosts[$i]['voted'] = $postRaw['voted'];
379
                $arrayPosts[$i]['id']    = $post->getId();
380
                $arrayPosts[$i]['user']  = $post->getUser();
381
                $arrayPosts[$i]['createdAt']  = $post->getCreatedAt();
382
                $i++;
383
            }
384
        }
385
386
        return $arrayPosts;
387
    }
388
389 View Code Duplication
    public function toggleVote($user, $ipAddress, $post, $comment = 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...
390
    {
391
        $postvoteVoteMapper = $this->getPostVoteVoteMapper();
392
        $postId = $post->getId();
393
        $commentId = ($comment !== null) ? $comment->getId() : null;
394
        $vote = null;
0 ignored issues
show
Unused Code introduced by
$vote 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...
395
        $game = $post->getPostvote();
396
397
        if ($user) {
398
            if ($comment == null) {
399
                $entryUser = count($postvoteVoteMapper->findBy(array('user' => $user, 'post' => $postId)));
400
                $vote = $postvoteVoteMapper->findOneBy(array('user' => $user, 'post' => $postId));
401
            } else {
402
                $entryUser = count($postvoteVoteMapper->findBy(array('user' => $user, 'post' => $postId, 'postComment' => $commentId)));
403
                $vote = $postvoteVoteMapper->findOneBy(array('user' => $user, 'post' => $postId, 'postComment' => $commentId));
404
            }
405
            
406
        } else {
407
            if ($comment == null) {
408
                $entryUser = count($postvoteVoteMapper->findBy(array('ip' => $ipAddress, 'post' => $postId)));
409
                $vote = $postvoteVoteMapper->findOneBy(array('ip' => $ipAddress, 'post' => $postId));
410
            } else {
411
                $entryUser = count($postvoteVoteMapper->findBy(array('ip' => $ipAddress, 'post' => $postId, 'postComment' => $commentId)));
412
                $vote = $postvoteVoteMapper->findOneBy(array('ip' => $ipAddress, 'post' => $postId, 'postComment' => $commentId));
413
            }
414
        }
415
416
        if ($entryUser && $entryUser > 0) {
417
            $postvoteVoteMapper->remove($vote);
418
        } else {
419
            $vote = new \PlaygroundGame\Entity\PostVoteVote();
420
            $vote->setPost($post);
421
            $vote->setIp($ipAddress);
422
            $vote->setNote(1);
0 ignored issues
show
Documentation introduced by
1 is of type integer, but the function expects a object<PlaygroundGame\Entity\unknown_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...
423
            // If the vote is for a comment
424
            if ($comment != null) {
425
                $vote->setPostComment($comment);
426
                $vote->setPostvote($post->getPostvote());
427
            // else if the vote is for the post itself
428
            } else {
429
                $vote->setPostvote($post->getPostvote(), true);
0 ignored issues
show
Unused Code introduced by
The call to PostVoteVote::setPostvote() has too many arguments starting with true.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
430
            }
431
432
            if ($user) {
433
                $vote->setUser($user);
434
            }
435
436
            $postvoteVoteMapper->insert($vote);
437
        }
438
439
        $this->getEventManager()->trigger(
440
            __FUNCTION__ .'.post',
441
            $this,
442
            array('user' => $user, 'game' => $game, 'post' => $post, 'vote' => $vote)
443
        );
444
445
        return true;
446
    }
447
448
    public function removeVote($user, $ipAddress, $post)
449
    {
450
        $postvoteVoteMapper = $this->getPostVoteVoteMapper();
451
        $postId = $post->getId();
452
        $commentId = ($comment !== null) ? $comment->getId() : null;
0 ignored issues
show
Bug introduced by
The variable $comment does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
453
        $vote = null;
0 ignored issues
show
Unused Code introduced by
$vote 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...
454
        $game = $post->getPostvote();
455
456
        if ($user) {
457
            if ($comment == null) {
458
                $entryUser = count($postvoteVoteMapper->findBy(array('user' => $user, 'post' => $postId)));
0 ignored issues
show
Unused Code introduced by
$entryUser 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...
459
                $vote = $postvoteVoteMapper->findOneBy(array('user' => $user, 'post' => $postId));
460
            } else {
461
                $entryUser = count($postvoteVoteMapper->findBy(array('user' => $user, 'post' => $postId, 'postComment' => $commentId)));
0 ignored issues
show
Unused Code introduced by
$entryUser 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...
462
                $vote = $postvoteVoteMapper->findOneBy(array('user' => $user, 'post' => $postId, 'postComment' => $commentId));
463
            }
464
            
465
        } else {
466
            if ($comment == null) {
467
                $entryUser = count($postvoteVoteMapper->findBy(array('ip' => $ipAddress, 'post' => $postId)));
0 ignored issues
show
Unused Code introduced by
$entryUser 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...
468
                $vote = $postvoteVoteMapper->findOneBy(array('ip' => $ipAddress, 'post' => $postId));
469
            } else {
470
                $entryUser = count($postvoteVoteMapper->findBy(array('ip' => $ipAddress, 'post' => $postId, 'postComment' => $commentId)));
0 ignored issues
show
Unused Code introduced by
$entryUser 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...
471
                $vote = $postvoteVoteMapper->findOneBy(array('ip' => $ipAddress, 'post' => $postId, 'postComment' => $commentId));
472
            }
473
        }
474
475
        $this->getEventManager()->trigger(
476
            __FUNCTION__ .'.post',
477
            $this,
478
            array('user' => $user, 'game' => $game, 'post' => $post, 'vote' => $vote)
479
        );
480
481
        return true;
482
    }
483
484 View Code Duplication
    public function addVote($user, $ipAddress, $post)
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...
485
    {
486
        $postvoteVoteMapper = $this->getPostVoteVoteMapper();
487
        $postId = $post->getId();
488
        $commentId = ($comment !== null) ? $comment->getId() : null;
0 ignored issues
show
Bug introduced by
The variable $comment does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
489
        $vote = null;
0 ignored issues
show
Unused Code introduced by
$vote 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...
490
        $game = $post->getPostvote();
0 ignored issues
show
Unused Code introduced by
$game 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...
491
492
        if ($user) {
493
            if ($comment == null) {
494
                $entryUser = count($postvoteVoteMapper->findBy(array('user' => $user, 'post' => $postId)));
495
                $vote = $postvoteVoteMapper->findOneBy(array('user' => $user, 'post' => $postId));
0 ignored issues
show
Unused Code introduced by
$vote 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...
496
            } else {
497
                $entryUser = count($postvoteVoteMapper->findBy(array('user' => $user, 'post' => $postId, 'postComment' => $commentId)));
498
                $vote = $postvoteVoteMapper->findOneBy(array('user' => $user, 'post' => $postId, 'postComment' => $commentId));
0 ignored issues
show
Unused Code introduced by
$vote 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...
499
            }
500
            
501
        } else {
502
            if ($comment == null) {
503
                $entryUser = count($postvoteVoteMapper->findBy(array('ip' => $ipAddress, 'post' => $postId)));
504
                $vote = $postvoteVoteMapper->findOneBy(array('ip' => $ipAddress, 'post' => $postId));
0 ignored issues
show
Unused Code introduced by
$vote 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...
505
            } else {
506
                $entryUser = count($postvoteVoteMapper->findBy(array('ip' => $ipAddress, 'post' => $postId, 'postComment' => $commentId)));
507
                $vote = $postvoteVoteMapper->findOneBy(array('ip' => $ipAddress, 'post' => $postId, 'postComment' => $commentId));
0 ignored issues
show
Unused Code introduced by
$vote 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...
508
            }
509
        }
510
511
        if ($entryUser && $entryUser > 0) {
512
            return false;
513
        } else {
514
            $vote = new \PlaygroundGame\Entity\PostVoteVote();
515
            $vote->setPost($post);
516
            $vote->setIp($ipAddress);
517
            $vote->setNote(1);
0 ignored issues
show
Documentation introduced by
1 is of type integer, but the function expects a object<PlaygroundGame\Entity\unknown_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...
518
            // If the vote is for a comment
519
            if ($comment != null) {
520
                $vote->setPostComment($comment);
521
                $vote->setPostvote($post->getPostvote());
522
            // else if the vote is for the post itself
523
            } else {
524
                $vote->setPostvote($post->getPostvote(), true);
0 ignored issues
show
Unused Code introduced by
The call to PostVoteVote::setPostvote() has too many arguments starting with true.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
525
            }
526
            if ($user) {
527
                $vote->setUser($user);
528
            }
529
530
            $postvoteVoteMapper->insert($vote);
531
            $game = $post->getPostvote();
532
            $this->getEventManager()->trigger(
533
                __FUNCTION__ .'.post',
534
                $this,
535
                array('user' => $user, 'game' => $game, 'post' => $post, 'vote' => $vote)
536
            );
537
538
            return true;
539
        }
540
    }
541
542
    public function addComment($user, $ipAddress, $post, $message = '', $category = null)
543
    {
544
        $postvoteCommentMapper = $this->getPostVoteCommentMapper();
545
        $game = $post->getPostvote();
546
        $comment = new \PlaygroundGame\Entity\PostVoteComment();
547
        $comment->setPost($post);
548
        $comment->setIp($ipAddress);
549
        $message = strip_tags($message);
550
        $comment->setMessage($message);
0 ignored issues
show
Documentation introduced by
$message is of type string, but the function expects a object<PlaygroundGame\Entity\unknown_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...
551
        if ($category !== null) {
552
            $comment->setCategory($category);
553
        }
554
        $comment->setPostvote($game);
555
        if ($user) {
556
            $comment->setUser($user);
557
        }
558
559
        $postvoteCommentMapper->insert($comment);
560
        
561
        $this->getEventManager()->trigger(
562
            __FUNCTION__ .'.post',
563
            $this,
564
            array('user' => $user, 'game' => $game, 'post' => $post, 'comment' => $comment)
565
        );
566
567
        return true;
568
    }
569
570
571
    public function addShare($post)
572
    {
573
        $postvotePostMapper = $this->getPostVotePostMapper();
574
        $post->setShares($post->getShares()+1);
575
        $postvotePostMapper->update($post);
576
577
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
578
            'post' => $post
579
        ));
580
581
        return true;
582
    }
583
    /**
584
     * Get all comments for this game
585
     */
586
    public function getCommentsForPostvote($postvote)
587
    {
588
        $postvoteCommentMapper = $this->getPostVoteCommentMapper();
589
        $comments = $postvoteCommentMapper->findBy(array('postvote' => $postvote), array('createdAt' => 'DESC'));
590
591
        return $comments ;
592
    }
593
594
    public function removeComment($user, $ipAddress, $messageId)
0 ignored issues
show
Unused Code introduced by
The parameter $ipAddress 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...
595
    {
596
        $postvoteCommentMapper = $this->getPostVoteCommentMapper();
597
        $comment = $postvoteCommentMapper->findOneBy(array('id' => $messageId));
598
        if ($comment->getUser()->getId() === $user->getId()) {
599
            $postvoteCommentMapper->remove($comment);
600
            $this->getEventManager()->trigger(
601
                'remove_comment_postvote.post',
602
                $this,
603
                array('user' => $user, 'comment' => $comment)
604
            );
605
606
            return true;
607
        }
608
609
        return false;
610
    }
611
612
    public function getEntriesHeader($game)
613
    {
614
        $header = parent::getEntriesHeader($game);
615
        if ($game->getForm()) {
616
            $form = json_decode($game->getForm()->getForm(), true);
617 View Code Duplication
            foreach ($form 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...
618
                foreach ($element as $k => $v) {
619
                    if ($k !== 'form_properties') {
620
                        $header[$v[0]['name']] = 1;
621
                    }
622
                }
623
            }
624
        }
625
626
        return $header;
627
    }
628
629 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...
630
    {
631
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
632
633
        $qb = $em->createQueryBuilder();
634
        $qb->select('
635
            p.id,
636
            u.username,
637
            u.title,
638
            u.firstname,
639
            u.lastname,
640
            u.email,
641
            u.optin,
642
            u.optinPartner,
643
            u.address,
644
            u.address2,
645
            u.postalCode,
646
            u.city,
647
            u.telephone,
648
            u.mobile,
649
            u.created_at,
650
            u.dob,
651
            e.winner,
652
            e.socialShares,
653
            e.playerData,
654
            e.updated_at,
655
            p.status,
656
            p
657
            ')
658
            ->from('PlaygroundGame\Entity\PostVotePost', 'p')
659
            ->innerJoin('p.entry', 'e')
660
            ->leftJoin('p.user', 'u')
661
            ->where($qb->expr()->eq('e.game', ':game'));
662
        
663
        $qb->setParameter('game', $game);
664
665
        return $qb->getQuery();
666
    }
667
668
    /**
669
    * getGameEntries : All entries of a game
670
    *
671
    * @return Array of PlaygroundGame\Entity\Game
672
    */
673
    public function getGameEntries($header, $entries, $game)
674
    {
675
        $results = array();
676
677
        foreach ($entries as $k => $entry) {
678
            $entryData = json_decode($entry['playerData'], true);
679
            $postElements = $entry[0]->getPostElements();
680
681
            foreach ($header as $key => $v) {
682
                if (isset($entryData[$key]) && $key !=='id') {
683
                    $results[$k][$key] = (is_array($entryData[$key]))?implode(', ', $entryData[$key]):$entryData[$key];
684
                } elseif (array_key_exists($key, $entry)) {
685
                    $results[$k][$key] = ($entry[$key] instanceof \DateTime)?$entry[$key]->format('Y-m-d'):$entry[$key];
686
                } else {
687
                    $results[$k][$key] = '';
688
                }
689
690
                foreach ($postElements as $e) {
691
                    if ($key === $e->getName()) {
692
                        $results[$k][$key] = (is_array($e->getValue()))?implode(', ', $e->getValue()):$e->getValue();
693
                        break;
694
                    }
695
                }
696
            }
697
        }
698
699
        return $results;
700
    }
701
702
    public function getPostVoteFormMapper()
703
    {
704
        if (null === $this->postvoteformMapper) {
705
            $this->postvoteformMapper = $this->serviceLocator->get('playgroundgame_postvoteform_mapper');
706
        }
707
708
        return $this->postvoteformMapper;
709
    }
710
711
    public function setPostVoteFormMapper($postvoteformMapper)
712
    {
713
        $this->postvoteformMapper = $postvoteformMapper;
714
715
        return $this;
716
    }
717
718
    public function getPostVotePostElementMapper()
719
    {
720
        if (null === $this->postVotePostElementMapper) {
721
            $this->postVotePostElementMapper = $this->serviceLocator->get(
722
                'playgroundgame_postvotepostelement_mapper'
723
            );
724
        }
725
726
        return $this->postVotePostElementMapper;
727
    }
728
729
    public function setPostVotePostElementMapper($postVotePostElementMapper)
730
    {
731
        $this->postVotePostElementMapper = $postVotePostElementMapper;
732
733
        return $this;
734
    }
735
736
    public function getPostVoteVoteMapper()
737
    {
738
        if (null === $this->postVoteVoteMapper) {
739
            $this->postVoteVoteMapper = $this->serviceLocator->get('playgroundgame_postvotevote_mapper');
740
        }
741
742
        return $this->postVoteVoteMapper;
743
    }
744
745
    public function setPostVoteVoteMapper($postVoteVoteMapper)
746
    {
747
        $this->postVoteVoteMapper = $postVoteVoteMapper;
748
749
        return $this;
750
    }
751
752
    public function getPostVoteCommentMapper()
753
    {
754
        if (null === $this->postVoteCommentMapper) {
755
            $this->postVoteCommentMapper = $this->serviceLocator->get('playgroundgame_postvotecomment_mapper');
756
        }
757
758
        return $this->postVoteCommentMapper;
759
    }
760
761
    public function setPostVoteCommentMapper($postVoteCommentMapper)
762
    {
763
        $this->postVoteCommentMapper = $postVoteCommentMapper;
764
765
        return $this;
766
    }
767
768
    public function getPostVotePostMapper()
769
    {
770
        if (null === $this->postVotePostMapper) {
771
            $this->postVotePostMapper = $this->serviceLocator->get('playgroundgame_postvotepost_mapper');
772
        }
773
774
        return $this->postVotePostMapper;
775
    }
776
777
    public function setPostVotePostMapper($postVotePostMapper)
778
    {
779
        $this->postVotePostMapper = $postVotePostMapper;
780
781
        return $this;
782
    }
783
784
    public function getPostVoteMapper()
785
    {
786
        if (null === $this->postvoteMapper) {
787
            $this->postvoteMapper = $this->serviceLocator->get('playgroundgame_postvote_mapper');
788
        }
789
790
        return $this->postvoteMapper;
791
    }
792
793
    /**
794
     * setQuizQuestionMapper
795
     *
796
     * @return PostVote
797
     */
798
    public function setPostVoteMapper($postvoteMapper)
799
    {
800
        $this->postvoteMapper = $postvoteMapper;
801
802
        return $this;
803
    }
804
}
805