Completed
Pull Request — master (#158)
by Adrien
02:11
created

DefaultController::indexAction()   C

Complexity

Conditions 8
Paths 10

Size

Total Lines 63
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 63
rs 6.8825
c 0
b 0
f 0
cc 8
eloc 38
nc 10
nop 0

How to fix   Long Method   

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 Badger\Bundle\GameBundle\Controller;
4
5
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
6
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
7
use Symfony\Component\HttpFoundation\JsonResponse;
8
use Symfony\Component\HttpFoundation\Request;
9
use Symfony\Component\HttpFoundation\Response;
10
11
/**
12
 * @license http://opensource.org/licenses/MIT The MIT License (MIT)
13
 */
14
class DefaultController extends Controller
15
{
16
    /**
17
     * @Route("/", name="homepage")
18
     */
19
    public function indexAction()
20
    {
21
        $mostUnlockedBadges = [];
22
        $badgeChampions = [];
23
        $userBadgeCompletions = [];
24
        $userTags = $this->getUser()->getTags()->toArray();
25
26
        // Put default tag first
27
        usort($userTags, function ($a, $b)
28
        {
29
            if ($a->isDefault()) {
30
                return -1;
31
            } else if($b->isDefault()) {
32
                return 1;
33
            }
34
        });
35
36
        // Get most unlocked badges & champions per tag
37
        foreach ($userTags as $tag) {
38
            $month = date('m');
0 ignored issues
show
Unused Code introduced by
$month 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...
39
            $month = "06";
40
            $year = date('Y');
0 ignored issues
show
Unused Code introduced by
$year 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...
41
            $year = "2016";
42
            $currentUserIsChampion = false;
43
44
            $mostUnlockedBadges[$tag->getCode()] = $this->get('badger.game.repository.badge_completion')
45
                ->getMostUnlockedBadgesForMonth($month, $year, $tag, 5);
46
47
            $maxBadgeCompletions = $this->get('badger.game.repository.badge_completion')
48
                ->getTopNumberOfUnlocksForMonth($month, $year, $tag);
49
50
            $champions = $this->get('badger.user.repository.user')
51
                ->getMonthlyBadgeChampions($month, $year, $tag, $maxBadgeCompletions);
52
53
            foreach ($champions as $champion) {
54
                if ($champion['user']->getId() === $this->getUser()->getId()) {
55
                    $currentUserIsChampion = true;
56
                }
57
58
                $badgeChampions[$tag->getCode()][$champion['badgeCompletions']][] = $champion['user'];
59
            }
60
61
            if (!$currentUserIsChampion) {
62
                $userCompletions = $this->get('badger.game.repository.badge_completion')
63
                    ->getTopNumberOfUnlocksForMonth($month, $year, $tag, $this->getUser());
64
65
                if (!empty($userCompletions)) {
66
                    $userBadgeCompletions[$tag->getCode()] = current($userCompletions)['nbCompletions'];
67
                }
68
            }
69
70
        }
71
72
        $newMembers = $this->get('badger.user.repository.user')->getNewUsersForMonth($month, $year);
0 ignored issues
show
Bug introduced by
The variable $month 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...
Bug introduced by
The variable $year 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...
73
74
        return $this->render('@Game/home.html.twig', [
75
            'newMembers'           => $newMembers,
76
            'mostUnlockedBadges'   => $mostUnlockedBadges,
77
            'userTags'             => $userTags,
78
            'badgeChampions'       => $badgeChampions,
79
            'userBadgeCompletions' => $userBadgeCompletions
80
        ]);
81
    }
82
83
    /**
84
     * @Route("/users", name="users")
85
     */
86
    public function usersAction()
87
    {
88
        $users = $this->getDoctrine()->getRepository('UserBundle:User')->findAll();
89
90
        return $this->render('@Game/users.html.twig', [
91
            'users' => $users
92
        ]);
93
    }
94
95
    /**
96
     * @Route("/admin", name="admin")
97
     */
98
    public function adminAction()
99
    {
100
        return $this->render('@Game/base-admin.html.twig');
101
    }
102
103
    /**
104
     * @Route("/user/{username}", name="userprofile")
105
     * @param string $username
106
     *
107
     * @return Response
108
     */
109
    public function userProfileAction($username)
110
    {
111
        $user = $this->getDoctrine()->getRepository('UserBundle:User')->findOneBy([
112
            'username' => $username
113
        ]);
114
115
        $badgeCompletions = [];
116
117
        if ($user) {
118
            $badgeCompletions = $this->get('badger.game.repository.badge_completion')->findBy([
119
                'user' => $user, 'pending' => '0'
120
            ]);
121
122
            foreach ($badgeCompletions as $key => $badgeCompletion) {
123
                if (!$this->get('security.authorization_checker')->isGranted('view', $badgeCompletion->getBadge())) {
124
                    unset($badgeCompletions[$key]);
125
                }
126
            }
127
        }
128
129
        $displayedTags = $user->getTags();
130
131
        foreach ($displayedTags as $key => $userTag) {
132
            if (!$this->get('security.authorization_checker')->isGranted('view', $userTag)) {
133
                unset($displayedTags[$key]);
134
            }
135
        }
136
137
        return $this->render('@Game/user-profile.html.twig', [
138
            'user'             => $user,
139
            'badgeCompletions' => $badgeCompletions
140
        ]);
141
    }
142
143
    /**
144
     * @Route("/badge/{id}", name="viewbadge")
145
     * @param $id
146
     *
147
     * @return Response
148
     */
149
    public function badgeViewAction($id)
150
    {
151
        $badge = $this->get('badger.game.repository.badge')->findOneBy([
152
            'id' => $id
153
        ]);
154
155
        if (null === $badge || !$this->get('security.authorization_checker')->isGranted('view', $badge)) {
156
            throw $this->createNotFoundException();
157
        }
158
159
        $badgeCompletions = $this->get('badger.game.repository.badge_completion')->findBy([
160
            'badge' => $badge,
161
            'pending' => '0'
162
        ]);
163
164
        $isUnlocked = false;
165
        $isClaimed = false;
166
167
        $userCompletion = $this->get('badger.game.repository.badge_completion')->findOneBy([
168
            'user' => $this->getUser(),
169
            'badge' => $badge
170
        ]);
171
172
        if (null !== $userCompletion) {
173
            $isClaimed = $userCompletion->isPending();
174
            $isUnlocked = !$userCompletion->isPending();
175
        }
176
177
        return $this->render('@Game/view-badge.html.twig', [
178
            'badge'            => $badge,
179
            'badgeCompletions' => $badgeCompletions,
180
            'isUnlocked'       => $isUnlocked,
181
            'isClaimed'        => $isClaimed
182
        ]);
183
    }
184
185
    /**
186
     * @Route("/claim/badge/{id}", name="claimbadge")
187
     * @param int $id
188
     *
189
     * @return JsonResponse
190
     */
191
    public function claimBadgeAction($id)
192
    {
193
        $user = $this->getUser();
194
        $badge = $this->get('badger.game.repository.badge')->find($id);
195
196
        if (null === $badge) {
197
            return new JsonResponse('No badge with this id.', 400);
198
        }
199
200
        if (!$this->get('security.authorization_checker')->isGranted('view', $badge)) {
201
            return new JsonResponse('No badge with this id.', 400);
202
        }
203
204
        $claimedBadge = $this->get('badger.game.repository.badge_completion')->findOneBy([
205
            'user' => $user,
206
            'badge' => $badge
207
        ]);
208
209
        if (null !== $claimedBadge) {
210
            return new JsonResponse('This badge is already claimed.', 400);
211
        }
212
213
        $badgeCompletionFactory = $this->get('badger.game.badge_completion.factory');
214
        $badgeCompletion = $badgeCompletionFactory->create($user, $badge);
215
216
        $this->get('badger.game.saver.badge_completion')->save($badgeCompletion);
217
218
        return new JsonResponse();
219
    }
220
221
    /**
222
     * @Route("/claim/step/{id}", name="claimstep")
223
     * @param int $id
224
     *
225
     * @return JsonResponse
226
     */
227 View Code Duplication
    public function claimStepAction($id)
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...
228
    {
229
        $user = $this->getUser();
230
        $step = $this->get('badger.game.repository.adventure_step')->find($id);
231
232
        if (null === $step) {
233
            return new JsonResponse('No step with this id.', 404);
234
        }
235
236
        if (!$this->get('security.authorization_checker')->isGranted('view', $step->getAdventure())) {
237
            return new JsonResponse('No step with this id.', 404);
238
        }
239
240
        $stepCompletion = $this->get('badger.game.repository.adventure_step_completion')->findOneBy([
241
            'user' => $user,
242
            'step' => $step
243
        ]);
244
245
        if (null !== $stepCompletion) {
246
            return new JsonResponse('This step is already claimed.', 400);
247
        }
248
249
        $stepCompletionFactory = $this->get('badger.game.adventure_step_completion.factory');
250
        $stepCompletion = $stepCompletionFactory->create($user, $step);
251
252
        $this->get('badger.game.saver.adventure_step_completion')->save($stepCompletion);
253
254
        return new JsonResponse();
255
    }
256
257
    /**
258
     * @Route("/claim/quest/{id}", name="claimquest")
259
     * @param int $id
260
     *
261
     * @return JsonResponse
262
     */
263 View Code Duplication
    public function claimQuestAction($id)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
264
    {
265
        $user = $this->getUser();
266
        $quest = $this->get('badger.game.repository.quest')->find($id);
267
268
        if (null === $quest) {
269
            return new JsonResponse('No quest with this id.', 400);
270
        }
271
272
        if (!$this->get('security.authorization_checker')->isGranted('view', $quest)) {
273
            return new JsonResponse('No quest with this id.', 400);
274
        }
275
276
        $questCompletion = $this->get('badger.game.repository.quest_completion')->findOneBy([
277
            'user' => $user,
278
            'quest' => $quest
279
        ]);
280
281
        if (null !== $questCompletion) {
282
            return new JsonResponse('This quest is already claimed.', 400);
283
        }
284
285
        $questCompletionFactory = $this->get('badger.game.quest_completion.factory');
286
        $questCompletion = $questCompletionFactory->create($user, $quest);
287
288
        $this->get('badger.game.saver.quest_completion')->save($questCompletion);
289
290
        return new JsonResponse();
291
    }
292
293
    /**
294
     * @Route("/badges", name="badges")
295
     *
296
     * @return Response
297
     */
298
    public function badgeListAction()
299
    {
300
        $user = $this->getUser();
301
        $userTags = $user->getTags();
302
303
        $unlockedBadgeIds = $this->get('badger.game.repository.badge_completion')
304
            ->getCompletionBadgesByUser($user, false);
305
306
        $claimedBadgeIds = $this->get('badger.game.repository.badge_completion')
307
            ->getCompletionBadgesByUser($user, true);
308
309
        return $this->render('@Game/badges.html.twig', [
310
            'tags' => $userTags,
311
            'unlockedBadgesIds' => $unlockedBadgeIds,
312
            'claimedBadgeIds' => $claimedBadgeIds
313
        ]);
314
    }
315
316
    /**
317
     * @Route("/quests", name="quests")
318
     * @param Request $request
319
     *
320
     * @return Response
321
     */
322
    public function questListAction(Request $request)
323
    {
324
        $user = $this->getUser();
325
        $status = $request->get('status', 'available');
326
327
        $questRepository = $this->get('badger.game.repository.quest');
328
        $completionRepository = $this->get('badger.game.repository.quest_completion');
329
330
        $availableQuests = $questRepository->getAvailableQuestsForUser($user);
331
        $questCompletions = $completionRepository->findBy(['user' => $user, 'pending' => 0]);
332
        $claimedQuestIds = $this->get('badger.game.repository.quest_completion')
333
            ->getQuestIdsClaimedByUser($user);
334
335
        return $this->render('@Game/quests.html.twig', [
336
            'availableQuests'      => $availableQuests,
337
            'questCompletions'     => $questCompletions,
338
            'countAvailableQuests' => count($availableQuests),
339
            'countCompletedQuests' => count($questCompletions),
340
            'claimedQuestIds'      => $claimedQuestIds,
341
            'status'               => $status
342
        ]);
343
    }
344
345
    /**
346
     * @Route("/adventures", name="adventures")
347
     *
348
     * @return Response
349
     */
350
    public function adventureListAction()
351
    {
352
        $user = $this->getUser();
353
354
        $availableAdventures = $this->get('badger.game.repository.adventure')
355
            ->getAvailableAdventuresForUser($user);
356
357
        $completedAdventures = $this->get('badger.game.repository.adventure')
358
            ->getCompletedAdventuresForUser($user);
359
360
        $completedStepsByAdventure = $this->get('badger.game.repository.adventure_step_completion')
361
            ->userCompletedSteps($user);
362
363
        foreach ($availableAdventures as $adventure) {
364
            $adventure->completed = '0';
365
366
            foreach ($completedStepsByAdventure as $data) {
367
                if ($adventure->getId() === $data['adventure']->getId()) {
368
                    $adventure->completed = $data['completions'];
369
                }
370
            }
371
        }
372
373
        return $this->render('@Game/adventures.html.twig', [
374
            'availableAdventures' => $availableAdventures,
375
            'completedAdventures' => $completedAdventures
376
        ]);
377
    }
378
379
    /**
380
     * @Route("/adventures/{id}", name="viewadventure")
381
     *
382
     * @param int $id
383
     *
384
     * @return Response
385
     */
386
    public function adventureViewAction($id)
387
    {
388
        $user = $this->getUser();
389
        $adventure = $this->get('badger.game.repository.adventure')
390
            ->find($id);
391
392
        $completedSteps = $this->get('badger.game.repository.adventure_step_completion')
393
            ->userAdventureCompletedSteps($user, $adventure);
394
395
        $claimedSteps = $this->get('badger.game.repository.adventure_step_completion')
396
            ->userAdventureClaimedSteps($user, $adventure);
397
398
        $progression = count($completedSteps) * 100 / count($adventure->getSteps());
399
400
        $totalStep = count($adventure->getSteps());
401
        $isAdventureComplete = count($completedSteps) === $totalStep;
402
403
        return $this->render('@Game/view-adventure.html.twig', [
404
            'adventure' => $adventure,
405
            'completedSteps' => $completedSteps,
406
            'claimedSteps' => $claimedSteps,
407
            'progression' => $progression,
408
            'isAdventureComplete' => $isAdventureComplete
409
        ]);
410
    }
411
412
    /**
413
     * @Route("/leaderboard", name="leaderboard")
414
     *
415
     * @return Response
416
     */
417
    public function leaderboardAction()
418
    {
419
        $users = $this->getDoctrine()->getRepository('UserBundle:User')->getSortedUserByUnlockedBadges();
420
421
        return $this->render('@Game/leaderboard.html.twig', [
422
            'users' => $users
423
        ]);
424
    }
425
426
    /**
427
     * @Route("/search/users", name="search_users")
428
     * @param Request $request
429
     *
430
     * @return JsonResponse
431
     */
432
    public function searchUsersAction(Request $request)
433
    {
434
        $token = $request->get('token');
435
436
        if ('' === trim($token)) {
437
            $users = $this->get('badger.user.repository.user')->findAll();
438
            $results = [];
439
440
            foreach ($users as $user) {
441
                $results[] = [
442
                    'username' => $user->getUsername(),
443
                    'profilePicture' => $user->getProfilePicture()
444
                ];
445
            }
446
447
            return new JsonResponse($results);
448
        }
449
450
        $results = $this->get('badger.user.repository.elastic.user')->findUser($token);
451
452
        return new JsonResponse($results);
453
    }
454
}
455