Completed
Push — master ( 4bb011...4b99be )
by Guillaume
13:23
created

UserController   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 224
Duplicated Lines 16.52 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 0
Metric Value
wmc 17
lcom 1
cbo 7
dl 37
loc 224
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A cgetAction() 0 22 3
A getAction() 16 16 3
A postAction() 21 21 3
B putAction() 0 29 6
A deleteAction() 0 9 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace Starkerxp\UserBundle\Controller;
4
5
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
6
use Starkerxp\StructureBundle\Controller\StructureController;
7
use Starkerxp\UserBundle\Entity\User;
8
use Starkerxp\UserBundle\Form\Type\UserType;
9
use Symfony\Component\HttpFoundation\JsonResponse;
10
use Symfony\Component\HttpFoundation\Request;
11
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
12
13
class UserController extends StructureController
14
{
15
    /**
16
     * @ApiDoc(
17
     *      resource=true,
18
     *      description="Liste les users.",
19
     *      section="User",
20
     *      parameters={
21
     *          {
22
     *              "name"="offset",
23
     *              "dataType"="integer",
24
     *              "requirement"="\d+",
25
     *              "description"="starkerxp_structure.doc.offset.result",
26
     *              "required"="false"
27
     *          },
28
     *          {
29
     *              "name"="limit",
30
     *              "dataType"="integer",
31
     *              "requirement"="\d+",
32
     *              "description"="starkerxp_structure.doc.limit.result",
33
     *              "required"="false"
34
     *          },
35
     *          {
36
     *              "name"="fields",
37
     *              "dataType"="string",
38
     *              "requirement"="\w+",
39
     *              "description"="starkerxp_structure.doc.list_field.entity",
40
     *              "required"="false"
41
     *          },
42
     *          {
43
     *              "name"="sort",
44
     *              "dataType"="string",
45
     *              "requirement"="\w+",
46
     *              "description"="starkerxp_structure.doc.sort.result",
47
     *              "required"="false"
48
     *          }
49
     *      },
50
     *      views = { "default" }
51
     * )
52
     */
53
    public function cgetAction(Request $request)
54
    {
55
        $manager = $this->get("starkerxp_user.manager.user");
56
        try {
57
            $options = $this->resolveParams()->resolve($request->query->all());
58
            $orderBy = $this->getOrderBy($options['sort']);
59
            $resultSets = $manager->findBy([], $orderBy, $options['limit'], $options['offset']);
60
        } catch (\Exception $e) {
61
            return new JsonResponse(["payload" => $e->getMessage()], 400);
62
        }
63
        if (empty($resultSets)) {
64
            return new JsonResponse([]);
65
        }
66
        $retour = array_map(
67
            function ($element) use ($manager, $options) {
68
                return $manager->toArray($element, $this->getFields($options['fields']));
69
            },
70
            $resultSets
71
        );
72
73
        return new JsonResponse($retour);
74
    }
75
76
77
    /**
78
     * @ApiDoc(
79
     *      resource=true,
80
     *      description="Affiche un user.",
81
     *      section="User",
82
     *      requirements={
83
     *          {
84
     *              "name"="user_id",
85
     *              "dataType"="integer",
86
     *              "requirement"="\d+",
87
     *              "description"="Permet d'afficher l'élément choisis"
88
     *          }
89
     *      },
90
     *      parameters={
91
     *          {
92
     *              "name"="fields",
93
     *              "dataType"="string",
94
     *              "requirement"="\w+",
95
     *              "description"="starkerxp_structure.doc.list_field.entity",
96
     *              "required"="false"
97
     *          }
98
     *      },
99
     *      views = { "default" }
100
     * )
101
     */
102 View Code Duplication
    public function getAction(Request $request)
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...
103
    {
104
        $manager = $this->get("starkerxp_user.manager.user");
105
        try {
106
            $options = $this->resolveParams()->resolve($request->query->all());
107
            $user = $manager->findOneBy(['id' => $request->get('user_id')]);
108
        } catch (\Exception $e) {
109
            return new JsonResponse(["payload" => $e->getMessage()], 400);
110
        }
111
        if (!$user instanceof User) {
112
            return new JsonResponse(["payload" => $this->translate("user.entity.not_found", "user")], 404);
113
        }
114
        $retour = $manager->toArray($user, $this->getFields($options['fields']));
115
116
        return new JsonResponse($retour);
117
    }
118
119
    /**
120
     * @ApiDoc(
121
     *      resource=true,
122
     *      description="Ajoute un user.",
123
     *      section="User",
124
     *      requirements={
125
     *          {
126
     *              "name"="email",
127
     *              "dataType"="string",
128
     *              "requirement"="\w+",
129
     *              "description"="Définit l'identifiant de connexion"
130
     *          },
131
     *          {
132
     *              "name"="type",
133
     *              "dataType"="integer",
134
     *              "requirement"="\d+",
135
     *              "description"="1 - User / 2 - Api"
136
     *          },
137
     *      },
138
     *      views = { "default" }
139
     * )
140
     */
141 View Code Duplication
    public function postAction(Request $request)
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...
142
    {
143
        $manager = $this->get("starkerxp_user.manager.user");
144
        try {
145
            $form = $this->createForm(UserType::class, [], ['method' => 'POST']);
146
            $form->submit($this->getRequestData($request));
147
            if ($form->isValid()) {
148
                $user = $form->getData();
149
                $user->setUuid($this->getUuid());
150
                $manager->insert($user);
151
152
                return new JsonResponse(["payload" => $this->translate("user.entity.created", "user")], 201);
153
            }
154
        } catch (\Exception $e) {
155
            $manager->rollback();
156
157
            return new JsonResponse(["payload" => $e->getMessage()], 400);
158
        }
159
160
        return new JsonResponse(["payload" => $this->getFormErrors($form)], 400);
161
    }
162
163
    /**
164
     * @ApiDoc(
165
     *      resource=true,
166
     *      description="Modifie un user.",
167
     *      section="User",
168
     *      requirements={
169
     *          {
170
     *              "name"="user_id",
171
     *              "dataType"="integer",
172
     *              "requirement"="\d+",
173
     *              "description"="Permet de modifier l'élément choisi."
174
     *          }
175
     *      },
176
     *      views = { "default" }
177
     * )
178
     */
179
    public function putAction(Request $request)
180
    {
181
        $manager = $this->get("starkerxp_user.manager.user");
182
        $user = $manager->find($request->get('user_id'));
183
        if (!$user instanceof User) {
184
            return new JsonResponse(["payload" => $this->translate("user.entity.not_found", "user")], 404);
185
        }
186
        // Un user ne peut modifier un autre user sauf si ce dernier est un super admin.
187
        if($this->getUser()->getId() !=  $user->getId() && !$this->isGranted("ROLE_SUPER_ADMIN")){
188
            return new JsonResponse(["payload" => $this->translate("user.entity.not_updated_is_not_admin", "user")], 400);
189
        }
190
        $manager->beginTransaction();
191
        try {
192
            $form = $this->createForm(UserType::class, $user, ['method' => 'PUT']);
193
            $form->submit($this->getRequestData($request));
194
            if ($form->isValid()) {
195
                $user = $form->getData();
196
                $manager->update($user);
197
198
                return new JsonResponse(["payload" => $this->translate("user.entity.updated", "user")], 204);
199
            }
200
        } catch (\Exception $e) {
201
            $manager->rollback();
202
203
            return new JsonResponse(["payload" => $e->getMessage()], 400);
204
        }
205
206
        return new JsonResponse(["payload" => $this->getFormErrors($form)], 400);
207
    }
208
209
    /**
210
     * @ApiDoc(
211
     *      resource=true,
212
     *      description="Supprime un user.",
213
     *      section="User",
214
     *      requirements={
215
     *          {
216
     *              "name"="user_id",
217
     *              "dataType"="integer",
218
     *              "requirement"="\d+",
219
     *              "description"="Permet de supprimer l'élément choisi."
220
     *          }
221
     *      },
222
     *      views = { "default" }
223
     * )
224
     * @Security("has_role('ROLE_SUPER_ADMIN')")
225
     */
226
    public function deleteAction(Request $request)
227
    {
228
        $manager = $this->get("starkerxp_user.manager.user");
229
        $user = $manager->find($request->get('user_id'));
230
        if (!$user instanceof User) {
231
            return new JsonResponse(["payload" => $this->translate("user.entity.not_found", "user")], 404);
232
        }
233
        return new JsonResponse(["payload" => $this->translate("user.entity.deleted", "user")], 204);
234
    }
235
236
} 
0 ignored issues
show
Coding Style introduced by
As per coding style, files should not end with a newline character.

This check marks files that end in a newline character, i.e. an empy line.

Loading history...
237