Completed
Push — develop ( 5dae5d...f6975e )
by greg
02:34
created

PostVote::moderatePost()   C

Complexity

Conditions 11
Paths 9

Size

Total Lines 68

Duplication

Lines 32
Ratio 47.06 %

Importance

Changes 0
Metric Value
dl 32
loc 68
rs 6.5515
c 0
b 0
f 0
cc 11
nc 9
nop 2

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
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
        $entry = $post->getEntry();
286
        $game = $post->getPostvote();
287
288
        if ($status && strtolower($status) === 'validation') {
289
            $post->setStatus(2);
290
            $this->getPostVotePostMapper()->update($post);
291
292
            $this->getEventManager()->trigger(
293
                __FUNCTION__ .'.validation',
294
                $this,
295
                array('user' => $post->getUser(), 'game' => $game, 'entry' => $entry, 'post' => $post)
296
            );
297
298 View Code Duplication
            if ($game->getMailModerationValidated()) {
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...
299
                $from = $this->getOptions()->getEmailFromAddress();
300
                if ($entry->getAnonymousIdentifier()) {
301
                    $to = $entry->getAnonymousIdentifier();
302
                } elseif ($post->getUser()) {
303
                    $to = $post->getUser()->getEmail();
304
                }
305
                $subject = $game->getMailModerationValidatedSubject();
306
                $data = [
307
                    'game' => $game,
308
                    'user' => $post->getUser(),
309
                    'entry' => $entry,
310
                    'content' => $game->getMailModerationValidatedBlock(),
311
                ];
312
                $this->mail($from, $to, $subject, 'moderation-validated', $data);
0 ignored issues
show
Bug introduced by
The variable $to does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
313
            }
314
        } elseif ($status && strtolower($status) === 'rejection') {
315
            // We reject the $post
316
            $post->setStatus(9);
317
            $this->getPostVotePostMapper()->update($post);
318
319
            // We signal we want to remove the initial points earned from the $post
320
            $entry->setPoints(-$entry->getPoints());
321
322
            $this->getEventManager()->trigger(
323
                __FUNCTION__ .'.rejection',
324
                $this,
325
                array('user' => $post->getUser(), 'game' => $game, 'entry' => $entry, 'post' => $post)
326
            );
327
328
            // We set the points from the $entry to 0;
329
            $entry->setPoints(0);
330
            $entryMapper = $this->getEntryMapper();
331
            $entryMapper->update($entry);
332
333 View Code Duplication
            if ($game->getMailModerationRejected()) {
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...
334
                $from = $this->getOptions()->getEmailFromAddress();
335
                if ($entry->getAnonymousIdentifier()) {
336
                    $to = $entry->getAnonymousIdentifier();
337
                } elseif ($post->getUser()) {
338
                    $to = $post->getUser()->getEmail();
339
                }
340
                $subject = $game->getMailModerationRejectedSubject();
341
                $data = [
342
                    'game' => $game,
343
                    'user' => $post->getUser(),
344
                    'entry' => $entry,
345
                    'content' => $game->getMailModerationRejectedBlock(),
346
                ];
347
                $this->mail($from, $to, $subject, 'moderation-rejected', $data);
348
            }
349
        }
350
    }
351
352
    /**
353
     *
354
     * This service is ready for all types of games
355
     *
356
     * @param  array                  $data
357
     * @return \PlaygroundGame\Entity\Game
358
     */
359 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...
360
    {
361
        $title ='';
362
        $description = '';
363
364
        if ($data['form_jsonified']) {
365
            $jsonPV = json_decode($data['form_jsonified']);
366
            foreach ($jsonPV as $element) {
367
                if ($element->form_properties) {
368
                    $attributes  = $element->form_properties[0];
369
                    $title       = $attributes->title;
370
                    $description = $attributes->description;
371
372
                    break;
373
                }
374
            }
375
        }
376
        if (!$form) {
377
            $form = new \PlaygroundGame\Entity\PostVoteForm();
378
        }
379
        $form->setPostvote($game);
380
        $form->setTitle($title);
381
        $form->setDescription($description);
382
        $form->setForm($data['form_jsonified']);
383
        $form->setFormTemplate($data['form_template']);
384
385
        $form = $this->getPostVoteFormMapper()->insert($form);
386
387
        return $form;
388
    }
389
390
    public function findArrayOfValidatedPosts($game, $user, $filter, $search = '')
