Completed
Push — develop ( d04bd8...ba22c0 )
by Victor
02:48
created

UserController::deleteUserAction()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 50
Code Lines 32

Duplication

Lines 9
Ratio 18 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 9
loc 50
ccs 0
cts 33
cp 0
rs 8.6315
cc 5
eloc 32
nc 4
nop 2
crap 30
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
class UserController extends Controller
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...
Unused Code introduced by
The parameter $request 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
        return [
43
            'users'  => $users,
44
        ];
45
    }
46
47
    /**
48
     * @param $id
49
     * @param $action
50
     * @param Request $request
51
     * @Route("/user/{action}/{id}", name="userEdit",
52
     *     defaults={"id": 0},
53
     *     requirements={
54
     *      "action": "new|edit",
55
     *      "id": "\d+"
56
     *     })
57
     * @Method({"GET", "POST"})
58
     * @Template("AppBundle:admin/form:user.html.twig")
59
     *
60
     * @return Response
61
     */
62
    public function editUserAction($id, $action, Request $request)
63
    {
64
        $em = $this->getDoctrine()->getManager();
65
        if ($action == "edit") {
66
            $user = $em->getRepository('AppBundle:User')
67
                ->find($id);
68
            $title = 'Edit user id: '.$id;
69
        }
70
        else {
71
            $user = new User();
72
            $title = 'Create new user';
73
        }
74
75
76
        $form = $this->createForm(UserType::class, $user, [
77
            'em' => $em,
78
            'action' => $this->generateUrl('userEdit', ['action' => $action, 'id' => $id]),
79
            'method' => Request::METHOD_POST,
80
        ])
81
            ->add('save', SubmitType::class, array('label' => 'Save'));
82
83 View Code Duplication
        if ($request->getMethod() == 'POST') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
84
            $form->handleRequest($request);
85
            if ($form->isValid()) {
86
                $em->persist($user);
87
                $em->flush();
88
89
                return $this->redirectToRoute('usersAdmin');
90
            }
91
        }
92
93
        return [
94
            'title' => $title,
95
            'form'  => $form->createView(),
96
        ];
97
    }
98
99
    /**
100
     * @param $id
101
     * @param Request $request
102
     * @Route("/user/delete/{id}", name="userDelete",
103
     *     requirements={
104
     *      "id": "\d+"
105
     *     })
106
     * @Method({"GET", "POST"})
107
     * @Template("AppBundle:admin/form:delete.html.twig")
108
     *
109
     * @return Response
110
     */
111
    public function deleteUserAction($id, Request $request)
112
    {
113
        $em = $this->getDoctrine()->getManager();
114
        $user = $em->getRepository('AppBundle:User')
115
            ->find($id);
116
117
        $countArticles = count($user->getArticles());
118
        $countComments = count($user->getComments());
119
120
        $message = 'You want to delete user "' . $user->getName() . '" (id: ' . $id . '). ';
121
        $message .= 'Related records: articles (count: ' . $countArticles . '), ';
122
        $message .= 'comments (count: ' . $countComments . '). ';
123
124
        if ($countArticles == 0 or $countComments == 0) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
125
            $message .= 'Are you sure, you want to continue?';
126
127
            $form = $this->createFormBuilder($user)
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...
128
                ->setAction($this->generateUrl('userDelete', ['id' => $id]))
129
                ->setMethod('POST')
130
                ->add('delete', SubmitType::class, array(
131
                        'label'     => 'Continue',
132
                        'attr'      => [
133
                            'class' => 'btn btn-default'
134
                        ],
135
                    )
136
                )
137
                ->getForm();
138
139 View Code Duplication
            if ($request->getMethod() == 'POST') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
140
                $form->handleRequest($request);
141
                if ($form->isValid()) {
142
                    $em->remove($user);
143
                    $em->flush();
144
145
                    return $this->redirectToRoute('usersAdmin');
146
                }
147
            }
148
149
            $renderedForm = $form->createView();
150
        }
151
        else {
152
            $message .= 'You must to delete related records before.';
153
            $renderedForm = '';
154
        }
155
156
        return [
157
            'message' => $message,
158
            'form'    => $renderedForm,
159
        ];
160
    }
161
}
162