Completed
Push — master ( 557b3f...cc4751 )
by Adrien
12s
created

DefaultController::claimBadgeAction()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 29
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 29
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 16
nc 4
nop 1
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
        $date = new \DateTime();
26
27
        // Put default tag first
28
        usort($userTags, function ($a, $b)
29
        {
30
            if ($a->isDefault()) {
31
                return -1;
32
            } else if($b->isDefault()) {
33
                return 1;
34
            }
35
        });
36
37
        // Get most unlocked badges & champions per tag
38
        foreach ($userTags as $tag) {
39
            $currentUserIsChampion = false;
40
41
            $mostUnlockedBadges[$tag->getCode()] = $this->get('badger.game.repository.badge_completion')
42
                ->getMostUnlockedBadgesForDate($date, $tag, 5);
43
44
            $maxBadgeCompletions = $this->get('badger.game.repository.badge_completion')
45
                ->getTopNumberOfUnlocksForDate($date, $tag);
46
47
            $champions = $this->get('badger.user.repository.user')
48
                ->getMonthlyBadgeChampions($date, $tag, $maxBadgeCompletions);
49
50
            foreach ($champions as $champion) {
51
                if ($champion['user']->getId() === $this->getUser()->getId()) {
52
                    $currentUserIsChampion = true;
53
                }
54
55
                $badgeChampions[$tag->getCode()][$champion['badgeCompletions']][] = $champion['user'];
56
            }
57
58
            if (!$currentUserIsChampion) {
59
                $userCompletions = $this->get('badger.game.repository.badge_completion')
60
                    ->getTopNumberOfUnlocksForDate($date, $tag, $this->getUser());
61
62
                if (!empty($userCompletions)) {
63
                    $userBadgeCompletions[$tag->getCode()] = current($userCompletions)['nbCompletions'];
64
                }
65
            }
66
67
        }
68
69
        $newMembers = $this->get('badger.user.repository.user')->getNewUsersForMonth($date);
70
71
        return $this->render('@Game/home.html.twig', [
72
            'newMembers'           => $newMembers,
73
            'mostUnlockedBadges'   => $mostUnlockedBadges,
74
            'userTags'             => $userTags,
75
            'badgeChampions'       => $badgeChampions,
76
            'userBadgeCompletions' => $userBadgeCompletions
77
        ]);
78
    }
79
80
    /**
81
     * @Route("/users", name="users")
82
     */
83
    public function usersAction()
84
    {
85
        $users = $this->getDoctrine()->getRepository('UserBundle:User')->findAll();
86
87
        return $this->render('@Game/users.html.twig', [
88
            'users' => $users
89
        ]);
90
    }
91
92
    /**
93
     * @Route("/admin", name="admin")
94
     */
95
    public function adminAction()
96
    {
97
        return $this->render('@Game/base-admin.html.twig');
98
    }
99
100
    /**
101
     * @Route("/user/{username}", name="userprofile")
102
     * @param string $username
103
     *
104
     * @return Response
105
     */
106
    public function userProfileAction($username)
107
    {
108
        $user = $this->getDoctrine()->getRepository('UserBundle:User')->findOneBy([
109
            'username' => $username
110
        ]);
111
112
        $badgeCompletions = [];
113
114
        if ($user) {
115
            $badgeCompletions = $this->get('badger.game.repository.badge_completion')->findBy([
116
                'user' => $user, 'pending' => '0'
117
            ]);
118
119
            foreach ($badgeCompletions as $key => $badgeCompletion) {
120
                if (!$this->get('security.authorization_checker')->isGranted('view', $badgeCompletion->getBadge())) {
121
                    unset($badgeCompletions[$key]);
122
                }
123
            }
124
        }
125
126
        $displayedTags = $user->getTags();
127
128
        foreach ($displayedTags as $key => $userTag) {
129
            if (!$this->get('security.authorization_checker')->isGranted('view', $userTag)) {
130
                unset($displayedTags[$key]);
131
            }
132
        }
133
134
        return $this->render('@Game/user-profile.html.twig', [
135
            'user'             => $user,
136
            'badgeCompletions' => $badgeCompletions
137
        ]);
138
    }
139
140
    /**
141
     * @Route("/badge/{id}", name="viewbadge")
142
     * @param $id
143
     *
144
     * @return Response
145
     */
146
    public function badgeViewAction($id)
