Completed
Push — master ( 858bee...ca95b0 )
by Pavel
10s
created

UserController::createFormDelete()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 9

Duplication

Lines 12
Ratio 100 %

Code Coverage

Tests 8
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 2
Metric Value
c 2
b 0
f 2
dl 12
loc 12
ccs 8
cts 8
cp 1
rs 9.4285
cc 1
eloc 9
nc 1
nop 1
crap 1
1
<?php
2
3
namespace AppBundle\Controller\Admin;
4
5
use Symfony\Component\HttpFoundation\Request;
6
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
7
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
8
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
9
use AppBundle\Entity\User;
10
use AppBundle\Form\UserType;
11
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
12
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
13
14
/**
15
 * User controller.
16
 *
17
 * @Route("/admin/user")
18
 */
19
class UserController extends Controller
20
{
21
    /**
22
     * Lists all User entities.
23
     *
24
     * @Route("", name="user_show")
25
     * @Method("GET")
26
     * @Template("@App/admin/user/showUser.html.twig")
27
     */
28 1 View Code Duplication
    public function indexAction()
0 ignored issues
show
Duplication introduced by
This method 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...
29
    {
30 1
        $em = $this->getDoctrine()->getManager();
31 1
        $sql = $em->getRepository('AppBundle:User')->findUsersWithoutRole(User::ROLE_ADMIN);
32 1
        $paginator = $this->get('knp_paginator');
33 1
        $users = $paginator->paginate(
34 1
            $sql,
35 1
            $this->get('request')->query->get('page', 1),
36 1
            $this->container->getParameter('knp_paginator.page_range')
37 1
        );
38
39 1
        $form_delete = [];
40
41 1
        foreach ($users as $item) {
42 1
            $form_delete[$item->getId()] = $this->createFormDelete($item->getId())->createView();
43 1
        }
44
45
        return [
46 1
            'users' => $users,
47
            'form_remove' => $form_delete
48 1
        ];
49
    }
50
51
    /**
52
     * Displays a form to edit an existing User entity.
53
     *
54
     * @Route("/{id}/edit", name="edit_user")
55
     * @Method({"GET", "POST"})
56
     * @Template("@App/admin/user/editUser.html.twig")
57
     */
58 1 View Code Duplication
    public function editAction(Request $request, User $user)
0 ignored issues
show
Duplication introduced by
This method 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...
59
    {
60 1
        $editForm = $this->createForm('AppBundle\Form\UpdateUserType', $user);
61
62 1
        $editForm->handleRequest($request);
63
64 1
        if ($editForm->isSubmitted() && $editForm->isValid()) {
65
            $em = $this->getDoctrine()->getManager();
66
            $em->persist($user);
67
            $em->flush();
68
69
            return $this->redirectToRoute('user_show');
70
        }
71
72
        return [
73 1
            'user' => $user,
74 1
            'form' => $editForm->createView(),
75 1
        ];
76
    }
77
78
    /**
79
     * Deletes a User entity.
80
     *
81
     * @Route("/{id}", name="user_delete")
82
     * @Method("DELETE")
83
     */
84 1
    public function deleteAction(Request $request, User $user)
85
    {
86 1
        $form = $this->createFormDelete($user->getId());
87 1
        $form->handleRequest($request);
88
89 1
        if ($form->isSubmitted() && $form->isValid()) {
90
            $em = $this->getDoctrine()->getManager();
91
            $em->remove($user);
92
            $em->flush();
93
        }
94
95 1
        return $this->redirectToRoute('user_show');
96
    }
97
98
    /**
99
     * Creates a form to delete a User entity.
100
     *
101
     * @return \Symfony\Component\Form\Form The form
102
     */
103 2 View Code Duplication
    private function createFormDelete($id)
0 ignored issues
show
Duplication introduced by
This method 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...
104
    {
105 2
        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...
106 2
            ->setAction($this->generateUrl('user_delete', ['id' => $id]))
107 2
            ->setMethod('DELETE')
108 2
            ->add('submit', SubmitType::class, ['label' => ' ',
109
                'attr' => [
110 2
                    'class' => 'glyphicon glyphicon-remove btn-link',
111
                    'onclick' => 'return confirm("Are you sure?")'
112 2
                ]])
113 2
            ->getForm();
114
    }
115
}