BadgeCompletionController::giveAction()   B
last analyzed

Complexity

Conditions 6
Paths 8

Size

Total Lines 70
Code Lines 42

Duplication

Lines 30
Ratio 42.86 %

Importance

Changes 0
Metric Value
dl 30
loc 70
rs 8.5454
c 0
b 0
f 0
cc 6
eloc 42
nc 8
nop 1

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 Badger\Bundle\GameBundle\Event\BadgeUnlockEvent;
6
use Badger\Bundle\GameBundle\GameEvents;
7
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
8
use Symfony\Component\HttpFoundation\RedirectResponse;
9
use Symfony\Component\HttpFoundation\Request;
10
use Symfony\Component\HttpFoundation\Response;
11
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
12
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
13
14
/**
15
 * @author  Adrien Pétremann <[email protected]>
16
 * @license http://opensource.org/licenses/MIT The MIT License (MIT)
17
 */
18
class BadgeCompletionController extends Controller
19
{
20
    /**
21
     * Lists all pending badge completions.
22
     *
23
     * @return Response
24
     */
25 View Code Duplication
    public function indexAction()
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...
26
    {
27
        $pendingCompletions = $this->get('badger.game.repository.badge_completion')
28
            ->findBy(['pending' => 1]);
29
30
        return $this->render('@Game/claimed-badges/index.html.twig', [
31
            'pendingCompletions' => $pendingCompletions
32
        ]);
33
    }
34
35
    /**
36
     * Reject a badge completion by removing it from the database.
37
     *
38
     * @param string $id
39
     *
40
     * @return RedirectResponse
41
     */
42
    public function rejectAction($id)
43
    {
44
        $pendingCompletion = $this->get('badger.game.repository.badge_completion')
45
            ->findOneBy(['id' => $id, 'pending' => 1]);
46
47
        if (null === $pendingCompletion) {
48
            throw new NotFoundHttpException(sprintf('No pending BadgeCompletion entity with id %s', $id));
49
        }
50
51
        $badgeTitle = $pendingCompletion->getBadge()->getTitle();
52
        $username = $pendingCompletion->getUser()->getUsername();
53
54
        $badgeCompletionRemover = $this->get('badger.game.remover.badge_completion');
55
        $badgeCompletionRemover->remove($pendingCompletion);
56
57
        $event = new BadgeUnlockEvent($pendingCompletion);
58
        $this->get('event_dispatcher')->dispatch(GameEvents::BADGE_HAS_BEEN_REJECTED, $event);
59
60
        $this->addFlash('notice', sprintf(
61
            'Successfully rejected the claimed badge "%s" for %s!',
62
            $badgeTitle,
63
            $username
64
        ));
65
66
        return $this->redirectToRoute('admin_claimed_badge_index');
67
    }
68
69
    /**
70
     * Accept a badge completion.
71
     *
72
     * @param string $id
73
     *
74
     * @return RedirectResponse
75
     */
76
    public function acceptAction($id)
77
    {
78
        $pendingCompletion = $this->get('badger.game.repository.badge_completion')
79
            ->findOneBy(['id' => $id, 'pending' => 1]);
80
81
        if (null === $pendingCompletion) {
82
            throw new NotFoundHttpException(sprintf('No pending BadgeCompletion entity with id %s', $id));
83
        }
84
85
        $user = $pendingCompletion->getUser();
86
        $badge = $pendingCompletion->getBadge();
87
88
        $pendingCompletion->setPending(false);
89
        $pendingCompletion->setCompletionDate(new \DateTime());
90
91
        $errors = $this->get('validator')->validate($pendingCompletion);
92
93 View Code Duplication
        if (0 === count($errors)) {
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...
94
            $this->get('badger.game.saver.badge_completion')->save($pendingCompletion);
95
96
            $event = new BadgeUnlockEvent($pendingCompletion);
97
            $this->get('event_dispatcher')->dispatch(GameEvents::USER_UNLOCKED_BADGE, $event);
98
99
            $this->addFlash('notice', sprintf(
100
                '%s successfully unlocked the badge "%s"!',
101
                $user->getUsername(),
102
                $badge->getTitle()
103
            ));
104
        } else {
105
            $this->addFlash('error', (string) $errors);
106
        }
107
108
        return $this->redirectToRoute('admin_claimed_badge_index');
109
    }
110
111
    /**
112
     * Give a badge to a user directly by creating a completed badge completion.
113
     *
114
     * @param Request $request
115
     *
116
     * @return Response
117
     */
118
    public function giveAction(Request $request)
119
    {
120
        $badgeRepository = $this->get('badger.game.repository.badge');
121
122
        if ('POST' === $request->getMethod()) {
123
            $validator = $this->get('validator');
124
125
            $user = $this->get('fos_user.user_manager')->findUserByUsername($request->get('user'));
126
            $badge = $badgeRepository->find($request->get('badge'));
127
128
            $token = new UsernamePasswordToken($user, 'none', 'none', $user->getRoles());
129
            $isUnlockable = $this->get('security.access.public_decision_manager')->decide($token, ['view'], $badge);
130
131 View Code Duplication
            if (!$isUnlockable) {
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...
132
                $this->addFlash(
133
                    'error',
134
                    sprintf('%s does not have access to badge "%s"', $user->getUsername(), $badge->getTitle())
135
                );
136
137
                return $this->redirectToRoute('admin_unlocked_badge_give');
138
            }
139
140
            $badgeCompletion = $this->get('badger.game.repository.badge_completion')
141
                ->findOneBy([
142
                    'user' => $user,
143
                    'badge' => $badge
144
                ]);
145
146
            if (null === $badgeCompletion) {
147
                $badgeCompletion = $this->get('badger.game.badge_completion.factory')->create($user, $badge);
148
            }
149
150 View Code Duplication
            if (!$badgeCompletion->isPending()) {
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...
151
                $this->addFlash(
152
                    'error',
153
                    sprintf('%s already has the badge "%s"', $user->getUsername(), $badge->getTitle())
154
                );
155
156
                return $this->redirectToRoute('admin_unlocked_badge_give');
157
            }
158
159
            $badgeCompletion->setPending(false);
160
            $badgeCompletion->setCompletionDate(new \DateTime());
161
162
            $errors = $validator->validate($badgeCompletion);
163
164 View Code Duplication
            if (0 === count($errors)) {
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...
165
                $this->get('badger.game.saver.badge_completion')->save($badgeCompletion);
166
167
                $event = new BadgeUnlockEvent($badgeCompletion);
168
                $this->get('event_dispatcher')->dispatch(GameEvents::USER_UNLOCKED_BADGE, $event);
169
170
                $this->addFlash('notice', sprintf(
171
                    '%s successfully received the badge "%s"!',
172
                    $user->getUsername(),
173
                    $badge->getTitle()
174
                ));
175
            } else {
176
                $this->addFlash('error', (string) $errors);
177
            }
178
        }
179
180
        $badges = $badgeRepository->findAll();
181
        $usernames = $this->get('badger.user.repository.user')->getAllUsernames();
182
183
        return $this->render('@Game/unlocked-badges/give.html.twig', [
184
            'badges' => json_encode($badges),
185
            'users'  => json_encode($usernames)
186
        ]);
187
    }
188
189
    /**
190
     * Remove a badge from a user by removing the badge completion.
191
     *
192
     * @param Request $request
193
     *
194
     * @return Response
195
     */
196
    public function removeAction(Request $request)
197
    {
198
        $badgeRepository = $this->get('badger.game.repository.badge');
199
200
        if ('POST' === $request->getMethod()) {
201
            $user = $this->container->get('fos_user.user_manager')->findUserByUsername($request->get('user'));
202
            $badge = $badgeRepository->findOneById($request->get('badge'));
203
204
            $badgeCompletion = $this->get('badger.game.repository.badge_completion')
205
                ->findOneBy([
206
                    'user' => $user,
207
                    'badge' => $badge,
208
                    'pending' => false
209
                ]);
210
211 View Code Duplication
            if (null === $badgeCompletion) {
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...
212
                $this->addFlash(
213
                    'error',
214
                    sprintf('%s has no badge named "%s"', $user->getUsername(), $badge->getTitle())
215
                );
216
217
                return $this->redirectToRoute('admin_unlocked_badge_remove');
218
            }
219
220
            $badgeCompletionRemover = $this->get('badger.game.remover.badge_completion');
221
            $badgeCompletionRemover->remove($badgeCompletion);
222
223
            $event = new BadgeUnlockEvent($badgeCompletion);
224
            $this->get('event_dispatcher')->dispatch(GameEvents::BADGE_HAS_BEEN_REMOVED, $event);
225
226
            $this->addFlash('notice', sprintf(
227
                'Successfully removed the badge "%s" to the user "%s"!',
228
                $badge->getTitle(),
229
                $user->getUsername()
230
            ));
231
        }
232
233
        $badges = $badgeRepository->findAll();
234
        $usernames = $this->get('badger.user.repository.user')->getAllUsernames();
235
236
        return $this->render('@Game/unlocked-badges/remove.html.twig', [
237
            'badges' => json_encode($badges),
238
            'users'  => json_encode($usernames)
239
        ]);
240
    }
241
}
242