Completed
Pull Request — dev (#22)
by
unknown
19:52
created

UserController::createActivateUserForm()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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