Completed
Push — master ( 0e3d33...33a693 )
by greg
08:28 queued 04:16
created

PostVote::createPost()   D

Complexity

Conditions 16
Paths 111

Size

Total Lines 96

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 96
rs 4.4672
c 0
b 0
f 0
cc 16
nc 111
nop 4

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
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
            foreach($form as $e) {
149
                if ($e->getName() == $name) {
150
                    $postElement->setLabel($e->getLabel());
151
                    break;
152
                }
153
            }
154
            $postElement->setPosition($position);
155
156
            if (is_array($value) && isset($value['tmp_name'])) {
157
                // The file upload has been done in ajax but some weird bugs remain without it
158
159
                if (! $value['error']) {
160
                    ErrorHandler::start();
161
                    $value['name'] = $this->fileNewname($path, $value['name'], true);
162
                    move_uploaded_file($value['tmp_name'], $path . $value['name']);
163
164
                    if (getimagesize($path . $value['name'])) {
165
                        $image = $this->serviceLocator->get('playgroundcore_image_service');
166
                        $image->setImage($path . $value['name']);
167
168
                        if ($image->canCorrectOrientation()) {
169
                            $image->correctOrientation()->save();
170
                        }
171
                        $postElement->setValue($media_url . $value['name']);
172
                        
173
                        if (class_exists("Imagick")) {
174
                            $ext = pathinfo($value['name'], PATHINFO_EXTENSION);
175
                            $img = new \Imagick($path . $value['name']);
176
                            $img->cropThumbnailImage(100, 100);
177
                            $img->setImageCompression(\Imagick::COMPRESSION_JPEG);
178
                            $img->setImageCompressionQuality(75);
179
                            // Strip out unneeded meta data
180
                            $img->stripImage();
181
                            $img->writeImage($path . str_replace('.'.$ext, '-thumbnail.'.$ext, $value['name']));
182
                            ErrorHandler::stop(true);
183
                        }
184
                    } else {
185
                        $postElement->setValue($media_url . $value['name']);
186
                    }
187
                }
188
            } elseif (is_array($value) || $form->get($name) instanceof \Zend\Form\Element\Select) {
189
                $arValues = $form->get($name)->getValueOptions();
190
                $postElement->setValue($arValues[$value[0]]);
191
            } elseif (!empty($value)) {
192
                $postElement->setValue($value);
193
            }
194
            $post->addPostElement($postElement);
195
            // $postElement->setPost($post);
196
            // $postVotePostElementMapper->insert($postElement);
197
            $position++;
198
        }
199
200
        $postvotePostMapper->update($post);
201
202
        // If a preview step is not proposed, I confirmPost on this step
203
        $steps = $game->getStepsArray();
204
        $previewKey = array_search('preview', $steps);
205
        if (!$previewKey) {
206
            $post = $this->confirmPost($game, $user);
207
        }
208
209
        $this->getEventManager()->trigger(
210
            __FUNCTION__ . '.post',
211
            $this,
212
            [
213
                'user' => $user,
214
                'game' => $game,
215
                'post' => $post,
216
                'entry' => $entry,
217
            ]
218
        );
219
220
        return $post;
221
    }
222
223
    /**
224
     *
225
     * @return \PlaygroundGame\Entity\Game
226
     */
227
    public function confirmPost($game, $user)
228
    {
229
        $postvotePostMapper = $this->getPostVotePostMapper();
230
231
        $entryMapper = $this->getEntryMapper();
232
        $entry = $this->findLastActiveEntry($game, $user);
233
234
        if (!$entry) {
235
            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...
236
        }
237
238
        $post = $postvotePostMapper->findOneBy(array('entry' => $entry));
239
240
        if (! $post) {
241
            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...
242
        }
243
244
        // The post is confirmed by user. I update the status and close the associated entry
245
        // Post are validated by default, unless pre-moderation is enable for the game
246
        if ($game->getModerationType()) {
247
            $post->setStatus(1);
248
        } else {
249
            $post->setStatus(2);
250
        }
251
252
        $post = $postvotePostMapper->update($post);
253
254
        $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...
255
        $entryMapper->update($entry);
256
257
        $this->getEventManager()->trigger(
258
            __FUNCTION__ . '.post',
259
            $this,
260
            [
261
                'user' => $user,
262
                'game' => $game,
263
                'entry' => $entry,
264
                'post' => $post,
265
            ]
266
        );
267
268
        return $post;
269
    }
