Passed
Push — master ( a74354...254a60 )
by Andrea
18:29 queued 11s
created

FiApiCoreCrudControllerTrait::update()   B

Complexity

Conditions 5
Paths 7

Size

Total Lines 79
Code Lines 49

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 5
eloc 49
c 2
b 0
f 0
nc 7
nop 2
dl 0
loc 79
ccs 0
cts 48
cp 0
crap 30
rs 8.8016

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Cdf\BiCoreBundle\Controller;
4
5
use Cdf\BiCoreBundle\Utils\Tabella\ParametriTabella;
6
use Doctrine\DBAL\Exception\ForeignKeyConstraintViolationException;
7
use Doctrine\ORM\EntityManager;
8
use Symfony\Component\HttpFoundation\Request;
9
use Symfony\Component\HttpFoundation\Response;
10
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
11
use Cdf\BiCoreBundle\Utils\Api\ApiUtils;
12
use Cdf\BiCoreBundle\Utils\Entity\ModelUtils;
13
14
trait FiApiCoreCrudControllerTrait
15
{
16
    use FiApiCoreCrudInlineControllerTrait;
17
18
    /**
19
     * Displays a form to create a new table entity.
20
     */
21
    public function new(Request $request)
22
    {
23
        /* @var $em EntityManager */
24
        $bundle = $this->getBundle();
0 ignored issues
show
Bug introduced by
It seems like getBundle() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

24
        /** @scrutinizer ignore-call */ 
25
        $bundle = $this->getBundle();
Loading history...
25
        $controller = $this->getController();
0 ignored issues
show
Bug introduced by
It seems like getController() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

25
        /** @scrutinizer ignore-call */ 
26
        $controller = $this->getController();
Loading history...
26
        if (!$this->getPermessi()->canCreate($this->getController())) {
0 ignored issues
show
Bug introduced by
It seems like getPermessi() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

26
        if (!$this->/** @scrutinizer ignore-call */ getPermessi()->canCreate($this->getController())) {
Loading history...
27
            throw new AccessDeniedException('Non si hanno i permessi per creare questo contenuto');
28
        }
29
30
        $crudtemplate = $this->getCrudTemplate($bundle, $controller, $this->getThisFunctionName());
0 ignored issues
show
Bug introduced by
It seems like getThisFunctionName() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

30
        $crudtemplate = $this->getCrudTemplate($bundle, $controller, $this->/** @scrutinizer ignore-call */ getThisFunctionName());
Loading history...
Bug introduced by
It seems like getCrudTemplate() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

30
        /** @scrutinizer ignore-call */ 
31
        $crudtemplate = $this->getCrudTemplate($bundle, $controller, $this->getThisFunctionName());
Loading history...
31
        $tabellatemplate = $this->getTabellaTemplate($controller);
0 ignored issues
show
Bug introduced by
It seems like getTabellaTemplate() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

31
        /** @scrutinizer ignore-call */ 
32
        $tabellatemplate = $this->getTabellaTemplate($controller);
Loading history...
32
33
        $parametriform = $request->get('parametriform') ? json_decode($request->get('parametriform'), true) : [];
34
35
        //$entityclass = $this->getModelClassName();
36
        $entityclass = $this->getControllerItemName();
0 ignored issues
show
Bug introduced by
It seems like getControllerItemName() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

36
        /** @scrutinizer ignore-call */ 
37
        $entityclass = $this->getControllerItemName();
Loading history...
37
        $entity = new $entityclass();
38
39
        //$formclass = str_replace('Entity', 'Form', $entityclass);
40
        $formclass = $this->getFormName();
0 ignored issues
show
Bug introduced by
It seems like getFormName() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

40
        /** @scrutinizer ignore-call */ 
41
        $formclass = $this->getFormName();
Loading history...
41
        $formType = $formclass.'Type';
42
43
        $attrArray = ['attr' => [
44
            'id' => 'formdati'.$controller,
45
                    ],
46
            'action' => $this->generateUrl($controller.'_new'), 'parametriform' => $parametriform,
0 ignored issues
show
Bug introduced by
It seems like generateUrl() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

46
            'action' => $this->/** @scrutinizer ignore-call */ generateUrl($controller.'_new'), 'parametriform' => $parametriform,
Loading history...
47
            'extra-options' => []
48
                ];
49
50
        foreach ($this->options as $key => $option) {
51
            $attrArray['extra-options'][$key] = $option;
52
        }
53
54
        $form = $this->createForm(
0 ignored issues
show
Bug introduced by
It seems like createForm() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

54
        /** @scrutinizer ignore-call */ 
55
        $form = $this->createForm(
Loading history...
55
            $formType,
56
            $entity,
57
            $attrArray
58
        );
59
60
        $form->handleRequest($request);
61
62
        $twigparms = [
63
            'form' => $form->createView(),
64
            'nomecontroller' => ParametriTabella::setParameter($controller),
65
            'tabellatemplate' => $tabellatemplate,
66
        ];
67
68
        if ($form->isSubmitted()) {
69
            if ($form->isValid()) {
70
                //TODO: evaluate if this part can be improved
71
                $parameters = $request->request->get($form->getName());
72
                $entity = $form->getData();
73
                $this->setIdObjectfromSelect($entity, $parameters);
74
75
                $apiClass = $this->apiController;
76
                $apiObject = new $apiClass();
77
                $apiBook = new ApiUtils($this->collection);
78
                $createMethod = $apiBook->getCreate();
79
80
                /*$response = */
81
                $apiObject->$createMethod($entity);
82
                
83
                return new Response(
84
                    $this->renderView($crudtemplate, $twigparms),
0 ignored issues
show
Bug introduced by
It seems like renderView() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

84
                    $this->/** @scrutinizer ignore-call */ 
85
                           renderView($crudtemplate, $twigparms),
Loading history...
85
                    200
86
                );
87
            } else {
88
                //Quando non passa la validazione
89
                return new Response(
90
                    $this->renderView($crudtemplate, $twigparms),
91
                    400
92
                );
93
            }
94
        } else {
95
            //Quando viene richiesta una "nuova" new
96
            return new Response(
97
                $this->renderView($crudtemplate, $twigparms),
98
                200
99
            );
100
        }
101
    }
102
103
    /**
104
     * Displays a form to edit an existing table entity.
105
     */
106
    public function edit(Request $request, $id)
107
    {
108
        $bundle = $this->getBundle();
109
        $controller = $this->getController();
110
111
        if (!$this->getPermessi()->canUpdate($this->getController())) {
112
            throw new AccessDeniedException('Non si hanno i permessi per modificare questo contenuto');
113
        }
114
        $crudtemplate = $this->getCrudTemplate($bundle, $controller, $this->getThisFunctionName());
115
        $tabellatemplate = $this->getTabellaTemplate($controller);
116
117
        $formclass = $this->getFormName();
118
        $formType = $formclass.'Type';
119
120
        $apiClass = $this->apiController;
121
        $apiObject = new $apiClass();
122
        $apiBook = new ApiUtils($this->collection);
123
        $getMethod = $apiBook->getItem();
124
125
        //TODO: response belongs to last operation
126
        $entityorig = $apiObject->$getMethod($id);
127
128
        $elencomodifiche = $this->elencoModifiche($controller, $id);
129
130
        $modelutils = new ModelUtils();
131
        $entity = $modelutils->setApiValues($entityorig);
132
133
134
        $attrArray = ['attr' => [
135
                        'id' => 'formdati'.$controller,
136
                                ],
137
                    'action' => $this->generateUrl($controller.'_update', ['id' => $entity->getId()]),
138
                    'extra-options' => []
139
                            ];
140
        foreach ($this->options as $key => $option) {
141
            $attrArray['extra-options'][$key] = $option;
142
        }
143
144
        $editForm = $this->createForm(
145
            $formType,
146
            $entity,
147
            $attrArray
148
        );
149
150
        return $this->render(
0 ignored issues
show
Bug introduced by
It seems like render() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

150
        return $this->/** @scrutinizer ignore-call */ render(
Loading history...
151
            $crudtemplate,
152
            [
153
                            'entity' => $entity,
154
                            'nomecontroller' => ParametriTabella::setParameter($controller),
155
                            'tabellatemplate' => $tabellatemplate,
156
                            'edit_form' => $editForm->createView(),
157
                            'elencomodifiche' => $elencomodifiche,
158
                        ]
159
        );
160
    }
161
162
    /**
163
     * Update value of _id field with value selected on select list.
164
     * //TODO: review duplicated code
165
     */
166
    private function setIdfromSelect(&$parameters)
167
    {
168
        foreach (array_keys($parameters) as $key) {
169
            if (\str_contains($key, '_id')) {
170
                $sourceKey = substr($key, 0, strpos($key, '_id'));
171
                if (isset($parameters[$sourceKey])) {
172
                    $parameters[$key] = $parameters[$sourceKey];
173
                }
174
            } elseif (\str_contains($key, '_enum')) {
175
                $sourceKey = substr($key, 0, strpos($key, '_enum'));
176
                if (isset($parameters[$sourceKey])) {
177
                    $parameters[$key] = $parameters[$sourceKey];
178
                }
179
            }
180
        }
181
    }
182
183
    /**
184
     * Update value of _id fields of an object with value selected on select list.
185
     * It forces the received field to be an INT (It applies a cast)
186
     */
187
    private function setIdObjectfromSelect(&$classItem, &$parameters)
188
    {
189
        //TODO: (int) cast that is fixed
190
        $setters = $classItem::setters();
191
        foreach (array_keys($parameters) as $key) {
192
            if (\str_contains($key, '_id')) {
193
                $setMethod = $setters[$key];
194
                $sourceKey = substr($key, 0, strpos($key, '_id'));
195
                $classItem->$setMethod((int)$parameters[$sourceKey]);
196
            } elseif (\str_contains($key, '_enum')) {
197
                $setMethod = $setters[$key];
198
                $sourceKey = substr($key, 0, strpos($key, '_enum'));
199
                $classItem->$setMethod((int)$parameters[$sourceKey]);
200
            }
201
        }
202
    }
203
204
    /**
205
     * Edits an existing table entity.
206
     */
207
    public function update(Request $request, $id)
208
    {
209
        $bundle = $this->getBundle();
210
        $controller = $this->getController();
211
        if (!$this->getPermessi()->canUpdate($this->getController())) {
212
            throw new AccessDeniedException('Non si hanno i permessi per modificare questo contenuto');
213
        }
214
        $crudtemplate = $this->getCrudTemplate($bundle, $controller, 'edit');
215
        $tabellatemplate = $this->getTabellaTemplate($controller);
216
        $elencomodifiche = $this->elencoModifiche($controller, $id);
217
218
        $formclass = $this->getFormName();
219
        $formType = $formclass.'Type';
220
221
        $apiClass = $this->apiController;
222
        $apiObject = new $apiClass();
223
        $apiBook = new ApiUtils($this->collection);
224
        $getMethod = $apiBook->getItem();
225
226
        //TODO: response belongs to last operation
227
        $entityorig = $apiObject->$getMethod($id);
228
229
        $modelutils = new ModelUtils();
230
        $entity = $modelutils->setApiValues($entityorig);
231
232
        $attrArray = ['attr' => [
233
            'id' => 'formdati'.$controller,
234
                    ],
235
        'action' => $this->generateUrl($controller.'_update', ['id' => $entity->getId()]),
236
        'extra-options' => []
237
                ];
238
239
        foreach ($this->options as $key => $option) {
240
            $attrArray['extra-options'][$key] = $option;
241
        }
242
243
        $editForm = $this->createForm(
244
            $formType,
245
            $entity,
246
            $attrArray
247
        );
248
249
        $parameters = $request->request->get($editForm->getName());
250
251
        $this->setIdfromSelect($parameters);
252
        $editForm->submit($parameters);
253
254
        if ($editForm->isValid()) {
255
            $entityItem = $editForm->getData();
256
257
            //$entityItem = $modelutils->getControllerItem($modelEntity , $this->getControllerItemName());
258
            
259
260
            $apiClass = $this->apiController;
261
            $apiObject = new $apiClass();
262
            $apiBook = new ApiUtils($this->collection);
263
            $updateMethod = $apiBook->getUpdateItem();
264
265
            /*$responseMessage = */
266
            $apiObject->$updateMethod($entityItem, $id);
267
268
            $continua = (int) $request->get('continua');
269
            if (0 === $continua) {
270
                return new Response('OK');
271
            } else {
272
                return $this->redirect($this->generateUrl($controller.'_edit', ['id' => $id]));
0 ignored issues
show
Bug introduced by
It seems like redirect() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

272
                return $this->/** @scrutinizer ignore-call */ redirect($this->generateUrl($controller.'_edit', ['id' => $id]));
Loading history...
273
            }
274
        }
275
276
        return new Response($this->renderView(
277
            $crudtemplate,
278
            [
279
                            'entity' => $entity,
280
                            'edit_form' => $editForm->createView(),
281
                            'nomecontroller' => ParametriTabella::setParameter($controller),
282
                            'tabellatemplate' => $tabellatemplate,
283
                            'elencomodifiche' => $elencomodifiche,
284
            ]
285
        ), 400);
286
    }
287
288
    /**
289
     * Deletes a table entity.
290
     */
291
    public function delete(Request $request, $token)
292
    {
293
        /* @var $em EntityManager */
294
        if (!$this->getPermessi()->canDelete($this->getController())) {
295
            throw new AccessDeniedException('Non si hanno i permessi per eliminare questo contenuto');
296
        }
297
        //$entityclass = $this->getEntityClassName();
298
299
        $isValidToken = $this->isCsrfTokenValid($this->getController(), $token);
0 ignored issues
show
Bug introduced by
It seems like isCsrfTokenValid() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

299
        /** @scrutinizer ignore-call */ 
300
        $isValidToken = $this->isCsrfTokenValid($this->getController(), $token);
Loading history...
300
301
        if (!$isValidToken) {
302
            throw $this->createNotFoundException('Token non valido');
0 ignored issues
show
Bug introduced by
It seems like createNotFoundException() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

302
            throw $this->/** @scrutinizer ignore-call */ createNotFoundException('Token non valido');
Loading history...
303
        }
304
305
        try {
306
            $ids = explode(',', $request->get('id'));
307
308
            $apiClass = $this->apiController;
309
            $apiObject = new $apiClass();
310
            $apiBook = new ApiUtils($this->collection);
311
            $deleteMethod = $apiBook->getDelete();
312
313
            foreach ($ids as $id) {
314
              //TODO: response belongs to last operation
315
                $response = $apiObject->$deleteMethod($id);
0 ignored issues
show
Unused Code introduced by
The assignment to $response is dead and can be removed.
Loading history...
316
            }
317
        } catch (\Exception $e) {
318
            $response = new Response($e->getMessage());
319
            $response->setStatusCode('200');
320
321
            return $response;
322
        }
323
324
        return new Response('Operazione eseguita con successo');
325
    }
326
327
    public function elencoModifiche($controller, $id)
328
    {
329
        $em = $this->getDoctrine()->getManager();
0 ignored issues
show
Bug introduced by
It seems like getDoctrine() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

329
        $em = $this->/** @scrutinizer ignore-call */ getDoctrine()->getManager();
Loading history...
330
        $risultato = $em->getRepository('BiCoreBundle:Storicomodifiche')->findBy(
331
            [
332
                    'nometabella' => $controller,
333
                    'idtabella' => $id,
334
                ],
335
            ['giorno' => 'DESC']
336
        );
337
338
        return $risultato;
339
    }
340
}
341