FiCoreCrudControllerTrait::new()   A
last analyzed

Complexity

Conditions 5
Paths 7

Size

Total Lines 58
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 41
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 38
nc 7
nop 1
dl 0
loc 58
ccs 41
cts 41
cp 1
crap 5
rs 9.0008
c 1
b 0
f 0

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\Entity\Storicomodifiche;
12
13
trait FiCoreCrudControllerTrait
14
{
15
    use FiCoreCrudInlineControllerTrait;
16
17
    /**
18
     * Displays a form to create a new table entity.
19
     *
20
     * @param Request $request
21
     * @return Response
22
     * @throws AccessDeniedException
23
     *
24
     */
25 10
    public function new(Request $request): Response
26
    {
27
        /* @var $em EntityManager */
28 10
        $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

28
        /** @scrutinizer ignore-call */ 
29
        $bundle = $this->getBundle();
Loading history...
29 10
        $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

29
        /** @scrutinizer ignore-call */ 
30
        $controller = $this->getController();
Loading history...
30 10
        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

30
        if (!$this->/** @scrutinizer ignore-call */ getPermessi()->canCreate($this->getController())) {
Loading history...
31 1
            throw new AccessDeniedException('Non si hanno i permessi per creare questo contenuto');
32
        }
33
34 9
        $crudtemplate = $this->getCrudTemplate($bundle, $controller, $this->getThisFunctionName());
0 ignored issues
show
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

34
        /** @scrutinizer ignore-call */ 
35
        $crudtemplate = $this->getCrudTemplate($bundle, $controller, $this->getThisFunctionName());
Loading history...
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

34
        $crudtemplate = $this->getCrudTemplate($bundle, $controller, $this->/** @scrutinizer ignore-call */ getThisFunctionName());
Loading history...
35 9
        $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

35
        /** @scrutinizer ignore-call */ 
36
        $tabellatemplate = $this->getTabellaTemplate($controller);
Loading history...
36
37 9
        $parametriform = $request->get('parametriform') ? json_decode($request->get('parametriform'), true) : [];
0 ignored issues
show
Bug introduced by
It seems like $request->get('parametriform') can also be of type null; however, parameter $json of json_decode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

37
        $parametriform = $request->get('parametriform') ? json_decode(/** @scrutinizer ignore-type */ $request->get('parametriform'), true) : [];
Loading history...
38
39 9
        $entityclass = $this->getEntityClassName();
0 ignored issues
show
Bug introduced by
It seems like getEntityClassName() 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

39
        /** @scrutinizer ignore-call */ 
40
        $entityclass = $this->getEntityClassName();
Loading history...
40 9
        $formclass = str_replace('Entity', 'Form', $entityclass);
41
42 9
        $entity = new $entityclass();
43 9
        $formType = $formclass . 'Type';
44 9
        $form = $this->createForm($formType, $entity, ['attr' => [
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

44
        /** @scrutinizer ignore-call */ 
45
        $form = $this->createForm($formType, $entity, ['attr' => [
Loading history...
45 9
                'id' => 'formdati' . $controller,
46 9
            ],
47 9
            '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

47
            'action' => $this->/** @scrutinizer ignore-call */ generateUrl($controller . '_new'), 'parametriform' => $parametriform,
Loading history...
48 9
        ]);
49
50 9
        $form->handleRequest($request);
51
52 9
        $twigparms = [
53 9
            'form' => $form->createView(),
54 9
            'nomecontroller' => ParametriTabella::setParameter($controller),
55 9
            'tabellatemplate' => $tabellatemplate,
56 9
            'permessi' => ParametriTabella::setParameter(json_encode($this->getPermessi()->toJson($controller))),
57 9
        ];
58
59 9
        if ($form->isSubmitted()) {
60 6
            if ($form->isValid()) {
61 5
                $entity = $form->getData();
62
63 5
                $entityManager = $this->em;
64 5
                $entityManager->persist($entity);
65 5
                $entityManager->flush();
66
67 5
                return new Response(
68 5
                    $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

68
                    $this->/** @scrutinizer ignore-call */ 
69
                           renderView($crudtemplate, $twigparms),
Loading history...
69 5
                    200
70 5
                );
71
            } else {
72
                //Quando non passa la validazione
73 1
                return new Response(
74 1
                    $this->renderView($crudtemplate, $twigparms),
75 1
                    400
76 1
                );
77
            }
78
        } else {
79
            //Quando viene richiesta una "nuova" new
80 9
            return new Response(
81 9
                $this->renderView($crudtemplate, $twigparms),
82 9
                200
83 9
            );
84
        }
85
    }
86
87
    /**
88
     * Displays a form to edit an existing table entity.
89
     *
90
     * @param Request $request
91
     * @param string|int $id
92
     * @return Response
93
     * @throws AccessDeniedException
94
     *
95
     */
96 8
    public function edit(Request $request, $id): Response
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed. ( Ignorable by Annotation )

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

96
    public function edit(/** @scrutinizer ignore-unused */ Request $request, $id): Response

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
97
    {
98
        /* @var $this->em EntityManager */
99 8
        $bundle = $this->getBundle();
100 8
        $controller = $this->getController();
101
102 8
        if (!$this->getPermessi()->canRead($this->getController())) {
103 1
            throw new AccessDeniedException('Non si hanno i permessi per modificare questo contenuto');
104
        }
105 7
        $crudtemplate = $this->getCrudTemplate($bundle, $controller, $this->getThisFunctionName());
106 7
        $tabellatemplate = $this->getTabellaTemplate($controller);
107
108 7
        $entityclass = $this->getEntityClassName();
109 7
        $formclass = str_replace('Entity', 'Form', $entityclass);
110
111 7
        $formType = $formclass . 'Type';
112
113 7
        $elencomodifiche = $this->elencoModifiche($controller, $id);
114
115
        /** @var class-string $entityclass */
116
        /** @var mixed $entity */
117 7
        $entity = $this->em->getRepository($entityclass)->find($id);
118
119 7
        if (!$entity) {
120 1
            throw $this->createNotFoundException('Impossibile trovare l\'entità ' . $controller . ' del record con id ' . $id . '.');
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

120
            throw $this->/** @scrutinizer ignore-call */ createNotFoundException('Impossibile trovare l\'entità ' . $controller . ' del record con id ' . $id . '.');
Loading history...
121
        }
122
        
123 7
        $editForm = $this->createForm(
124 7
            $formType,
125 7
            $entity,
126 7
            ['attr' => [
127 7
                        'id' => 'formdati' . $controller,
128 7
                    ],
129 7
                    'action' => $this->generateUrl($controller . '_update', ['id' => $entity->getId()]),
130 7
                ]
131 7
        );
132
133 7
        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

133
        return $this->/** @scrutinizer ignore-call */ render(
Loading history...
134 7
            $crudtemplate,
135 7
            [
136 7
                            'entity' => $entity,
137 7
                            'nomecontroller' => ParametriTabella::setParameter($controller),
138 7
                            'tabellatemplate' => $tabellatemplate,
139 7
                            'edit_form' => $editForm->createView(),
140 7
                            'elencomodifiche' => $elencomodifiche,
141 7
                            'permessi' => ParametriTabella::setParameter(json_encode($this->getPermessi()->toJson($controller))),
142 7
                        ]
143 7
        );
144
    }
145
146
    /**
147
     * Update an existing table entity.
148
     *
149
     * @param Request $request
150
     * @param int $id
151
     * @return Response
152
     * @throws AccessDeniedException
153
     */
154 9
    public function update(Request $request, $id): Response
155
    {
156
        /* @var $ EntityManager */
157 9
        $bundle = $this->getBundle();
158 9
        $controller = $this->getController();
159 9
        if (!$this->getPermessi()->canUpdate($this->getController())) {
160 1
            throw new AccessDeniedException('Non si hanno i permessi per modificare questo contenuto');
161
        }
162 8
        $crudtemplate = $this->getCrudTemplate($bundle, $controller, 'edit');
163 8
        $tabellatemplate = $this->getTabellaTemplate($controller);
164 8
        $elencomodifiche = $this->elencoModifiche($controller, $id);
165
166 8
        $entityclass = $this->getEntityClassName();
167 8
        $formclass = str_replace('Entity', 'Form', $entityclass);
168 8
        $formType = $formclass . 'Type';
169
170
        /** @var class-string $entityclass */
171
        /** @var mixed $entity */
172 8
        $entity = $this->em->getRepository($entityclass)->find($id);
173
174 8
        if (!$entity) {
175 1
            throw $this->createNotFoundException('Impossibile trovare l\'entità ' . $controller . ' per il record con id ' . $id);
176
        }
177
        
178 7
        $editForm = $this->createForm(
179 7
            $formType,
180 7
            $entity,
181 7
            ['attr' => [
182 7
                        'id' => 'formdati' . $controller,
183 7
                    ],
184 7
                    'action' => $this->generateUrl($controller . '_update', ['id' => $entity->getId()]),
185 7
                ]
186 7
        );
187
        
188
        /** @phpstan-ignore-next-line */
189 7
        $editForm->submit($request->request->get($editForm->getName()));
190
191 7
        if ($editForm->isValid()) {
192 7
            $originalData = $this->em->getUnitOfWork()->getOriginalEntityData($entity);
193
194 7
            $this->em->persist($entity);
195 7
            $this->em->flush();
196
197 7
            $newData = $this->em->getUnitOfWork()->getOriginalEntityData($entity);
198
            /** @var \Cdf\BiCoreBundle\Repository\StoricomodificheRepository $repoStorico */
199 7
            $repoStorico = $this->em->getRepository(Storicomodifiche::class);
200 7
            $changes = $repoStorico->isRecordChanged($controller, $originalData, $newData);
201
202 7
            if ($changes) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $changes of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
203
                /** @var \Cdf\BiCoreBundle\Entity\Operatori $currentUser */
204 2
                $currentUser = $this->getUser();
0 ignored issues
show
Bug introduced by
It seems like getUser() 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

204
                /** @scrutinizer ignore-call */ 
205
                $currentUser = $this->getUser();
Loading history...
205 2
                $repoStorico->saveHistory($controller, $changes, $id, $currentUser);
206
            }
207
208 7
            $continua = (int) $request->get('continua');
209 7
            if (0 === $continua) {
210 7
                return new Response('OK');
211
            } else {
212
                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

212
                return $this->/** @scrutinizer ignore-call */ redirect($this->generateUrl($controller . '_edit', ['id' => $id]));
Loading history...
213
            }
214
        }
215
216 1
        return new Response($this->renderView(
217 1
            $crudtemplate,
218 1
            [
219 1
                            'entity' => $entity,
220 1
                            'edit_form' => $editForm->createView(),
221 1
                            'nomecontroller' => ParametriTabella::setParameter($controller),
222 1
                            'tabellatemplate' => $tabellatemplate,
223 1
                            'elencomodifiche' => $elencomodifiche,
224 1
                        ]
225 1
        ), 400);
226
    }
227
228
    /**
229
     * Deletes a table entity.
230
     */
231 8
    public function delete(Request $request, string $token): Response
232
    {
233
        /* @var $this->em EntityManager */
234 8
        if (!$this->getPermessi()->canDelete($this->getController())) {
235 1
            throw new AccessDeniedException('Non si hanno i permessi per eliminare questo contenuto');
236
        }
237 7
        $entityclass = $this->getEntityClassName();
238
239 7
        $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

239
        /** @scrutinizer ignore-call */ 
240
        $isValidToken = $this->isCsrfTokenValid($this->getController(), $token);
Loading history...
240
241 7
        if (!$isValidToken) {
242
            throw $this->createNotFoundException('Token non valido:' . $this->getController() . " " . $token);
243
        }
244
245
        try {
246 7
            $qb = $this->em->createQueryBuilder();
247 7
            $ids = explode(',', $request->get('id'));
0 ignored issues
show
Bug introduced by
It seems like $request->get('id') can also be of type null; however, parameter $string of explode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

247
            $ids = explode(',', /** @scrutinizer ignore-type */ $request->get('id'));
Loading history...
248 7
            $qb->delete($entityclass, 'u')
249 7
                    ->andWhere('u.id IN (:ids)')
250 7
                    ->setParameter('ids', $ids);
251
252 7
            $query = $qb->getQuery();
253 7
            $query->execute();
254 2
        } catch (ForeignKeyConstraintViolationException $e) {
255 2
            $response = new Response($e->getMessage());
256 2
            $response->setStatusCode(501);
257
258 2
            return $response;
259
        } catch (\Exception $e) {
260
            $response = new Response($e->getMessage());
261
            $response->setStatusCode(200);
262
263
            return $response;
264
        }
265
266 5
        return new Response('Operazione eseguita con successo');
267
    }
268
269
    /**
270
     *
271
     * @param string $controller
272
     * @param string|int $id
273
     * @return array<Storicomodifiche>
274
     */
275 8
    public function elencoModifiche(string $controller, $id): array
276
    {
277 8
        $risultato = $this->em->getRepository(Storicomodifiche::class)->findBy(
278 8
            [
279 8
                    'nometabella' => $controller,
280 8
                    'idtabella' => $id,
281 8
                ],
282 8
            ['giorno' => 'DESC']
283 8
        );
284
285 8
        return $risultato;
286
    }
287
}
288