Completed
Push — develop ( ba22c0...6d3372 )
by Victor
02:49
created

RoleController::roleAction()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 10
ccs 0
cts 6
cp 0
rs 9.4285
cc 1
eloc 6
nc 1
nop 2
crap 2
1
<?php
2
3
namespace AppBundle\Controller\Admin;
4
5
use AppBundle\Entity\Role;
6
use AppBundle\Form\Type\RoleType;
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 AdminController
17
 * @package AppBundle\Controller\Admin
18
 * @Route("/admin")
19
 */
20
class RoleController extends Controller
21
{
22
    /**
23
     * @param Request $request
24
     * @param $page
25
     * @Method({"GET", "POST"})
26
     * @Route("/roles/{pager}/{page}", name="rolesAdmin",
27
     *     defaults={"pager": "page", "page": 1},
28
     *     requirements={
29
     *          "pager": "page",
30
     *          "page": "[1-9]\d*",
31
     *     })
32
     * @Template("AppBundle:admin:roles.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
        $roles = $em->getRepository('AppBundle:Role')
40
            ->findAll();
41
42
        return [
43
            'roles'  => $roles,
44
        ];
45
    }
46
47
    /**
48
     * @param $id
49
     * @param $action
50
     * @param Request $request
51
     * @Route("/role/{action}/{id}", name="roleEdit",
52
     *     defaults={"id": 0},
53
     *     requirements={
54
     *      "action": "new|edit",
55
     *      "id": "\d+"
56
     *     })
57
     * @Method({"GET", "POST"})
58
     * @Template("AppBundle:admin/form:role.html.twig")
59
     *
60
     * @return Response
61
     */
62
    public function editRoleAction($id, $action, Request $request)
63
    {
64
        $em = $this->getDoctrine()->getManager();
65
        if ($action == "edit") {
66
            $role = $em->getRepository('AppBundle:Role')
67
                ->find($id);
68
            $title = 'Edit role id: '.$id;
69
        }
70
        else {
71
            $role = new Role();
72
            $title = 'Create new role';
73
        }
74
75
76
        $form = $this->createForm(RoleType::class, $role, [
77
            'em' => $em,
78
            'action' => $this->generateUrl('roleEdit', ['action' => $action, 'id' => $id]),
79
            'method' => Request::METHOD_POST,
80
        ])
81
            ->add('save', SubmitType::class, array('label' => 'Save'));
82
83
        if ($request->getMethod() == 'POST') {
84
            $form->handleRequest($request);
85
            if ($form->isValid()) {
86
                $em->persist($role);
87
                $em->flush();
88
89
                return $this->redirectToRoute('rolesAdmin');
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("/role/delete/{id}", name="roleDelete",
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 deleteRoleAction($id, Request $request)
112
    {
113
        $em = $this->getDoctrine()->getManager();
114
        $role = $em->getRepository('AppBundle:Role')
115
            ->find($id);
116
117
        $countUsers = count($role->getUsers());
118
119
        $message = 'You want to delete role "' . $role->getName() . '" (id: ' . $id . '). ';
120
        $message .= 'Related records: users (count: ' . $countUsers . '). ';
121
122 View Code Duplication
        if ($countUsers == 0) {
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...
123
            $message .= 'Are you sure, you want to continue?';
124
125
            $form = $this->createFormBuilder($role)
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...
126
                ->setAction($this->generateUrl('roleDelete', ['id' => $id]))
127
                ->setMethod('POST')
128
                ->add('delete', SubmitType::class, array(
129
                        'label'     => 'Continue',
130
                        'attr'      => [
131
                            'class' => 'btn btn-default'
132
                        ],
133
                    )
134
                )
135
                ->getForm();
136
137
            if ($request->getMethod() == 'POST') {
138
                $form->handleRequest($request);
139
                if ($form->isValid()) {
140
                    $em->remove($role);
141
                    $em->flush();
142
143
                    return $this->redirectToRoute('rolesAdmin');
144
                }
145
            }
146
147
            $renderedForm = $form->createView();
148
        }
149
        else {
150
            $message .= 'You must to delete related records before.';
151
            $renderedForm = '';
152
        }
153
154
        return [
155
            'message' => $message,
156
            'form'    => $renderedForm,
157
        ];
158
    }
159
}
160