Completed
Pull Request — dev (#22)
by
unknown
03:09
created

UserController::createActivationForm()   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 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->createActivationForm($user)->createView();
37
        }
38
        return [
39
            "users" => $users,
40
            'activateForm' => $activateForm
41
        ];
42
    }
43
44
    /**
45
     * @Route("/user/activate", name="activate_user")
46
     * @Template("@App/add.html.twig")
47
     *
48
     * @Method("PUT")
49
     * @param  Request $request
50
     * @return RedirectResponse
51
     */
52
    public function activationAction(Request $request)
53
    {
54
        $em = $this->getDoctrine()->getManager();
55
        $user = $em->getRepository(User::class)->find($request->get('id'));
56
        $user->setStatus($user->isEnabled() ? false : true);
57
        $em->persist($user);
58
        $em->flush();
59
        return $this->redirect($this->generateUrl("users_list"));
60
    }
61
62
    /**
63
     * Creates a form to activate|deactivate User profile.
64
     * @param User $user
65
     * @return \Symfony\Component\Form\Form The form
66
     */
67
    private function createActivationForm(User $user)
68
    {
69
        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...
70
            ->setAction($this->generateUrl('activate_user', array('id' => $user->getId())))
71
            ->setMethod('PUT')
72
            ->add('submit', SubmitType::class)
73
            ->getForm();
74
    }
75
76
    /**
77
     * @Route("/user/add", name="add_user")
78
     * @Template("@App/add.html.twig")
79
     *
80
     * @param Request $request
81
     * @return array|RedirectResponse
82
     */
83
    public function userAddAction(Request $request)
84
    {
85
        $em = $this->getDoctrine()->getManager();
86
        $user = new User();
87
        $form = $this->createForm(RegistrationType::class, $user, [
88
            'action' => $this->generateUrl('add_user'),
89
            'validation_groups' => array('registration'),
90
        ]);
91
        $form->handleRequest($request);
92
        if ($form->isValid()) {
93
            $em->persist($user);
94
            $em->flush();
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
            return $this->redirect($this->generateUrl("users_list"));
121
        }
122
        return ['form' => $form->createView()];
123
    }
124
}
125