391
    {
392
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
393
        $qb = $em->createQueryBuilder();
394
        $and = $qb->expr()->andx();
395
396
        $and->add($qb->expr()->eq('p.status', 2));
397
398
        $and->add($qb->expr()->eq('g.id', ':game'));
399
        $qb->setParameter('game', $game);
400
401
        if ($search != '') {
402
            $and->add(
403
                $qb->expr()->orX(
404
                    $qb->expr()->like('u.username', $qb->expr()->literal('%:search%')),
405
                    $qb->expr()->like('u.firstname', $qb->expr()->literal('%:search%')),
406
                    $qb->expr()->like('u.lastname', $qb->expr()->literal('%:search%')),
407
                    $qb->expr()->like('e.value', $qb->expr()->literal('%:search%')),
408
                    $qb->expr()->isNull('g.publicationDate')
409
                )
410
            );
411
            $qb->setParameter('search', $search);
412
        }
413
414
        if ('push' == $filter) {
415
            $and->add(
416
                $qb->expr()->andX(
417
                    $qb->expr()->eq('p.pushed', 1)
418
                )
419
            );
420
        }
421
422
        $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')
423
            ->from('PlaygroundGame\Entity\PostVotePost', 'p')
424
            ->innerJoin('p.postvote', 'g')
425
            ->leftJoin('p.user', 'u')
426
            ->innerJoin('p.postElements', 'e')
427
            ->leftJoin('p.votes', 'v')
428
            ->leftJoin('p.votes', 'av', 'WITH', 'av.user = :user')
429
            ->where($and)
430
            ->groupBy('p.id');
431
432
        if ($user) {
433
            $qb->setParameter('user', $user);
434
        } else {
435
            $qb->setParameter('user', null);
436
        }
437
438
        switch ($filter) {
439
            case 'random':
440
                $qb->orderBy('e.value', 'ASC');
441
                break;
442
            case 'vote':
443
                $qb->orderBy('votesCount', 'DESC');
444
                break;
445
            case 'date':
446
                $qb->orderBy('p.createdAt', 'DESC');
447
                break;
448
            case 'push':
449
                $qb->orderBy('p.createdAt', 'DESC');
450
                break;
451
            case 'id':
452
                $qb->orderBy('p.createdAt', 'ASC');
453
                break;
454
            default:
455
                $qb->orderBy('p.createdAt', 'ASC');
456
                break;
457
        }
458
459
        $query = $qb->getQuery();
460
        // echo $query->getSql();
461
        $posts = $query->getResult();
462
        $arrayPosts = array();
463
        $i=0;
464
        foreach ($posts as $postRaw) {
465
            $data = array();
466
            $post = $postRaw[0];
467
            if ($post) {
468
                foreach ($post->getPostElements() as $element) {
469
                    $data[$element->getPosition()] = $element->getValue();
470
                }
471
                $arrayPosts[$i]['post']  = $post;
472
                $arrayPosts[$i]['data']  = $data;
473
                $arrayPosts[$i]['votes'] = count($post->getVotes());
474
                $arrayPosts[$i]['voted'] = $postRaw['voted'];
475
                $arrayPosts[$i]['votesCount'] = $postRaw['votesCount'];
476
                $arrayPosts[$i]['id']    = $post->getId();
477
                $arrayPosts[$i]['user']  = $post->getUser();
478
                $arrayPosts[$i]['createdAt']  = $post->getCreatedAt();
479
                $i++;
480
            }
481
        }
482
483
        return $arrayPosts;
484
    }
485
486
    public function toggleVote($user, $ipAddress, $post, $comment = null, $note = 1)
