Completed
Push — master ( faea8c...2382d1 )
by greg
04:56 queued 02:27
created

PostVote::moderatePost()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 41

Duplication

Lines 0
Ratio 0 %

Importance

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

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

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

Loading history...
476
            if ($comment == null) {
477
                $entryUser = count($postvoteVoteMapper->findBy(array('ip' => $ipAddress, 'post' => $postId, 'postComment' => null)));
478
                $vote = $postvoteVoteMapper->findOneBy(array('ip' => $ipAddress, 'post' => $postId, 'postComment' => null));
479
            } else {
480
                $entryUser = count($postvoteVoteMapper->findBy(array('ip' => $ipAddress, 'post' => $postId, 'postComment' => $commentId)));
481
                $vote = $postvoteVoteMapper->findOneBy(array('ip' => $ipAddress, 'post' => $postId, 'postComment' => $commentId));
482
            }
483
        }
484
485
        if ($entryUser && $entryUser > 0) {
486
            $postvoteVoteMapper->remove($vote);
487
488
            return 0;
489
        } else {
490
            $vote = new \PlaygroundGame\Entity\PostVoteVote();
491
            $vote->setPost($post);
492
            $vote->setIp($ipAddress);
493
            $vote->setNote($note);
494
            // If the vote is for a comment
495 View Code Duplication
            if ($comment != null) {
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...
496
                $vote->setPostComment($comment);
497
                $vote->setPostvote($post->getPostvote());
498
            // else if the vote is for the post itself
499
            } else {
500
                $vote->setPostvote($post->getPostvote(), true);
501
            }
502
503
            if ($user) {
504
                $vote->setUser($user);
505
            }
506
507
            $postvoteVoteMapper->insert($vote);
508
        }
509
510
        $this->getEventManager()->trigger(
511
            __FUNCTION__ .'.post',
512
            $this,
513
            array('user' => $user, 'game' => $game, 'post' => $post, 'vote' => $vote)
514
        );
515
516
        return 1;
517
    }
518
519
    public function removeVote($user, $ipAddress, $post)
520
    {
521
        $postvoteVoteMapper = $this->getPostVoteVoteMapper();
522
        $postId = $post->getId();
523
        $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...
524
        $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...
525
        $game = $post->getPostvote();
526
527 View Code Duplication
        if ($user) {
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...
528
            if ($comment == null) {
529
                $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...
530
                $vote = $postvoteVoteMapper->findOneBy(array('user' => $user, 'post' => $postId));
531
            } else {
532
                $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...
533
                $vote = $postvoteVoteMapper->findOneBy(array('user' => $user, 'post' => $postId, 'postComment' => $commentId));
534
            }
535
        } else {
536
            if ($comment == null) {
537
                $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...
538
                $vote = $postvoteVoteMapper->findOneBy(array('ip' => $ipAddress, 'post' => $postId));
539
            } else {
540
                $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...
541
                $vote = $postvoteVoteMapper->findOneBy(array('ip' => $ipAddress, 'post' => $postId, 'postComment' => $commentId));
542
            }
543
        }
544
545
        $this->getEventManager()->trigger(
546
            __FUNCTION__ .'.post',
547
            $this,
548
            array('user' => $user, 'game' => $game, 'post' => $post, 'vote' => $vote)
549
        );
550
551
        return true;
552
    }
553
554
    public function addVote($user, $ipAddress, $post)
555
    {
556
        $postvoteVoteMapper = $this->getPostVoteVoteMapper();
557
        $postId = $post->getId();
558
        $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...
559
        $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...
560
        $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...
561
562 View Code Duplication
        if ($user) {
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...
563
            if ($comment == null) {
564
                $entryUser = count($postvoteVoteMapper->findBy(array('user' => $user, 'post' => $postId)));
565
                $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...
566
            } else {
567
                $entryUser = count($postvoteVoteMapper->findBy(array('user' => $user, 'post' => $postId, 'postComment' => $commentId)));
568
                $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...
569
            }
570
        } else {
571
            if ($comment == null) {
572
                $entryUser = count($postvoteVoteMapper->findBy(array('ip' => $ipAddress, 'post' => $postId)));
573
                $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...
574
            } else {
575
                $entryUser = count($postvoteVoteMapper->findBy(array('ip' => $ipAddress, 'post' => $postId, 'postComment' => $commentId)));
576
                $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...
577
            }
578
        }
579
580
        if ($entryUser && $entryUser > 0) {
581
            return false;
582
        } else {
583
            $vote = new \PlaygroundGame\Entity\PostVoteVote();
584
            $vote->setPost($post);
585
            $vote->setIp($ipAddress);
586
            $vote->setNote(1);
587
            // If the vote is for a comment
588 View Code Duplication
            if ($comment != null) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
589
                $vote->setPostComment($comment);
590
                $vote->setPostvote($post->getPostvote());
591
            // else if the vote is for the post itself
592
            } else {
593
                $vote->setPostvote($post->getPostvote(), true);
594
            }
595
            if ($user) {
596
                $vote->setUser($user);
597
            }
598
599
            $postvoteVoteMapper->insert($vote);
600
            $game = $post->getPostvote();
601
            $this->getEventManager()->trigger(
602
                __FUNCTION__ .'.post',
603
                $this,
604
                array('user' => $user, 'game' => $game, 'post' => $post, 'vote' => $vote)
605
            );
606
607
            return true;
608
        }