270
271
    /**
272
     *
273
     * This service is ready for all types of games
274
     *
275
     * @param  array                  $data
276
     * @return \PlaygroundGame\Entity\Game
277
     */
278 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...
279
    {
280
        $title ='';
281
        $description = '';
282
283
        if ($data['form_jsonified']) {
284
            $jsonPV = json_decode($data['form_jsonified']);
285
            foreach ($jsonPV as $element) {
286
                if ($element->form_properties) {
287
                    $attributes  = $element->form_properties[0];
288
                    $title       = $attributes->title;
289
                    $description = $attributes->description;
290
291
                    break;
292
                }
293
            }
294
        }
295
        if (!$form) {
296
            $form = new \PlaygroundGame\Entity\PostVoteForm();
297
        }
298
        $form->setPostvote($game);
299
        $form->setTitle($title);
300
        $form->setDescription($description);
301
        $form->setForm($data['form_jsonified']);
302
        $form->setFormTemplate($data['form_template']);
303
304
        $form = $this->getPostVoteFormMapper()->insert($form);
305
306
        return $form;
307
    }
308
309
    public function findArrayOfValidatedPosts($game, $user, $filter, $search = '')
310
    {
311
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
312
        $qb = $em->createQueryBuilder();
313
        $and = $qb->expr()->andx();
314
        
315
        $and->add($qb->expr()->eq('p.status', 2));
316
317
        $and->add($qb->expr()->eq('g.id', ':game'));
318
        $qb->setParameter('game', $game);
319
        
320
        if ($search != '') {
321
            $and->add(
322
                $qb->expr()->orX(
323
                    $qb->expr()->like('u.username', $qb->expr()->literal('%:search%')),
324
                    $qb->expr()->like('u.firstname', $qb->expr()->literal('%:search%')),
325
                    $qb->expr()->like('u.lastname', $qb->expr()->literal('%:search%')),
326
                    $qb->expr()->like('e.value', $qb->expr()->literal('%:search%')),
327
                    $qb->expr()->isNull('g.publicationDate')
328
                )
329
            );
330
            $qb->setParameter('search', $search);
331
        }
332
        
333
        if ('push' == $filter) {
334
            $and->add(
335
                $qb->expr()->andX(
336
                    $qb->expr()->eq('p.pushed', 1)
337
                )
338
            );
339
        }
340
        
341
        $qb->select('p, COUNT(DISTINCT v) AS votesCount, COUNT(distinct av) AS voted')
342
            ->from('PlaygroundGame\Entity\PostVotePost', 'p')
343
            ->innerJoin('p.postvote', 'g')
344
            ->leftJoin('p.user', 'u')
345
            ->innerJoin('p.postElements', 'e')
346
            ->leftJoin('p.votes', 'v')
347
            ->leftJoin('p.votes', 'av', 'WITH', 'av.user = :user')
348
            ->where($and)
349
            ->groupBy('p.id');
350
 
351
        if ($user) {
352
            $qb->setParameter('user', $user);
353
        } else {
354
            $qb->setParameter('user', null);
355
        }
356
357
        switch ($filter) {
358
            case 'random':
359
                $qb->orderBy('e.value', 'ASC');
360
                break;
361
            case 'vote':
362
                $qb->orderBy('votesCount', 'DESC');
363
                break;
364
            case 'date':
365
                $qb->orderBy('p.createdAt', 'DESC');
366
                break;
367
            case 'push':
368
                $qb->orderBy('p.createdAt', 'DESC');
369
                break;
370
            case 'id':
371
                $qb->orderBy('p.createdAt', 'ASC');
372
                break;
373
            default:
374
                $qb->orderBy('p.createdAt', 'ASC');
375
                break;
376
        }
377
        
378
        $query = $qb->getQuery();
379
        
380
        $posts = $query->getResult();
381
        $arrayPosts = array();
382
        $i=0;
383
        foreach ($posts as $postRaw) {
384
            $data = array();
385
            $post = $postRaw[0];
386
            if ($post) {
387
                foreach ($post->getPostElements() as $element) {
388
                    $data[$element->getPosition()] = $element->getValue();
389
                }
390
                $arrayPosts[$i]['post']  = $post;
391
                $arrayPosts[$i]['data']  = $data;
392
                $arrayPosts[$i]['votes'] = count($post->getVotes());
393
                $arrayPosts[$i]['voted'] = $postRaw['voted'];
394
                $arrayPosts[$i]['id']    = $post->getId();
395
                $arrayPosts[$i]['user']  = $post->getUser();
396
                $arrayPosts[$i]['createdAt']  = $post->getCreatedAt();
397
                $i++;
398
            }
399
        }
400
401
        return $arrayPosts;
402
    }