487
    {
488
        $postvoteVoteMapper = $this->getPostVoteVoteMapper();
489
        $postId = $post->getId();
490
        $commentId = ($comment !== null) ? $comment->getId() : null;
491
        $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...
492
        $game = $post->getPostvote();
493
494
        if ($user) {
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
                $entryUser = count($postvoteVoteMapper->findBy(array('user' => $user, 'post' => $postId, 'postComment' => null)));
497
                $vote = $postvoteVoteMapper->findOneBy(array('user' => $user, 'post' => $postId, 'postComment' => null));
498
            } else {
499
                $entryUser = count($postvoteVoteMapper->findBy(array('user' => $user, 'post' => $postId, 'postComment' => $commentId)));
500
                $vote = $postvoteVoteMapper->findOneBy(array('user' => $user, 'post' => $postId, 'postComment' => $commentId));
501
            }
502 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...
503
            if ($comment == null) {
504
                $entryUser = count($postvoteVoteMapper->findBy(array('ip' => $ipAddress, 'post' => $postId, 'postComment' => null)));
505
                $vote = $postvoteVoteMapper->findOneBy(array('ip' => $ipAddress, 'post' => $postId, 'postComment' => null));
506
            } else {
507
                $entryUser = count($postvoteVoteMapper->findBy(array('ip' => $ipAddress, 'post' => $postId, 'postComment' => $commentId)));
508
                $vote = $postvoteVoteMapper->findOneBy(array('ip' => $ipAddress, 'post' => $postId, 'postComment' => $commentId));
509
            }
510
        }
511
512
        if ($entryUser && $entryUser > 0) {
513
            $postvoteVoteMapper->remove($vote);
514
515
            return 0;
516
        } else {
517
            $vote = new \PlaygroundGame\Entity\PostVoteVote();
518
            $vote->setPost($post);
519
            $vote->setIp($ipAddress);
520
            $vote->setNote($note);
521
            // If the vote is for a comment
522 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...
523
                $vote->setPostComment($comment);
524
                $vote->setPostvote($post->getPostvote());
525
            // else if the vote is for the post itself
526
            } else {
527
                $vote->setPostvote($post->getPostvote(), true);
528
            }
529
530
            if ($user) {
531
                $vote->setUser($user);
532
            }
533
534
            $postvoteVoteMapper->insert($vote);
535
        }
536
537
        $this->getEventManager()->trigger(
538
            __FUNCTION__ .'.post',
539
            $this,
540
            array('user' => $user, 'game' => $game, 'post' => $post, 'vote' => $vote)
541
        );
542
543
        return 1;
544
    }
545
546
    public function removeVote($user, $ipAddress, $post)
547
    {
548
        $postvoteVoteMapper = $this->getPostVoteVoteMapper();
549
        $postId = $post->getId();
550
        $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...
551
        $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...
552
        $game = $post->getPostvote();
553
554 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...
555
            if ($comment == null) {
556
                $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...
557
                $vote = $postvoteVoteMapper->findOneBy(array('user' => $user, 'post' => $postId));
558
            } else {
559
                $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...
560
                $vote = $postvoteVoteMapper->findOneBy(array('user' => $user, 'post' => $postId, 'postComment' => $commentId));
561
            }
562
        } else {
563
            if ($comment == null) {
564
                $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...
565
                $vote = $postvoteVoteMapper->findOneBy(array('ip' => $ipAddress, 'post' => $postId));
566
            } else {
567
                $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...
568
                $vote = $postvoteVoteMapper->findOneBy(array('ip' => $ipAddress, 'post' => $postId, 'postComment' => $commentId));
569
            }
570
        }
571
572
        $this->getEventManager()->trigger(
573
            __FUNCTION__ .'.post',
574
            $this,
575
            array('user' => $user, 'game' => $game, 'post' => $post, 'vote' => $vote)
576
        );
577
578
        return true;
579
    }
580
581
    public function addVote($user, $ipAddress, $post)
582
    {
583
        $postvoteVoteMapper = $this->getPostVoteVoteMapper();
584
        $postId = $post->getId();
585
        $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...
586
        $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...
587
        $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...
588
589 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...
590
            if ($comment == null) {
591
                $entryUser = count($postvoteVoteMapper->findBy(array('user' => $user, 'post' => $postId)));
592
                $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...
593
            } else {
594
                $entryUser = count($postvoteVoteMapper->findBy(array('user' => $user, 'post' => $postId, 'postComment' => $commentId)));
595
                $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...
596
            }
597
        } else {
598
            if ($comment == null) {
599
                $entryUser = count($postvoteVoteMapper->findBy(array('ip' => $ipAddress, 'post' => $postId)));
600
                $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...
601
            } else {
602
                $entryUser = count($postvoteVoteMapper->findBy(array('ip' => $ipAddress, 'post' => $postId, 'postComment' => $commentId)));
603
                $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...
604
            }
605
        }