609
    }
610
611
    public function addComment($user, $ipAddress, $post, $message = '', $category = null)
612
    {
613
        $postvoteCommentMapper = $this->getPostVoteCommentMapper();
614
        $game = $post->getPostvote();
615
        $comment = new \PlaygroundGame\Entity\PostVoteComment();
616
        $comment->setPost($post);
617
        $comment->setIp($ipAddress);
618
        $message = strip_tags($message);
619
        $comment->setMessage($message);
620
        if ($category !== null) {
621
            $comment->setCategory($category);
622
        }
623
        $comment->setPostvote($game);
624
        if ($user) {
625
            $comment->setUser($user);
626
        }
627
628
        $postvoteCommentMapper->insert($comment);
629
630
        $this->getEventManager()->trigger(
631
            __FUNCTION__ .'.post',
632
            $this,
633
            array('user' => $user, 'game' => $game, 'post' => $post, 'comment' => $comment)
634
        );
635
636
        return true;
637
    }
638
639 View Code Duplication
    public function addView($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...
640
    {
641
        $postvoteViewMapper = $this->getPostVoteViewMapper();
642
        $postView = new \PlaygroundGame\Entity\PostVoteView();
643
        $postView->setPost($post)
644
            ->setPostvote($post->getPostvote())
645
            ->setUser($user)
646
            ->setIp($ipAddress);
647
        $postvoteViewMapper->insert($postView);
648
649
        $this->getEventManager()->trigger(
650
            __FUNCTION__ . '.post',
651
            $this,
652
            array(
653
                'post' => $post
654
            )
655
        );
656
657
        return true;
658
    }
659
660 View Code Duplication
    public function addShare($post, $user)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
661
    {
662
        $postvoteShareMapper = $this->getPostVoteShareMapper();
663
        $postShare = new \PlaygroundGame\Entity\PostVoteShare();
664
        $postShare->setPost($post)
665
            ->setPostvote($post->getPostvote())
666
            ->setUser($user)
667
            ->setOrigin('mail');
668
        $postvoteShareMapper->insert($postShare);
669
670
        $this->getEventManager()->trigger(
671
            __FUNCTION__ . '.post',
672
            $this,
673
            array(
674
                'post' => $post
675
            )
676
        );
677
678
        return true;
679
    }
680
681
    /**
682
     * Get all comments for this game
683
     */
684
    public function getCommentsForPostvote($postvote)
685
    {
686
        $postvoteCommentMapper = $this->getPostVoteCommentMapper();
687
        $comments = $postvoteCommentMapper->findBy(array('postvote' => $postvote), array('createdAt' => 'DESC'));
688
689
        return $comments ;
690
    }
691
692
    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...
693
    {
694
        $postvoteCommentMapper = $this->getPostVoteCommentMapper();
695
        $comment = $postvoteCommentMapper->findOneBy(array('id' => $messageId));
696
        if ($comment->getUser()->getId() === $user->getId()) {
697
            $postvoteCommentMapper->remove($comment);
698
            $this->getEventManager()->trigger(
699
                'remove_comment_postvote.post',
700
                $this,
701
                array('user' => $user, 'comment' => $comment)
702
            );
703
704
            return true;
705
        }
706
707
        return false;
708
    }
709
710
    /**
711
     * DEPRECATED
712
     */
713
    public function getEntriesHeader($game)
714
    {
715
        $header = parent::getEntriesHeader($game);
716
        if ($game->getForm()) {
717
            $form = json_decode($game->getForm()->getForm(), true);
718 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...
719
                foreach ($element as $k => $v) {
720
                    if ($k !== 'form_properties') {
721
                        $header[$v[0]['name']] = 1;
722
                    }
723
                }
724
            }
725
        }
726
        if ($game->getVoteActive()) {
727
            $header['p.votes'] = 1;
728
        }
729
730
        $header['p.views'] = 1;
731
        $header['p.shares'] = 1;
732
733
        return $header;
734
    }