403
404 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...
405
    {
406
        $postvoteVoteMapper = $this->getPostVoteVoteMapper();
407
        $postId = $post->getId();
408
        $commentId = ($comment !== null) ? $comment->getId() : null;
409
        $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...
410
        $game = $post->getPostvote();
411
412
        if ($user) {
413
            if ($comment == null) {
414
                $entryUser = count($postvoteVoteMapper->findBy(array('user' => $user, 'post' => $postId)));
415
                $vote = $postvoteVoteMapper->findOneBy(array('user' => $user, 'post' => $postId));
416
            } else {
417
                $entryUser = count($postvoteVoteMapper->findBy(array('user' => $user, 'post' => $postId, 'postComment' => $commentId)));
418
                $vote = $postvoteVoteMapper->findOneBy(array('user' => $user, 'post' => $postId, 'postComment' => $commentId));
419
            }
420
        } else {
421
            if ($comment == null) {
422
                $entryUser = count($postvoteVoteMapper->findBy(array('ip' => $ipAddress, 'post' => $postId)));
423
                $vote = $postvoteVoteMapper->findOneBy(array('ip' => $ipAddress, 'post' => $postId));
424
            } else {
425
                $entryUser = count($postvoteVoteMapper->findBy(array('ip' => $ipAddress, 'post' => $postId, 'postComment' => $commentId)));
426
                $vote = $postvoteVoteMapper->findOneBy(array('ip' => $ipAddress, 'post' => $postId, 'postComment' => $commentId));
427
            }
428
        }
429
430
        if ($entryUser && $entryUser > 0) {
431
            $postvoteVoteMapper->remove($vote);
432
433
            return 0;
434
        } else {
435
            $vote = new \PlaygroundGame\Entity\PostVoteVote();
436
            $vote->setPost($post);
437
            $vote->setIp($ipAddress);
438
            $vote->setNote(1);
439
            // If the vote is for a comment
440
            if ($comment != null) {
441
                $vote->setPostComment($comment);
442
                $vote->setPostvote($post->getPostvote());
443
            // else if the vote is for the post itself
444
            } else {
445
                $vote->setPostvote($post->getPostvote(), true);
446
            }
447
448
            if ($user) {
449
                $vote->setUser($user);
450
            }
451
452
            $postvoteVoteMapper->insert($vote);
453
        }
454
455
        $this->getEventManager()->trigger(
456
            __FUNCTION__ .'.post',
457
            $this,
458
            array('user' => $user, 'game' => $game, 'post' => $post, 'vote' => $vote)
459
        );
460
461
        return 1;
462
    }