606
607
        if ($entryUser && $entryUser > 0) {
608
            return false;
609
        } else {
610
            $vote = new \PlaygroundGame\Entity\PostVoteVote();
611
            $vote->setPost($post);
612
            $vote->setIp($ipAddress);
613
            $vote->setNote(1);
614
            // If the vote is for a comment
615 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...
616
                $vote->setPostComment($comment);
617
                $vote->setPostvote($post->getPostvote());
618
            // else if the vote is for the post itself
619
            } else {
620
                $vote->setPostvote($post->getPostvote(), true);
621
            }
622
            if ($user) {
623
                $vote->setUser($user);
624
            }
625
626
            $postvoteVoteMapper->insert($vote);
627
            $game = $post->getPostvote();
628
            $this->getEventManager()->trigger(
629
                __FUNCTION__ .'.post',
630
                $this,
631
                array('user' => $user, 'game' => $game, 'post' => $post, 'vote' => $vote)
632
            );
633
634
            return true;
635
        }
636
    }
637
638
    public function addComment($user, $ipAddress, $post, $message = '', $category = null)
639
    {
640
        $postvoteCommentMapper = $this->getPostVoteCommentMapper();
641
        $game = $post->getPostvote();
642
        $comment = new \PlaygroundGame\Entity\PostVoteComment();
643
        $comment->setPost($post);
644
        $comment->setIp($ipAddress);
645
        $message = strip_tags($message);
646
        $comment->setMessage($message);
647
        if ($category !== null) {
648
            $comment->setCategory($category);
649
        }
650
        $comment->setPostvote($game);
651
        if ($user) {
652
            $comment->setUser($user);
653
        }
654
655
        $postvoteCommentMapper->insert($comment);
656
657
        $this->getEventManager()->trigger(
658
            __FUNCTION__ .'.post',
659
            $this,
660
            array('user' => $user, 'game' => $game, 'post' => $post, 'comment' => $comment)
661
        );
662
663
        return true;
664
    }
665
666 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...
667
    {
668
        $postvoteViewMapper = $this->getPostVoteViewMapper();
669
        $postView = new \PlaygroundGame\Entity\PostVoteView();
670
        $postView->setPost($post)
671
            ->setPostvote($post->getPostvote())
672
            ->setUser($user)
673
            ->setIp($ipAddress);
674
        $postvoteViewMapper->insert($postView);
675
676
        $this->getEventManager()->trigger(
677
            __FUNCTION__ . '.post',
678
            $this,
679
            array(
680
                'post' => $post
681
            )
682
        );
683
684
        return true;
685
    }
686
687 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...
688
    {
689
        $postvoteShareMapper = $this->getPostVoteShareMapper();
690
        $postShare = new \PlaygroundGame\Entity\PostVoteShare();
691
        $postShare->setPost($post)
692
            ->setPostvote($post->getPostvote())
693
            ->setUser($user)
694
            ->setOrigin('mail');
695
        $postvoteShareMapper->insert($postShare);
696
697
        $this->getEventManager()->trigger(
698
            __FUNCTION__ . '.post',
699
            $this,
700
            array(
701
                'post' => $post
702
            )
703
        );
704
705
        return true;
706
    }
707
708
    /**
709
     * Get all comments for this game
710
     */
711
    public function getCommentsForPostvote($postvote)
712
    {
713
        $postvoteCommentMapper = $this->getPostVoteCommentMapper();
714
        $comments = $postvoteCommentMapper->findBy(array('postvote' => $postvote), array('createdAt' => 'DESC'));
715
716
        return $comments ;
717
    }
718
719
    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...
720
    {
721
        $postvoteCommentMapper = $this->getPostVoteCommentMapper();
722
        $comment = $postvoteCommentMapper->findOneBy(array('id' => $messageId));
723
        if ($comment->getUser()->getId() === $user->getId()) {
724
            $postvoteCommentMapper->remove($comment);
725
            $this->getEventManager()->trigger(
726
                'remove_comment_postvote.post',
727
                $this,
728
                array('user' => $user, 'comment' => $comment)
729
            );
730
731
            return true;
732
        }
733
734
        return false;
735
    }
736
737
    /**
738
     * DEPRECATED
739
     */
740
    public function getEntriesHeader($game)
741
    {
742
        $header = parent::getEntriesHeader($game);
743
        if ($game->getForm()) {
744
            $form = json_decode($game->getForm()->getForm(), true);
745 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...
746
                foreach ($element as $k => $v) {
747
                    if ($k !== 'form_properties') {
748
                        $header[$v[0]['name']] = 1;
749
                    }
750
                }
751
            }
752
        }