147
    {
148
        $badge = $this->get('badger.game.repository.badge')->findOneBy([
149
            'id' => $id
150
        ]);
151
152
        if (null === $badge || !$this->get('security.authorization_checker')->isGranted('view', $badge)) {
153
            throw $this->createNotFoundException();
154
        }
155
156
        $badgeCompletions = $this->get('badger.game.repository.badge_completion')->findBy([
157
            'badge' => $badge,
158
            'pending' => '0'
159
        ]);
160
161
        $isUnlocked = false;
162
        $isClaimed = false;
163
164
        $userCompletion = $this->get('badger.game.repository.badge_completion')->findOneBy([
165
            'user' => $this->getUser(),
166
            'badge' => $badge
167
        ]);
168
169
        if (null !== $userCompletion) {
170
            $isClaimed = $userCompletion->isPending();
171
            $isUnlocked = !$userCompletion->isPending();
172
        }
173
174
        return $this->render('@Game/view-badge.html.twig', [
175
            'badge'            => $badge,
176
            'badgeCompletions' => $badgeCompletions,
177
            'isUnlocked'       => $isUnlocked,
178
            'isClaimed'        => $isClaimed
179
        ]);
180
    }
181
182
    /**
183
     * @Route("/claim/badge/{id}", name="claimbadge")
184
     * @param int $id
185
     *
186
     * @return JsonResponse
187
     */
188
    public function claimBadgeAction($id)
189
    {
190
        $user = $this->getUser();
191
        $badge = $this->get('badger.game.repository.badge')->find($id);
192
193
        if (null === $badge) {
194
            return new JsonResponse('No badge with this id.', 400);
195
        }
196
197
        if (!$this->get('security.authorization_checker')->isGranted('view', $badge)) {
198
            return new JsonResponse('No badge with this id.', 400);
199
        }
200
201
        $claimedBadge = $this->get('badger.game.repository.badge_completion')->findOneBy([
202
            'user' => $user,
203
            'badge' => $badge
204
        ]);
205
206
        if (null !== $claimedBadge) {
207
            return new JsonResponse('This badge is already claimed.', 400);
208
        }
209
210
        $badgeCompletionFactory = $this->get('badger.game.badge_completion.factory');
211
        $badgeCompletion = $badgeCompletionFactory->create($user, $badge);
212
213
        $this->get('badger.game.saver.badge_completion')->save($badgeCompletion);
214
215
        return new JsonResponse();
216
    }
217
218
    /**
219
     * @Route("/claim/step/{id}", name="claimstep")
220
     * @param int $id
221
     *
222
     * @return JsonResponse
223
     */
224 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...
225
    {
226
        $user = $this->getUser();
227
        $step = $this->get('badger.game.repository.adventure_step')->find($id);
228
229
        if (null === $step) {
230
            return new JsonResponse('No step with this id.', 404);
231
        }
232
233
        if (!$this->get('security.authorization_checker')->isGranted('view', $step->getAdventure())) {
234
            return new JsonResponse('No step with this id.', 404);
235
        }
236
237
        $stepCompletion = $this->get('badger.game.repository.adventure_step_completion')->findOneBy([
238
            'user' => $user,
239
            'step' => $step
240
        ]);
241
242
        if (null !== $stepCompletion) {
243
            return new JsonResponse('This step is already claimed.', 400);
244
        }
245
246
        $stepCompletionFactory = $this->get('badger.game.adventure_step_completion.factory');
247
        $stepCompletion = $stepCompletionFactory->create($user, $step);
248
249
        $this->get('badger.game.saver.adventure_step_completion')->save($stepCompletion);
250
251
        return new JsonResponse();
252
    }
253
254
    /**
255
     * @Route("/claim/quest/{id}", name="claimquest")
256
     * @param int $id
257
     *
258
     * @return JsonResponse
259
     */
260 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...
261
    {
262
        $user = $this->getUser();
263
        $quest = $this->get('badger.game.repository.quest')->find($id);
264
265
        if (null === $quest) {
266
            return new JsonResponse('No quest with this id.', 400);
267
        }
268
269
        if (!$this->get('security.authorization_checker')->isGranted('view', $quest)) {
270
            return new JsonResponse('No quest with this id.', 400);
271
        }
272
273
        $questCompletion = $this->get('badger.game.repository.quest_completion')->findOneBy([
274
            'user' => $user,
275
            'quest' => $quest
276
        ]);
277
278
        if (null !== $questCompletion) {
279
            return new JsonResponse('This quest is already claimed.', 400);
280
        }
281
282
        $questCompletionFactory = $this->get('badger.game.quest_completion.factory');
283
        $questCompletion = $questCompletionFactory->create($user, $quest);
284
285
        $this->get('badger.game.saver.quest_completion')->save($questCompletion);
286
287
        return new JsonResponse();
288
    }
289
290
    /**
291
     * @Route("/badges", name="badges")
292
     *
293
     * @return Response
294
     */
295
    public function badgeListAction()
296
    {
297
        $user = $this->getUser();
298
        $userTags = $user->getTags();
299
300
        $unlockedBadgeIds = $this->get('badger.game.repository.badge_completion')
301
            ->getCompletionBadgesByUser($user, false);
302
303
        $claimedBadgeIds = $this->get('badger.game.repository.badge_completion')
304
            ->getCompletionBadgesByUser($user, true);
305
306
        return $this->render('@Game/badges.html.twig', [
307
            'tags' => $userTags,
308
            'unlockedBadgesIds' => $unlockedBadgeIds,
309
            'claimedBadgeIds' => $claimedBadgeIds
310
        ]);
311
    }