463
464
    public function removeVote($user, $ipAddress, $post)
465
    {
466
        $postvoteVoteMapper = $this->getPostVoteVoteMapper();
467
        $postId = $post->getId();
468
        $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...
469
        $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...
470
        $game = $post->getPostvote();
471
472
        if ($user) {
473
            if ($comment == null) {
474
                $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...
475
                $vote = $postvoteVoteMapper->findOneBy(array('user' => $user, 'post' => $postId));
476
            } else {
477
                $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...
478
                $vote = $postvoteVoteMapper->findOneBy(array('user' => $user, 'post' => $postId, 'postComment' => $commentId));
479
            }
480
        } else {
481
            if ($comment == null) {
482
                $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...
483
                $vote = $postvoteVoteMapper->findOneBy(array('ip' => $ipAddress, 'post' => $postId));
484
            } else {
485
                $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...
486
                $vote = $postvoteVoteMapper->findOneBy(array('ip' => $ipAddress, 'post' => $postId, 'postComment' => $commentId));
487
            }
488
        }
489
490
        $this->getEventManager()->trigger(
491
            __FUNCTION__ .'.post',
492
            $this,
493
            array('user' => $user, 'game' => $game, 'post' => $post, 'vote' => $vote)
494
        );
495
496
        return true;
497
    }
498
499 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...
500
    {
501
        $postvoteVoteMapper = $this->getPostVoteVoteMapper();
502
        $postId = $post->getId();
503
        $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...
504
        $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...
505
        $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...
506
507
        if ($user) {
508
            if ($comment == null) {
509
                $entryUser = count($postvoteVoteMapper->findBy(array('user' => $user, 'post' => $postId)));
510
                $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...
511
            } else {
512
                $entryUser = count($postvoteVoteMapper->findBy(array('user' => $user, 'post' => $postId, 'postComment' => $commentId)));
513
                $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...
514
            }
515
        } else {
516
            if ($comment == null) {
517
                $entryUser = count($postvoteVoteMapper->findBy(array('ip' => $ipAddress, 'post' => $postId)));
518
                $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...
519
            } else {
520
                $entryUser = count($postvoteVoteMapper->findBy(array('ip' => $ipAddress, 'post' => $postId, 'postComment' => $commentId)));
521
                $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...
522
            }
523
        }
524
525
        if ($entryUser && $entryUser > 0) {
526
            return false;
527
        } else {
528
            $vote = new \PlaygroundGame\Entity\PostVoteVote();
529
            $vote->setPost($post);
530
            $vote->setIp($ipAddress);
531
            $vote->setNote(1);
532
            // If the vote is for a comment
533
            if ($comment != null) {
534
                $vote->setPostComment($comment);
535
                $vote->setPostvote($post->getPostvote());
536
            // else if the vote is for the post itself
537
            } else {
538
                $vote->setPostvote($post->getPostvote(), true);
539
            }
540
            if ($user) {
541
                $vote->setUser($user);
542
            }
543
544
            $postvoteVoteMapper->insert($vote);
545
            $game = $post->getPostvote();
546
            $this->getEventManager()->trigger(
547
                __FUNCTION__ .'.post',
548
                $this,
549
                array('user' => $user, 'game' => $game, 'post' => $post, 'vote' => $vote)
550
            );
551
552
            return true;
553
        }
554
    }
555
556
    public function addComment($user, $ipAddress, $post, $message = '', $category = null)
557
    {
558
        $postvoteCommentMapper = $this->getPostVoteCommentMapper();
559
        $game = $post->getPostvote();
560
        $comment = new \PlaygroundGame\Entity\PostVoteComment();
561
        $comment->setPost($post);
562
        $comment->setIp($ipAddress);
563
        $message = strip_tags($message);
564
        $comment->setMessage($message);
565
        if ($category !== null) {
566
            $comment->setCategory($category);
567
        }
568
        $comment->setPostvote($game);
569
        if ($user) {
570
            $comment->setUser($user);
571
        }
572
573
        $postvoteCommentMapper->insert($comment);
574
        
575
        $this->getEventManager()->trigger(
576
            __FUNCTION__ .'.post',
577
            $this,
578
            array('user' => $user, 'game' => $game, 'post' => $post, 'comment' => $comment)
579
        );
580
581
        return true;
582
    }