753
        if ($game->getVoteActive()) {
754
            $header['p.votes'] = 1;
755
        }
756
757
        $header['p.views'] = 1;
758
        $header['p.shares'] = 1;
759
760
        return $header;
761
    }
762
763
    public function getGrid($game)
764
    {
765
        $qb = $this->getEntriesQuery($game);
766
        // echo $qb->getQuery()->getSQL();
767
        // die('---');
768
769
        /* @var $grid \ZfcDatagrid\Datagrid */
770
        $grid = $this->serviceLocator->get('ZfcDatagrid\Datagrid');
771
        $grid->setTitle('Entries');
772
        $grid->setDataSource($qb);
773
        $grid->setDefaultItemsPerPage(50);
774
775
        $col = new Column\Select('id', 'p');
776
        $col->setLabel('Id');
777
        $col->setIdentity(true);
778
        $grid->addColumn($col);
779
780
        $colType = new Type\DateTime(
781
            'Y-m-d H:i:s',
782
            \IntlDateFormatter::MEDIUM,
783
            \IntlDateFormatter::MEDIUM
784
        );
785
        $colType->setSourceTimezone('UTC');
786
787
        $col = new Column\Select('created_at', 'u');
788
        $col->setLabel('Created');
789
        $col->setType($colType);
790
        $grid->addColumn($col);
791
792
        // $col = new Column\Select('username', 'u');
793
        // $col->setLabel('Username');
794
        // $grid->addColumn($col);
795
796
        $col = new Column\Select('email', 'u');
797
        $col->setLabel('Email');
798
        $grid->addColumn($col);
799
800
        $col = new Column\Select('firstname', 'u');
801
        $col->setLabel('Firstname');
802
        $grid->addColumn($col);
803
804
        $col = new Column\Select('lastname', 'u');
805
        $col->setLabel('Lastname');
806
        $grid->addColumn($col);
807
808
        // $col = new Column\Select('winner', 'e');
809
        // $col->setLabel('Status');
810
        // $col->setReplaceValues(
811
        //     [
812
        //         0 => 'looser',
813
        //         1 => 'winner',
814
        //     ]
815
        // );
816
        // $grid->addColumn($col);
817
818
        $imageFormatter = new Formatter\Image();
819
        //Set the prefix of the image path and the prefix of the link
820
        $imageFormatter->setPrefix('/');
821
        $imageFormatter->setAttribute('width', '120');
822
        $imageFormatter->setLinkAttribute('class', 'pop');
823
824
        if ($game->getForm()) {
825
            $form = json_decode($game->getForm()->getForm(), true);
826
            foreach ($form as $element) {
827
                foreach ($element as $k => $v) {
828
                    if ($k !== 'form_properties') {
829
                        $querySelect = new Expr\Select("MAX(CASE WHEN f.name = '".$v[0]['name']."' THEN f.value ELSE '' END)");
830
                        if ($v[0]['type'] == 'file') {
831
                            // print_r($v[0]['data']['fileextension']);
832
                            // die('---');
833
                            $col = new Column\Select($querySelect, $v[0]['name']);
834
                            //$col->setType(new Type\Image());
835 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...
836
                                $col->addFormatter($imageFormatter);
837
                            }
838 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...
839
                                $col->addFormatter(new Formatter\Link());
840
                            }
841 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...
842
                                $col->addFormatter(new Formatter\Link());
843
                            }
844
                        } else {
845
                            $col = new Column\Select($querySelect, $v[0]['name']);
846
                        }
847
                        $col->setLabel($v[0]['data']['label']);
848
                        $col->setUserFilterDisabled(true);
849
                        $grid->addColumn($col);
850
                    }
851
                }
852
            }
853
        }
854
855
        if ($game->getVoteActive()) {
856
            $querySelect = new Expr\Select("COUNT(vo.id)");
857
            $col = new Column\Select($querySelect, "votes");
858
            $col->setLabel("Votes");
859
            $col->setUserFilterDisabled(true);
860
            $grid->addColumn($col);
861
        }
862
863
        $querySelect = new Expr\Select("COUNT(v.id)");
864
        $col = new Column\Select($querySelect, "views");
865
        $col->setLabel("Views");
866
        $col->setUserFilterDisabled(true);
