Completed
Pull Request — dev (#22)
by
unknown
07:49
created

UserController   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 110
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 9

Importance

Changes 2
Bugs 0 Features 1
Metric Value
wmc 9
c 2
b 0
f 1
lcom 1
cbo 9
dl 0
loc 110
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A usersListAction() 0 18 2
A userActivateAction() 0 8 2
A createActivateUserForm() 0 8 1
A userAddAction() 0 17 2
A userEditAction() 0 17 2
1
<?php
2
3
namespace AppBundle\Controller;
4
5
use AppBundle\Entity\User;
6
use AppBundle\Form\User\EditType;
7
use AppBundle\Form\User\RegistrationType;
8
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
9
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
10
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
11
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
12
use Symfony\Component\HttpFoundation\RedirectResponse;
13
use Symfony\Component\HttpFoundation\Request;
14
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
15
16
class UserController extends Controller
17
{
18
    /**
19
     * @Route("/users", name="users_list")
20
     * @Template("@App/users.html.twig")
21
     *
22
     * @param Request $request
23
     * @return array
24
     */
25
    public function usersListAction(Request $request)
26
    {
27
        $em = $this->getDoctrine()->getManager();
28
        $paginator = $this->get('knp_paginator');
29
        $users = $paginator->paginate(
30
            $em->getRepository(User::class)->selectUsersByParams($request->query),
31
            $request->query->getInt('page', 1),
32
            10
33
        );
34
        $activateForm = [];
35
        foreach ($users as $user) {
36
            $activateForm[$user->getId()] = $this->createActivateUserForm($user)->createView();
37
        }
38
        return [
39
            "users" => $users,
40
            'activateForm' => $activateForm
41
        ];
42
    }
43
44
    /**
45
     * @Route("/user/activate/{id}", name="activate_user")
46
     * @Template("@App/add.html.twig")
47
     *
48
     * @Method("PUT")
49
     * @param  User $user
50
     * @return RedirectResponse
51
     */
52
    public function userActivateAction(User $user)
53
    {
54
        $em = $this->getDoctrine()->getManager();
55
        $user->setStatus($user->isEnabled() ? false : true);
56
        $em->persist($user);
57
        $em->flush();
58
        return $this->redirect($this->generateUrl("users_list"));
59
    }
60
61
    /**
62
     * Creates a form to activate|deactivate User profile.
63
     * @param User $user
64
     * @return \Symfony\Component\Form\Form The form
65
     */
66
    private function createActivateUserForm(User $user)
67
    {
68
        return $this->createFormBuilder()
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...
69
            ->setAction($this->generateUrl('activate_user', array('id' => $user->getId())))
70
            ->setMethod('PUT')
71
            ->add('submit', SubmitType::class)
72
            ->getForm();
73
    }
74
75
    /**
76
     * @Route("/user/add", name="add_user")
77
     * @Template("@App/add.html.twig")
78
     *
79
     * @param Request $request
80
     * @return array|RedirectResponse
81
     */
82
    public function userAddAction(Request $request)
83
    {
84
        $em = $this->getDoctrine()->getManager();
85
        $user = new User();
86
        $form = $this->createForm(RegistrationType::class, $user, [
87
            'action' => $this->generateUrl('add_user'),
88
            'validation_groups' => array('registration'),
89
        ]);
90
        $form->handleRequest($request);
91
        if ($form->isValid()) {
92
            $em->persist($user);
93
            $em->flush();
94
95
            return $this->redirect($this->generateUrl("users_list"));
96
        }
97
        return ['form' => $form->createView()];
98
    }
99
100
    /**
101
     * @Route("/user/edit/{id}", name="edit_user")
102
     * @Template("@App/add.html.twig")
103
     *
104
     * @param Request $request
105
     * @param User $user
106
     * @return array|RedirectResponse
107
     */
108
    public function userEditAction(Request $request, User $user)
109
    {
110
        $em = $this->getDoctrine()->getManager();
111
        $form = $this->createForm(EditType::class, $user, [
112
            'action' => $this->generateUrl('edit_user', array('id' => $user->getId())),
113
            'method' => 'POST',
114
            'validation_groups' => array('edit'),
115
        ]);
116
        $form->handleRequest($request);
117
        if ($form->isValid()) {
118
            $em->persist($user);
119
            $em->flush();
120
121
            return $this->redirect($this->generateUrl("users_list"));
122
        }
123
        return ['form' => $form->createView()];
124
    }
125
}
126