735
736
    public function getGrid($game)
737
    {
738
        $qb = $this->getEntriesQuery($game);
739
        // echo $qb->getQuery()->getSQL();
740
        // die('---');
741
742
        /* @var $grid \ZfcDatagrid\Datagrid */
743
        $grid = $this->serviceLocator->get('ZfcDatagrid\Datagrid');
744
        $grid->setTitle('Entries');
745
        $grid->setDataSource($qb);
746
        $grid->setDefaultItemsPerPage(50);
747
748
        $col = new Column\Select('id', 'p');
749
        $col->setLabel('Id');
750
        $col->setIdentity(true);
751
        $grid->addColumn($col);
752
753
        $colType = new Type\DateTime(
754
            'Y-m-d H:i:s',
755
            \IntlDateFormatter::MEDIUM,
756
            \IntlDateFormatter::MEDIUM
757
        );
758
        $colType->setSourceTimezone('UTC');
759
760
        $col = new Column\Select('created_at', 'u');
761
        $col->setLabel('Created');
762
        $col->setType($colType);
763
        $grid->addColumn($col);
764
765
        // $col = new Column\Select('username', 'u');
766
        // $col->setLabel('Username');
767
        // $grid->addColumn($col);
768
769
        $col = new Column\Select('email', 'u');
770
        $col->setLabel('Email');
771
        $grid->addColumn($col);
772
773
        $col = new Column\Select('firstname', 'u');
774
        $col->setLabel('Firstname');
775
        $grid->addColumn($col);
776
777
        $col = new Column\Select('lastname', 'u');
778
        $col->setLabel('Lastname');
779
        $grid->addColumn($col);
780
781
        // $col = new Column\Select('winner', 'e');
782
        // $col->setLabel('Status');
783
        // $col->setReplaceValues(
784
        //     [
785
        //         0 => 'looser',
786
        //         1 => 'winner',
787
        //     ]
788
        // );
789
        // $grid->addColumn($col);
790
791
        $imageFormatter = new Formatter\Image();
792
        //Set the prefix of the image path and the prefix of the link
793
        $imageFormatter->setPrefix('/');
794
        $imageFormatter->setAttribute('width', '120');
795
        $imageFormatter->setLinkAttribute('class', 'pop');
796
797
        if ($game->getForm()) {
798
            $form = json_decode($game->getForm()->getForm(), true);
799
            foreach ($form as $element) {
800
                foreach ($element as $k => $v) {
801
                    if ($k !== 'form_properties') {
802
                        $querySelect = new Expr\Select("MAX(CASE WHEN f.name = '".$v[0]['name']."' THEN f.value ELSE '' END)");
803
                        if ($v[0]['type'] == 'file') {
804
                            // print_r($v[0]['data']['fileextension']);
805
                            // die('---');
806
                            $col = new Column\Select($querySelect, $v[0]['name']);
807
                            //$col->setType(new Type\Image());
808 View Code Duplication
                            if (strpos($v[0]['data']['fileextension'], 'png') !== false) {
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...
809
                                $col->addFormatter($imageFormatter);
810
                            }
811 View Code Duplication
                            if (strpos($v[0]['data']['fileextension'], 'mp4') !== false) {
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...
812
                                $col->addFormatter(new Formatter\Link());
813
                            }
814 View Code Duplication
                            if (strpos($v[0]['data']['fileextension'], 'pdf') !== false) {
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...
815
                                $col->addFormatter(new Formatter\Link());
816
                            }
817
                        } else {
818
                            $col = new Column\Select($querySelect, $v[0]['name']);
819
                        }
820
                        $col->setLabel($v[0]['data']['label']);
821
                        $col->setUserFilterDisabled(true);
822
                        $grid->addColumn($col);
823
                    }
824
                }
825
            }
826
        }
827
828
        if ($game->getVoteActive()) {
829
            $querySelect = new Expr\Select("COUNT(vo.id)");
830
            $col = new Column\Select($querySelect, "votes");
831
            $col->setLabel("Votes");
832
            $col->setUserFilterDisabled(true);
833
            $grid->addColumn($col);
834
        }
835
836
        $querySelect = new Expr\Select("COUNT(v.id)");
837
        $col = new Column\Select($querySelect, "views");
838
        $col->setLabel("Views");
839
        $col->setUserFilterDisabled(true);
840
        $grid->addColumn($col);
841
842
        // $querySelect = new Expr\Select("COUNT(s.id)");
843
        // $col = new Column\Select($querySelect, "shares");
844
        // $col->setLabel("Shares");
845
        // $col->setUserFilterDisabled(true);
846
        // $grid->addColumn($col);
847
848
        /**
849
         * values :
850
         *          0 : draft
851
         *          1 : user confirmed
852
         *          2 : admin accepted
853
         *          8 : user rejected
854
         *          9 : admin rejected
855
         */
856
        $col = new Column\Select('status', 'p');
857
        $col->setLabel('Moderation');
858
        $col->setReplaceValues(
859
            [
860
                0 => 'Draft',
861
                1 => 'Pending',
862
                2 => 'Validated',
863
                8 => 'Canceled by the player',
864
                9 => 'Rejected',
865
            ]
866
        );
867
        $grid->addColumn($col);
868
869
        $actions = new Column\Action();
870
        $actions->setLabel('');
871
872
        $viewAction = new Column\Action\Button();
873
        $viewAction->setLabel('Moderate');
874
        $rowId = $viewAction->getRowIdPlaceholder();
875
        $viewAction->setLink('/admin/game/postvote-moderation-edit/'.$rowId);
876
        $actions->addAction($viewAction);
877
878
        $grid->addColumn($actions);
879
880
        // $action = new Action\Mass();
881
        // $action->setTitle('This is incredible');
882
        // $action->setLink('/admin/game/postvote-mod-list');
883
        // $action->setConfirm(true);
884
        // $grid->addMassAction($action);
885
886
        return $grid;
887
    }