867
        $grid->addColumn($col);
868
869
        // $querySelect = new Expr\Select("COUNT(s.id)");
870
        // $col = new Column\Select($querySelect, "shares");
871
        // $col->setLabel("Shares");
872
        // $col->setUserFilterDisabled(true);
873
        // $grid->addColumn($col);
874
875
        /**
876
         * values :
877
         *          0 : draft
878
         *          1 : user confirmed
879
         *          2 : admin accepted
880
         *          8 : user rejected
881
         *          9 : admin rejected
882
         */
883
        $col = new Column\Select('status', 'p');
884
        $col->setLabel('Moderation');
885
        $col->setReplaceValues(
886
            [
887
                0 => 'Draft',
888
                1 => 'Pending',
889
                2 => 'Validated',
890
                8 => 'Canceled by the player',
891
                9 => 'Rejected',
892
            ]
893
        );
894
        $grid->addColumn($col);
895
896
        $actions = new Column\Action();
897
        $actions->setLabel('');
898
899
        $viewAction = new Column\Action\Button();
900
        $viewAction->setLabel('Moderate');
901
        $rowId = $viewAction->getRowIdPlaceholder();
902
        $viewAction->setLink('/admin/game/postvote-moderation-edit/'.$rowId);
903
        $actions->addAction($viewAction);
904
905
        $grid->addColumn($actions);
906
907
        // $action = new Action\Mass();
908
        // $action->setTitle('This is incredible');
909
        // $action->setLink('/admin/game/postvote-mod-list');
910
        // $action->setConfirm(true);
911
        // $grid->addMassAction($action);
912
913
        return $grid;
914
    }
915
916
    public function getEntriesQuery($game)
917
    {
918
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
919
920
        $qb = $em->createQueryBuilder();
921
922
        $selectString = '';
923
924
        if ($game->getForm()) {
925
            $form = json_decode($game->getForm()->getForm(), true);
926
            foreach ($form as $element) {
927
                foreach ($element as $k => $v) {
928
                    if ($k !== 'form_properties') {
929
                        $selectString .= "MAX(CASE WHEN f.name = '".$v[0]['name']."' THEN f.value ELSE '' END) AS " .$v[0]['name']. ",";
930
                    }
931
                }
932
            }
933
        }
934
        $selectString .= 'p, u, e';
935
        $qb->select($selectString)
936
            ->from('PlaygroundGame\Entity\PostVotePost', 'p')
937
            ->leftJoin('p.votes', 'vo')
938
            ->leftJoin('p.shares', 's')
939
            ->leftJoin('p.views', 'v')
940
            ->innerJoin('p.postElements', 'f')
941
            ->innerJoin('p.entry', 'e')
942
            ->leftJoin('p.user', 'u')
943
            ->where($qb->expr()->eq('e.game', ':game'))
944
            ->groupBy('p.id');
945
946
        $qb->setParameter('game', $game);
947
948
        return $qb;
949
    }
950
951
    /**
952
     * DEPRECATED
953
     * getGameEntries : All entries of a game
954
     *
955
     * @return Array of PlaygroundGame\Entity\Game
956
     */
957
    public function getGameEntries($header, $entries, $game)
958
    {
959
        $results = array();
960
961
        foreach ($entries as $k => $entry) {
962
            $entryData = json_decode($entry['playerData'], true);
963
            $postElements = $entry[0]->getPostElements();
964
965
            foreach ($header as $key => $v) {
966
                if (isset($entryData[$key]) && $key !=='id') {
967
                    $results[$k][$key] = (is_array($entryData[$key]))?implode(', ', $entryData[$key]):$entryData[$key];
968
                } elseif (array_key_exists($key, $entry)) {
969
                    $results[$k][$key] = ($entry[$key] instanceof \DateTime)?$entry[$key]->format('Y-m-d'):$entry[$key];
970
                } else {
971
                    $results[$k][$key] = '';
972
                }
973
974
                foreach ($postElements as $e) {
975
                    if ($key === $e->getName()) {
976
                        $results[$k][$key] = (is_array($e->getValue()))?implode(', ', $e->getValue()):$e->getValue();
977
                        break;
978
                    }
979
                }
980
981
                if ($key === 'votes') {
982
                    $results[$k][$key] = count($entry[0]->getVotes());
983
                }
984
                if ($key === 'views') {
985
                    $results[$k][$key] = count($entry[0]->getViews());
986
                }
987
                if ($key === 'shares') {
988
                    $results[$k][$key] = count($entry[0]->getShares());
989
                }
990
            }
991
        }
992
993
        return $results;
994
    }