312
313
    /**
314
     * @Route("/quests", name="quests")
315
     * @param Request $request
316
     *
317
     * @return Response
318
     */
319
    public function questListAction(Request $request)
320
    {
321
        $user = $this->getUser();
322
        $status = $request->get('status', 'available');
323
324
        $questRepository = $this->get('badger.game.repository.quest');
325
        $completionRepository = $this->get('badger.game.repository.quest_completion');
326
327
        $availableQuests = $questRepository->getAvailableQuestsForUser($user);
328
        $questCompletions = $completionRepository->findBy(['user' => $user, 'pending' => 0]);
329
        $claimedQuestIds = $this->get('badger.game.repository.quest_completion')
330
            ->getQuestIdsClaimedByUser($user);
331
332
        return $this->render('@Game/quests.html.twig', [
333
            'availableQuests'      => $availableQuests,
334
            'questCompletions'     => $questCompletions,
335
            'countAvailableQuests' => count($availableQuests),
336
            'countCompletedQuests' => count($questCompletions),
337
            'claimedQuestIds'      => $claimedQuestIds,
338
            'status'               => $status
339
        ]);
340
    }
341
342
    /**
343
     * @Route("/adventures", name="adventures")
344
     *
345
     * @return Response
346
     */
347
    public function adventureListAction()
348
    {
349
        $user = $this->getUser();
350
351
        $availableAdventures = $this->get('badger.game.repository.adventure')
352
            ->getAvailableAdventuresForUser($user);
353
354
        $completedAdventures = $this->get('badger.game.repository.adventure')
355
            ->getCompletedAdventuresForUser($user);
356
357
        $completedStepsByAdventure = $this->get('badger.game.repository.adventure_step_completion')
358
            ->userCompletedSteps($user);
359
360
        foreach ($availableAdventures as $adventure) {
361
            $adventure->completed = '0';
362
363
            foreach ($completedStepsByAdventure as $data) {
364
                if ($adventure->getId() === $data['adventure']->getId()) {
365
                    $adventure->completed = $data['completions'];
366
                }
367
            }
368
        }
369
370
        return $this->render('@Game/adventures.html.twig', [
371
            'availableAdventures' => $availableAdventures,
372
            'completedAdventures' => $completedAdventures
373
        ]);
374
    }
375
376
    /**
377
     * @Route("/adventures/{id}", name="viewadventure")
378
     *
379
     * @param int $id
380
     *
381
     * @return Response
382
     */
383
    public function adventureViewAction($id)
384
    {
385
        $user = $this->getUser();
386
        $adventure = $this->get('badger.game.repository.adventure')
387
            ->find($id);
388
389
        $completedSteps = $this->get('badger.game.repository.adventure_step_completion')
390
            ->userAdventureCompletedSteps($user, $adventure);
391
392
        $claimedSteps = $this->get('badger.game.repository.adventure_step_completion')
393
            ->userAdventureClaimedSteps($user, $adventure);
394
395
        $progression = count($completedSteps) * 100 / count($adventure->getSteps());
396
397
        $totalStep = count($adventure->getSteps());
398
        $isAdventureComplete = count($completedSteps) === $totalStep;
399
400
        return $this->render('@Game/view-adventure.html.twig', [
401
            'adventure' => $adventure,
402
            'completedSteps' => $completedSteps,
403
            'claimedSteps' => $claimedSteps,
404
            'progression' => $progression,
405
            'isAdventureComplete' => $isAdventureComplete
406
        ]);
407
    }
408
409
    /**
410
     * @Route("/leaderboard", name="leaderboard")
411
     *
412
     * @return Response
413
     */
414
    public function leaderboardAction()
415
    {
416
        $users = $this->getDoctrine()->getRepository('UserBundle:User')->getSortedUserByUnlockedBadges();
417
418
        return $this->render('@Game/leaderboard.html.twig', [
419
            'users' => $users
420
        ]);
421
    }
422
423
    /**
424
     * @Route("/search/users", name="search_users")
425
     * @param Request $request
426
     *
427
     * @return JsonResponse
428
     */
429
    public function searchUsersAction(Request $request)
430
    {
431
        $token = $request->get('token');
432
433
        if ('' === trim($token)) {
434
            $users = $this->get('badger.user.repository.user')->findAll();
435
            $results = [];
436
437
            foreach ($users as $user) {
438
                $results[] = [
439
                    'username' => $user->getUsername(),
440
                    'profilePicture' => $user->getProfilePicture()
441
                ];
442
            }
443
444
            return new JsonResponse($results);
445
        }
446
447
        $results = $this->get('badger.user.repository.elastic.user')->findUser($token);
448
449
        return new JsonResponse($results);
450
    }
451
}
452