888
889
    public function getEntriesQuery($game)
890
    {
891
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
892
893
        $qb = $em->createQueryBuilder();
894
895
        $selectString = '';
896
897
        if ($game->getForm()) {
898
            $form = json_decode($game->getForm()->getForm(), true);
899
            foreach ($form as $element) {
900
                foreach ($element as $k => $v) {
901
                    if ($k !== 'form_properties') {
902
                        $selectString .= "MAX(CASE WHEN f.name = '".$v[0]['name']."' THEN f.value ELSE '' END) AS " .$v[0]['name']. ",";
903
                    }
904
                }
905
            }
906
        }
907
        $selectString .= 'p, u, e';
908
        $qb->select($selectString)
909
            ->from('PlaygroundGame\Entity\PostVotePost', 'p')
910
            ->leftJoin('p.votes', 'vo')
911
            ->leftJoin('p.shares', 's')
912
            ->leftJoin('p.views', 'v')
913
            ->innerJoin('p.postElements', 'f')
914
            ->innerJoin('p.entry', 'e')
915
            ->leftJoin('p.user', 'u')
916
            ->where($qb->expr()->eq('e.game', ':game'))
917
            ->groupBy('p.id');
918
919
        $qb->setParameter('game', $game);
920
921
        return $qb;
922
    }
923
924
    /**
925
     * DEPRECATED
926
     * getGameEntries : All entries of a game
927
     *
928
     * @return Array of PlaygroundGame\Entity\Game
929
     */
930
    public function getGameEntries($header, $entries, $game)
931
    {
932
        $results = array();
933
934
        foreach ($entries as $k => $entry) {
935
            $entryData = json_decode($entry['playerData'], true);
936
            $postElements = $entry[0]->getPostElements();
937
938
            foreach ($header as $key => $v) {
939
                if (isset($entryData[$key]) && $key !=='id') {
940
                    $results[$k][$key] = (is_array($entryData[$key]))?implode(', ', $entryData[$key]):$entryData[$key];
941
                } elseif (array_key_exists($key, $entry)) {
942
                    $results[$k][$key] = ($entry[$key] instanceof \DateTime)?$entry[$key]->format('Y-m-d'):$entry[$key];
943
                } else {
944
                    $results[$k][$key] = '';
945
                }
946
947
                foreach ($postElements as $e) {
948
                    if ($key === $e->getName()) {
949
                        $results[$k][$key] = (is_array($e->getValue()))?implode(', ', $e->getValue()):$e->getValue();
950
                        break;
951
                    }
952
                }
953
954
                if ($key === 'votes') {
955
                    $results[$k][$key] = count($entry[0]->getVotes());
956
                }
957
                if ($key === 'views') {
958
                    $results[$k][$key] = count($entry[0]->getViews());
959
                }
960
                if ($key === 'shares') {
961
                    $results[$k][$key] = count($entry[0]->getShares());
962
                }
963
            }
964
        }
965
966
        return $results;
967
    }