995
996
    public function getPostVoteFormMapper()
997
    {
998
        if (null === $this->postvoteformMapper) {
999
            $this->postvoteformMapper = $this->serviceLocator->get('playgroundgame_postvoteform_mapper');
1000
        }
1001
1002
        return $this->postvoteformMapper;
1003
    }
1004
1005
    public function setPostVoteFormMapper($postvoteformMapper)
1006
    {
1007
        $this->postvoteformMapper = $postvoteformMapper;
1008
1009
        return $this;
1010
    }
1011
1012
    public function getPostVotePostElementMapper()
1013
    {
1014
        if (null === $this->postVotePostElementMapper) {
1015
            $this->postVotePostElementMapper = $this->serviceLocator->get(
1016
                'playgroundgame_postvotepostelement_mapper'
1017
            );
1018
        }
1019
1020
        return $this->postVotePostElementMapper;
1021
    }
1022
1023
    public function setPostVotePostElementMapper($postVotePostElementMapper)
1024
    {
1025
        $this->postVotePostElementMapper = $postVotePostElementMapper;
1026
1027
        return $this;
1028
    }
1029
1030
    public function getPostVoteVoteMapper()
1031
    {
1032
        if (null === $this->postVoteVoteMapper) {
1033
            $this->postVoteVoteMapper = $this->serviceLocator->get('playgroundgame_postvotevote_mapper');
1034
        }
1035
1036
        return $this->postVoteVoteMapper;
1037
    }
1038
1039
    public function setPostVoteVoteMapper($postVoteVoteMapper)
1040
    {
1041
        $this->postVoteVoteMapper = $postVoteVoteMapper;
1042
1043
        return $this;
1044
    }
1045
1046
    public function getPostVoteCommentMapper()
1047
    {
1048
        if (null === $this->postVoteCommentMapper) {
1049
            $this->postVoteCommentMapper = $this->serviceLocator->get('playgroundgame_postvotecomment_mapper');
1050
        }
1051
1052
        return $this->postVoteCommentMapper;
1053
    }
1054
1055
    public function setPostVoteCommentMapper($postVoteCommentMapper)
1056
    {
1057
        $this->postVoteCommentMapper = $postVoteCommentMapper;
1058
1059
        return $this;
1060
    }
1061
1062
    public function getPostVotePostMapper()
1063
    {
1064
        if (null === $this->postVotePostMapper) {
1065
            $this->postVotePostMapper = $this->serviceLocator->get('playgroundgame_postvotepost_mapper');
1066
        }
1067
1068
        return $this->postVotePostMapper;
1069
    }
1070
1071
    public function getPostVoteShareMapper()
1072
    {
1073
        if (null === $this->postVoteShareMapper) {
1074
            $this->postVoteShareMapper = $this->serviceLocator->get('playgroundgame_postvoteshare_mapper');
1075
        }
1076
1077
        return $this->postVoteShareMapper;
1078
    }
1079
1080
    public function getPostVoteViewMapper()
1081
    {
1082
        if (null === $this->postVoteViewMapper) {
1083
            $this->postVoteViewMapper = $this->serviceLocator->get('playgroundgame_postvoteview_mapper');
1084
        }
1085
1086
        return $this->postVoteViewMapper;
1087
    }
1088
1089
    public function setPostVotePostMapper($postVotePostMapper)
1090
    {
1091
        $this->postVotePostMapper = $postVotePostMapper;
1092
1093
        return $this;
1094
    }
1095
1096
    public function getPostVoteMapper()
1097
    {
1098
        if (null === $this->postvoteMapper) {
1099
            $this->postvoteMapper = $this->serviceLocator->get('playgroundgame_postvote_mapper');
1100
        }
1101
1102
        return $this->postvoteMapper;
1103
    }
1104
1105
    /**
1106
     * setQuizQuestionMapper
1107
     *
1108
     * @return PostVote
1109
     */
1110
    public function setPostVoteMapper($postvoteMapper)
1111
    {
1112
        $this->postvoteMapper = $postvoteMapper;
1113
1114
        return $this;
1115
    }
1116
}
1117