Completed
Push — develop ( bb7f99...d04bd8 )
by Victor
03:30
created

UserController::roleAction()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 56
Code Lines 37

Duplication

Lines 56
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 56
loc 56
ccs 0
cts 39
cp 0
rs 8.7592
cc 5
eloc 37
nc 6
nop 2
crap 30

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 AppBundle\Controller\Admin;
4
5
use AppBundle\Entity\User;
6
use AppBundle\Form\Type\UserType;
7
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
8
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
9
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
10
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
11
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
12
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
13
use Symfony\Component\HttpFoundation\Request;
14
15
/**
16
 * Class UserController
17
 * @package AppBundle\Controller\Admin
18
 * @Route("/admin")
19
 */
20 View Code Duplication
class UserController extends Controller
0 ignored issues
show
Duplication introduced by
This class 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...
21
{
22
    /**
23
     * @param Request $request
24
     * @param $page
25
     * @Method({"GET", "POST"})
26
     * @Route("/users/{pager}/{page}", name="usersAdmin",
27
     *     defaults={"pager": "page", "page": 1},
28
     *     requirements={
29
     *          "pager": "page",
30
     *          "page": "[1-9]\d*",
31
     *     })
32
     * @Template("AppBundle:admin:users.html.twig")
33
     *
34
     * @return Response
35
     */
36
    public function roleAction(Request $request, $page = 1)
0 ignored issues
show
Unused Code introduced by
The parameter $page 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...
37
    {
38
        $em = $this->getDoctrine()->getManager();
39
        $users = $em->getRepository('AppBundle:User')
40
            ->findAll();
41
42
        $form = $this->createFormBuilder($users)
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Symfony\Component\Form\FormConfigBuilder as the method add() does only exist in the following sub-classes of Symfony\Component\Form\FormConfigBuilder: Symfony\Component\Form\FormBuilder. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
43
            ->setAction($this->generateUrl('usersAdmin'))
44
            ->setMethod('POST')
45
            ->add('users', ChoiceType::class, array(
46
                    'choices'           => $users,
47
                    'choices_as_values' => true,
48
                    'expanded'          => true,
49
                    'multiple'          => true,
50
                    'choice_value'      => 'id',
51
                    'label'             => false,
52
                    'choice_label'      => 'id',
53
                )
54
            )
55
            ->add('delete', SubmitType::class, array(
56
                    'label'     => 'Remove',
57
                    'attr'      => [
58
                        'class' => 'btn btn-xs btn-danger'
59
                    ],
60
                )
61
            )
62
            ->getForm();
63
64
        if ($request->getMethod() == 'POST') {
65
            $form->handleRequest($request);
66
            if ($form->isValid()) {
67
                $data = $form->getData();
68
                foreach ($data['users'] as $user) {
69
                    $em->remove($user);
70
                }
71
72
                try {
73
                    $em->flush();
74
                } catch (\Exception $e) {
75
                    return $this->render(
76
                        'AppBundle:admin:failure.html.twig',
77
                        array(
78
                            'message' => 'Deleting record is failed. Because record has relation to other records or another reasons.',
79
                        )
80
                    );
81
                }
82
83
                return $this->redirectToRoute('usersAdmin');
84
            }
85
        }
86
87
        return [
88
            'users'  => $users,
89
            'delete' => $form->createView(),
90
        ];
91
    }
92
93
    /**
94
     * @param $id
95
     * @param $action
96
     * @param Request $request
97
     * @Route("/user/{action}/{id}", name="userEdit",
98
     *     defaults={"id": 0},
99
     *     requirements={
100
     *      "action": "new|edit",
101
     *      "id": "\d+"
102
     *     })
103
     * @Method({"GET", "POST"})
104
     * @Template("AppBundle:admin/form:user.html.twig")
105
     *
106
     * @return Response
107
     */
108
    public function editUserAction($id, $action, Request $request)
109
    {
110
        $em = $this->getDoctrine()->getManager();
111
        if ($action == "edit") {
112
            $user = $em->getRepository('AppBundle:User')
113
                ->find($id);
114
            $title = 'Edit user id: '.$id;
115
        }
116
        else {
117
            $user = new User();
118
            $title = 'Create new user';
119
        }
120
121
122
        $form = $this->createForm(UserType::class, $user, [
123
            'em' => $em,
124
            'action' => $this->generateUrl('userEdit', ['action' => $action, 'id' => $id]),
125
            'method' => Request::METHOD_POST,
126
        ])
127
            ->add('save', SubmitType::class, array('label' => 'Save'));
128
129
        if ($request->getMethod() == 'POST') {
130
            $form->handleRequest($request);
131
            if ($form->isValid()) {
132
                $em->persist($user);
133
                $em->flush();
134
135
                return $this->redirectToRoute('usersAdmin');
136
            }
137
        }
138
139
        return [
140
            'title' => $title,
141
            'form'  => $form->createView(),
142
        ];
143
    }
144
145
}
146