968
969
    public function getPostVoteFormMapper()
970
    {
971
        if (null === $this->postvoteformMapper) {
972
            $this->postvoteformMapper = $this->serviceLocator->get('playgroundgame_postvoteform_mapper');
973
        }
974
975
        return $this->postvoteformMapper;
976
    }
977
978
    public function setPostVoteFormMapper($postvoteformMapper)
979
    {
980
        $this->postvoteformMapper = $postvoteformMapper;
981
982
        return $this;
983
    }
984
985
    public function getPostVotePostElementMapper()
986
    {
987
        if (null === $this->postVotePostElementMapper) {
988
            $this->postVotePostElementMapper = $this->serviceLocator->get(
989
                'playgroundgame_postvotepostelement_mapper'
990
            );
991
        }
992
993
        return $this->postVotePostElementMapper;
994
    }
995
996
    public function setPostVotePostElementMapper($postVotePostElementMapper)
997
    {
998
        $this->postVotePostElementMapper = $postVotePostElementMapper;
999
1000
        return $this;
1001
    }
1002
1003
    public function getPostVoteVoteMapper()
1004
    {
1005
        if (null === $this->postVoteVoteMapper) {
1006
            $this->postVoteVoteMapper = $this->serviceLocator->get('playgroundgame_postvotevote_mapper');
1007
        }
1008
1009
        return $this->postVoteVoteMapper;
1010
    }
1011
1012
    public function setPostVoteVoteMapper($postVoteVoteMapper)
1013
    {
1014
        $this->postVoteVoteMapper = $postVoteVoteMapper;
1015
1016
        return $this;
1017
    }
1018
1019
    public function getPostVoteCommentMapper()
1020
    {
1021
        if (null === $this->postVoteCommentMapper) {
1022
            $this->postVoteCommentMapper = $this->serviceLocator->get('playgroundgame_postvotecomment_mapper');
1023
        }
1024
1025
        return $this->postVoteCommentMapper;
1026
    }
1027
1028
    public function setPostVoteCommentMapper($postVoteCommentMapper)
1029
    {
1030
        $this->postVoteCommentMapper = $postVoteCommentMapper;
1031
1032
        return $this;
1033
    }
1034
1035
    public function getPostVotePostMapper()
1036
    {
1037
        if (null === $this->postVotePostMapper) {
1038
            $this->postVotePostMapper = $this->serviceLocator->get('playgroundgame_postvotepost_mapper');
1039
        }
1040
1041
        return $this->postVotePostMapper;
1042
    }
1043
1044
    public function getPostVoteShareMapper()
1045
    {
1046
        if (null === $this->postVoteShareMapper) {
1047
            $this->postVoteShareMapper = $this->serviceLocator->get('playgroundgame_postvoteshare_mapper');
1048
        }
1049
1050
        return $this->postVoteShareMapper;
1051
    }
1052
1053
    public function getPostVoteViewMapper()
1054
    {
1055
        if (null === $this->postVoteViewMapper) {
1056
            $this->postVoteViewMapper = $this->serviceLocator->get('playgroundgame_postvoteview_mapper');
1057
        }
1058
1059
        return $this->postVoteViewMapper;
1060
    }
1061
1062
    public function setPostVotePostMapper($postVotePostMapper)
1063
    {
1064
        $this->postVotePostMapper = $postVotePostMapper;
1065
1066
        return $this;
1067
    }
1068
1069
    public function getPostVoteMapper()
1070
    {
1071
        if (null === $this->postvoteMapper) {
1072
            $this->postvoteMapper = $this->serviceLocator->get('playgroundgame_postvote_mapper');
1073
        }
1074
1075
        return $this->postvoteMapper;
1076
    }
1077
1078
    /**
1079
     * setQuizQuestionMapper
1080
     *
1081
     * @return PostVote
1082
     */
1083
    public function setPostVoteMapper($postvoteMapper)
1084
    {
1085
        $this->postvoteMapper = $postvoteMapper;
1086
1087
        return $this;
1088
    }
1089
}
1090