583
584
585
    public function addShare($post)
586
    {
587
        $postvotePostMapper = $this->getPostVotePostMapper();
588
        $post->setShares($post->getShares()+1);
589
        $postvotePostMapper->update($post);
590
591
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array(
592
            'post' => $post
593
        ));
594
595
        return true;
596
    }
597
    /**
598
     * Get all comments for this game
599
     */
600
    public function getCommentsForPostvote($postvote)
601
    {
602
        $postvoteCommentMapper = $this->getPostVoteCommentMapper();
603
        $comments = $postvoteCommentMapper->findBy(array('postvote' => $postvote), array('createdAt' => 'DESC'));
604
605
        return $comments ;
606
    }
607
608
    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...
609
    {
610
        $postvoteCommentMapper = $this->getPostVoteCommentMapper();
611
        $comment = $postvoteCommentMapper->findOneBy(array('id' => $messageId));
612
        if ($comment->getUser()->getId() === $user->getId()) {
613
            $postvoteCommentMapper->remove($comment);
614
            $this->getEventManager()->trigger(
615
                'remove_comment_postvote.post',
616
                $this,
617
                array('user' => $user, 'comment' => $comment)
618
            );
619
620
            return true;
621
        }
622
623
        return false;
624
    }
625
626
    public function getEntriesHeader($game)
627
    {
628
        $header = parent::getEntriesHeader($game);
629
        if ($game->getForm()) {
630
            $form = json_decode($game->getForm()->getForm(), true);
631 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...
632
                foreach ($element as $k => $v) {
633
                    if ($k !== 'form_properties') {
634
                        $header[$v[0]['name']] = 1;
635
                    }
636
                }
637
            }
638
        }
639
        if ($game->getVoteActive()) {
640
            $header['votes'] = 1;
641
        }
642
643
        return $header;
644
    }
