UserController::unblockAction()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
3
namespace SumoCoders\FrameworkUserBundle\Controller;
4
5
use SumoCoders\FrameworkUserBundle\Entity\User;
6
use SumoCoders\FrameworkUserBundle\Form\OtherUserType;
7
use SumoCoders\FrameworkUserBundle\Form\OwnUserType;
8
use SumoCoders\FrameworkUserBundle\Form\UserType;
9
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
10
use Symfony\Component\HttpFoundation\Request;
11
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
12
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
13
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
14
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
15
16
class UserController extends Controller
0 ignored issues
show
Deprecated Code introduced by
The class Symfony\Bundle\Framework...e\Controller\Controller has been deprecated with message: since Symfony 4.2, use {@see AbstractController} instead.

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
17
{
18
    /**
19
     * Show an overview of all the users
20
     *
21
     * @Route("/")
22
     * @Method({"GET"})
23
     * @Template()
24
     */
25
    public function indexAction()
26
    {
27
        /** @var $userManager \SumoCoders\FrameworkUserBundle\Model\FrameworkUserManager */
28
        $userManager = $this->container->get('fos_user.user_manager');
29
        $users = $userManager->findUsers();
30
31
        /** @var $paginator \Knp\Component\Pager\Paginator */
32
        $paginator = $this->get('knp_paginator');
33
        $paginatedUsers = $paginator->paginate(
34
            $users,
35
            $this->get('request_stack')->getCurrentRequest()->query->get('page', 1)
36
        );
37
38
        return array(
39
            'dgUsers' => $paginatedUsers,
40
        );
41
    }
42
43
    /**
44
     * Add a user
45
     *
46
     * @Route("/new")
47
     * @Method({"GET|POST"})
48
     * @Template()
49
     *
50
     * @param Request $request
51
     * @return array
52
     */
53
    public function newAction(Request $request)
54
    {
55
        // fix the breadCrumb
56
        $this->get('framework.breadcrumb_builder')
57
            ->extractItemsBasedOnUri(
58
                $this->generateUrl('sumocoders_frameworkuser_user_index'),
59
                $request->getLocale()
60
            )
61
            ->addSimpleItem(
62
                'user.breadcrumb.new',
63
                $this->generateUrl('sumocoders_frameworkuser_user_new')
64
            );
65
66
        $form = $this->createForm(
67
            new UserType('\SumoCoders\FrameworkUserBundle\Entity\User')
0 ignored issues
show
Documentation introduced by
new \SumoCoders\Framewor...rBundle\\Entity\\User') is of type object<SumoCoders\Framew...erBundle\Form\UserType>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
68
        );
69
        $form->add('roles', 'choice', array(
70
            'choices' => $this->getExistingRoles(),
71
            'data' => array(),
72
            'label' => 'Roles',
73
            'expanded' => true,
74
            'multiple' => true,
75
            'mapped' => true,
76
        ));
77
78
        $form->handleRequest($request);
79
80
        if ($form->isValid()) {
81
            /** @var \SumoCoders\FrameworkUserBundle\Model\FrameworkUserManager $userManager */
82
            $userManager = $this->container->get('fos_user.user_manager');
83
            /** @var \SumoCoders\FrameworkUserBundle\Entity\User $user */
84
            $user = $form->getData();
85
            $user->setEnabled(true);
86
            $userManager->updateUser($user);
87
88
            /** @var \Symfony\Component\HttpFoundation\Session\Session $session */
89
            $session = $this->get('session');
0 ignored issues
show
Unused Code introduced by
$session 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...
90
            /** @var \Symfony\Bundle\FrameworkBundle\Translation\Translator $translator */
91
            $translator = $this->get('translator');
92
93
            $this->addFlash(
94
                'success',
95
                $translator->trans('user.flash.success.add', array('%username%' => $user->getUsername()))
96
            );
97
98
            // @todo move this in an event!
99 View Code Duplication
            if (array_key_exists(
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...
100
                'SumoCodersFrameworkSearchBundle',
101
                $this->container->getParameter('kernel.bundles')
102
            )
103
            ) {
104
                $searchIndexItems = \SumoCoders\FrameworkSearchBundle\Entity\IndexItem::createMultipleObjectsBasedOnProperties(
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 127 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
105
                    'SumoCoders\FrameworkUserBundle\Entity\User',
106
                    $user->getId(),
107
                    array('username', 'email'),
108
                    $user
109
                );
110
111
                $event = new \SumoCoders\FrameworkSearchBundle\Event\IndexUpdateEvent();
112
                $event->setObjects($searchIndexItems);
113
                $this->get('event_dispatcher')->dispatch('framework_search.index_update', $event);
114
            }
115
116
            return $this->redirect(
117
                $this->generateUrl(
118
                    'sumocoders_frameworkuser_user_index'
119
                )
120
            );
121
        }
122
123
        return array(
124
            'form' => $form->createView(),
125
        );
126
    }
127
128
    /**
129
     * Edit a user
130
     *
131
     * @Route("/{id}/edit", requirements={"id"= "\d+"})
132
     * @Method({"GET|POST"})
133
     * @Template()
134
     *
135
     * @param Request $request
136
     * @param int     $id
137
     * @return array
138
     */
139
    public function editAction(Request $request, $id)
140
    {
141
        // fix the breadCrumb
142
        $this->get('framework.breadcrumb_builder')
143
            ->extractItemsBasedOnUri(
144
                $this->generateUrl('sumocoders_frameworkuser_user_index'),
145
                $request->getLocale()
146
            )
147
            ->addSimpleItem(
148
                'user.breadcrumb.edit',
149
                $this->generateUrl(
150
                    'sumocoders_frameworkuser_user_edit',
151
                    array('id' => $id)
152
                )
153
            );
154
155
        $csrfProvider = $this->get('security.csrf.token_manager');
156
        /** @var \Symfony\Component\HttpFoundation\Session\Session $session */
157
        $session = $this->get('session');
158
        /** @var \Symfony\Bundle\FrameworkBundle\Translation\Translator $translator */
159
        $translator = $this->get('translator');
160
161
        /** @var \SumoCoders\FrameworkUserBundle\Model\FrameworkUserManager $userManager */
162
        $userManager = $this->container->get('fos_user.user_manager');
163
        /** @var \SumoCoders\FrameworkUserBundle\Entity\User $user */
164
        $user = $userManager->findUserBy(array('id' => $id));
165
        /** @var \SumoCoders\FrameworkUserBundle\Entity\User $currentUser */
166
        $currentUser = $this->get('security.context')->getToken()->getUser();
167
168
        // validate the user
169
        if (!$user) {
170
            throw new NotFoundHttpException(
171
                $translator->trans('core.errors.notFound')
172
            );
173
        }
174
175
        // if the current user is editing itself it should see the password field
176
        if ($currentUser->getId() == $user->getId()) {
177
            $type = new OwnUserType('\SumoCoders\FrameworkUserBundle\Entity\User');
178
        } else {
179
            $type = new OtherUserType('\SumoCoders\FrameworkUserBundle\Entity\User');
180
        }
181
182
        $form = $this->createForm($type, $user);
0 ignored issues
show
Documentation introduced by
$type is of type object<SumoCoders\Framew...dle\Form\OtherUserType>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
183
        $form->add(
184
            'roles',
185
            'choice',
186
            array(
187
                'choices' => $this->getExistingRoles(),
188
                'data' => $user->getRoles(),
189
                'label' => 'Roles',
190
                'expanded' => true,
191
                'multiple' => true,
192
            )
193
        );
194
195
        $form->handleRequest($request);
196
197
        if ($form->isValid()) {
198
            $user = $form->getData();
199
            $userManager->updateUser($user);
200
201 View Code Duplication
            if (array_key_exists(
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...
202
                'SumoCodersFrameworkSearchBundle',
203
                $this->container->getParameter('kernel.bundles')
204
            )
205
            ) {
206
                $searchIndexItems = \SumoCoders\FrameworkSearchBundle\Entity\IndexItem::createMultipleObjectsBasedOnProperties(
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 127 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
207
                    'SumoCoders\FrameworkUserBundle\Entity\User',
208
                    $user->getId(),
209
                    array('username', 'email'),
210
                    $user
211
                );
212
213
                $event = new \SumoCoders\FrameworkSearchBundle\Event\IndexUpdateEvent();
214
                $event->setObjects($searchIndexItems);
215
                $this->get('event_dispatcher')->dispatch('framework_search.index_update', $event);
216
            }
217
218
            $session->getFlashBag()->add(
219
                'success',
220
                $translator->trans('user.flash.success.edit', array('%username%' => $user->getUsername()))
221
            );
222
223
            return $this->redirect(
224
                $this->generateUrl(
225
                    'sumocoders_frameworkuser_user_index'
226
                )
227
            );
228
        }
229
230
        if ($user->isEnabled()) {
231
            $blockUnblockForm = $this->createBlockUnblockForm($user, 'block');
232
        } else {
233
            $blockUnblockForm = $this->createBlockUnblockForm($user, 'unblock');
234
        }
235
236
        return array(
237
            'form' => $form->createView(),
238
            'token' => $csrfProvider->getToken('block_unblock'),
239
            'user' => $user,
240
            'form_block_unblock' => $blockUnblockForm->createView(),
241
        );
242
    }
243
244
    /**
245
     * Creates a form to block a user.
246
     *
247
     * @param User $user The entity
248
     * @return \Symfony\Component\Form\Form The form
249
     */
250
    private function createBlockUnblockForm(User $user, $action = 'block')
251
    {
252
        $allowedActions = array(
253
            'block',
254
            'unblock',
255
        );
256
257
        if (!in_array($action, $allowedActions)) {
258
            throw new \InvalidArgumentException(
259
                'Invalid action, possible values are: ' . implode(', ', $allowedActions)
260
            );
261
        }
262
263
        if ('block' === $action) {
264
            $route = 'sumocoders_frameworkuser_user_block';
265
            $label = 'user.forms.buttons.block';
266
            $message = 'user.dialogs.messages.confirmBlock';
267
            $class = 'btn-danger';
268
            $icon = 'fa fa-remove';
269
        }
270
        if ('unblock' === $action) {
271
            $route = 'sumocoders_frameworkuser_user_unblock';
272
            $label = 'user.forms.buttons.unblock';
273
            $message = 'user.dialogs.messages.confirmUnblock';
274
            $class = 'btn-success';
275
            $icon = 'fa fa-check';
276
        }
277
278
        return $this->createFormBuilder()
279
            ->setAction(
280
                $this->generateUrl(
281
                    $route,
0 ignored issues
show
Bug introduced by
The variable $route 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...
282
                    array(
283
                        'id' => $user->getId(),
284
                    )
285
                )
286
            )
287
            ->setMethod('POST')
288
            ->add(
289
                'submit',
290
                'submit',
291
                array(
292
                    'icon' => $icon,
0 ignored issues
show
Bug introduced by
The variable $icon 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...
293
                    'label' => ucfirst($this->get('translator')->trans($label)),
0 ignored issues
show
Bug introduced by
The variable $label 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...
294
                    'attr' => array(
295
                        'class' => 'confirm ' . $class,
0 ignored issues
show
Bug introduced by
The variable $class 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...
296
                        'data-message' => $this->get('translator')->trans(
297
                            $message,
0 ignored issues
show
Bug introduced by
The variable $message 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...
298
                            array(
299
                                '%entity%' => $user,
300
                            )
301
                        ),
302
                    ),
303
                )
304
            )
305
            ->getForm();
306
    }
307
308
    /**
309
     * Block a user
310
     *
311
     * We won't delete users, as users can/will be linked through other stuff
312
     * in our application.
313
     *
314
     * @Route("/{id}/block", requirements={"id"= "\d+"})
315
     * @Method({"POST"})
316
     * @Template()
317
     *
318
     * @param User $user
319
     * @return array
320
     */
321
    public function blockAction(User $user)
322
    {
323
        return $this->handleBlockUnBlock('block', $user);
324
    }
325
326
    /**
327
     * Unblock a user
328
     *
329
     * @Route("/{id}/unblock", requirements={"id"= "\d+"})
330
     * @Method({"POST"})
331
     * @Template()
332
     *
333
     * @param User $user
334
     * @return array
335
     */
336
    public function unblockAction(User $user)
337
    {
338
        return $this->handleBlockUnBlock('unblock', $user);
339
    }
340
341
    /**
342
     * @param string $type
343
     * @param User   $user
344
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
345
     * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
346
     */
347
    private function handleBlockUnBlock($type, User $user)
348
    {
349
        /** @var \Symfony\Bundle\FrameworkBundle\Translation\Translator $translator */
350
        $translator = $this->get('translator');
351
352
        if ($type == 'unblock') {
353
            $enabled = true;
354
            $message = 'user.flash.success.unblocked';
355
        } else {
356
            $enabled = false;
357
            $message = 'user.flash.success.blocked';
358
        }
359
360
        $user->setEnabled($enabled);
361
        $this->container->get('fos_user.user_manager')->updateUser($user);
362
363
        $this->addFlash(
364
            'success',
365
            $translator->trans($message, array('%username%' => $user->getUsername()))
366
        );
367
368
        return $this->redirect(
369
            $this->generateUrl(
370
                'sumocoders_frameworkuser_user_edit',
371
                array(
372
                    'id' => $user->getId(),
373
                )
374
            )
375
        );
376
    }
377
378
    /**
379
     * Fetches all possible roles stated in our role_hierarchy setting
380
     *
381
     * @return array
382
     */
383
    protected function getExistingRoles()
384
    {
385
        $roleHierarchy = $this->container->getParameter('security.role_hierarchy.roles');
386
        $roles = array_keys($roleHierarchy);
387
388
        $cleanedUpRoles = array();
389
        foreach ($roles as $role) {
390
            $cleanedUpRoles[$role] = $role;
391
        }
392
393
        return $cleanedUpRoles;
394
    }
395
}
396