645
646 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...
647
    {
648
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
649
650
        $qb = $em->createQueryBuilder();
651
        $qb->select('
652
            p.id,
653
            u.username,
654
            u.title,
655
            u.firstname,
656
            u.lastname,
657
            u.displayName,
658
            u.email,
659
            u.optin,
660
            u.optinPartner,
661
            u.address,
662
            u.address2,
663
            u.postalCode,
664
            u.city,
665
            u.telephone,
666
            u.mobile,
667
            u.created_at,
668
            u.dob,
669
            e.winner,
670
            e.socialShares,
671
            e.playerData,
672
            e.updated_at,
673
            p.status,
674
            p
675
            ')
676
            ->from('PlaygroundGame\Entity\PostVotePost', 'p')
677
            ->innerJoin('p.entry', 'e')
678
            ->leftJoin('p.user', 'u')
679
            ->where($qb->expr()->eq('e.game', ':game'));
680
        
681
        $qb->setParameter('game', $game);
682
683
        return $qb->getQuery();
684
    }
685
686
    /**
687
    * getGameEntries : All entries of a game
688
    *
689
    * @return Array of PlaygroundGame\Entity\Game
690
    */
691
    public function getGameEntries($header, $entries, $game)
692
    {
693
        $results = array();
694
695
        foreach ($entries as $k => $entry) {
696
            $entryData = json_decode($entry['playerData'], true);
697
            $postElements = $entry[0]->getPostElements();
698
699
            foreach ($header as $key => $v) {
700
                if (isset($entryData[$key]) && $key !=='id') {
701
                    $results[$k][$key] = (is_array($entryData[$key]))?implode(', ', $entryData[$key]):$entryData[$key];
702
                } elseif (array_key_exists($key, $entry)) {
703
                    $results[$k][$key] = ($entry[$key] instanceof \DateTime)?$entry[$key]->format('Y-m-d'):$entry[$key];
704
                } else {
705
                    $results[$k][$key] = '';
706
                }
707
708
                foreach ($postElements as $e) {
709
                    if ($key === $e->getName()) {
710
                        $results[$k][$key] = (is_array($e->getValue()))?implode(', ', $e->getValue()):$e->getValue();
711
                        break;
712
                    }
713
                }
714
715
                if ($key === 'votes') {
716
                    $results[$k][$key] = count($entry[0]->getVotes());
717
                    break;
718
                }
719
            }
720
        }
721
722
        return $results;
723
    }
724
725
    public function getPostVoteFormMapper()
726
    {
727
        if (null === $this->postvoteformMapper) {
728
            $this->postvoteformMapper = $this->serviceLocator->get('playgroundgame_postvoteform_mapper');
729
        }
730
731
        return $this->postvoteformMapper;
732
    }
733
734
    public function setPostVoteFormMapper($postvoteformMapper)
735
    {
736
        $this->postvoteformMapper = $postvoteformMapper;
737
738
        return $this;
739
    }
740
741
    public function getPostVotePostElementMapper()
742
    {
743
        if (null === $this->postVotePostElementMapper) {
744
            $this->postVotePostElementMapper = $this->serviceLocator->get(
745
                'playgroundgame_postvotepostelement_mapper'
746
            );
747
        }
748
749
        return $this->postVotePostElementMapper;
750
    }
751
752
    public function setPostVotePostElementMapper($postVotePostElementMapper)
753
    {
754
        $this->postVotePostElementMapper = $postVotePostElementMapper;
755
756
        return $this;
757
    }
758
759
    public function getPostVoteVoteMapper()
760
    {
761
        if (null === $this->postVoteVoteMapper) {
762
            $this->postVoteVoteMapper = $this->serviceLocator->get('playgroundgame_postvotevote_mapper');
763
        }
764
765
        return $this->postVoteVoteMapper;
766
    }
767
768
    public function setPostVoteVoteMapper($postVoteVoteMapper)
769
    {
770
        $this->postVoteVoteMapper = $postVoteVoteMapper;
771
772
        return $this;
773
    }
774
775
    public function getPostVoteCommentMapper()
776
    {
777
        if (null === $this->postVoteCommentMapper) {
778
            $this->postVoteCommentMapper = $this->serviceLocator->get('playgroundgame_postvotecomment_mapper');
779
        }
780
781
        return $this->postVoteCommentMapper;
782
    }
783
784
    public function setPostVoteCommentMapper($postVoteCommentMapper)
785
    {
786
        $this->postVoteCommentMapper = $postVoteCommentMapper;
787
788
        return $this;
789
    }
790
791
    public function getPostVotePostMapper()
792
    {
793
        if (null === $this->postVotePostMapper) {
794
            $this->postVotePostMapper = $this->serviceLocator->get('playgroundgame_postvotepost_mapper');
795
        }
796
797
        return $this->postVotePostMapper;
798
    }
799
800
    public function setPostVotePostMapper($postVotePostMapper)
801
    {
802
        $this->postVotePostMapper = $postVotePostMapper;
803
804
        return $this;
805
    }
806
807
    public function getPostVoteMapper()
808
    {
809
        if (null === $this->postvoteMapper) {
810
            $this->postvoteMapper = $this->serviceLocator->get('playgroundgame_postvote_mapper');
811
        }
812
813
        return $this->postvoteMapper;
814
    }
815
816
    /**
817
     * setQuizQuestionMapper
818
     *
819
     * @return PostVote
820
     */
821
    public function setPostVoteMapper($postvoteMapper)
822
    {
823
        $this->postvoteMapper = $postvoteMapper;
824
825
        return $this;
826
    }
827
}
828