FiCrudController   A
last analyzed

Complexity

Total Complexity 40

Size/Duplication

Total Lines 454
Duplicated Lines 0 %

Test Coverage

Coverage 86.35%

Importance

Changes 6
Bugs 0 Features 0
Metric Value
wmc 40
eloc 261
c 6
b 0
f 0
dl 0
loc 454
ccs 215
cts 249
cp 0.8635
rs 9.2

13 Methods

Rating   Name   Duplication   Size   Complexity  
A aggiornaAction() 0 28 3
A createDeleteForm() 0 5 1
A deleteAction() 0 32 4
A newAction() 0 42 3
A setup() 0 19 6
B updateAction() 0 77 7
A editAction() 0 54 4
A indexAction() 0 52 3
B createAction() 0 58 5
A getBundle() 0 3 1
A getController() 0 3 1
A getNamespace() 0 3 1
A getAction() 0 3 1

How to fix   Complexity   

Complex Class

Complex classes like FiCrudController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use FiCrudController, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Fi\CoreBundle\Controller;
4
5
use Doctrine\DBAL\Exception\ForeignKeyConstraintViolationException;
6
use Doctrine\ORM\EntityManager;
7
use ReflectionClass;
8
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
9
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
10
use Symfony\Component\Form\Form;
11
use Symfony\Component\HttpFoundation\Request;
12
use Symfony\Component\HttpFoundation\Response;
13
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
14
15
class FiCrudController extends Controller
16
{
17
18
    public static $namespace;
19
    public static $bundle;
20
    public static $controller;
21
    public static $action;
22
    public static $parametrigriglia;
23
    public static $canRead;
24
    public static $canDelete;
25
    public static $canCreate;
26
    public static $canUpdate;
27
28 31
    protected function setup(Request $request)
29
    {
30 31
        $matches = array();
31 31
        $controllo = new ReflectionClass(get_class($this));
32
33 31
        preg_match('/(.*)\\\(.*)Bundle\\\Controller\\\(.*)Controller/', $controllo->name, $matches);
34 31
        if (count($matches) == 0) {
35
            preg_match('/(.*)(.*)\\\Controller\\\(.*)Controller/', $controllo->name, $matches);
36
        }
37 31
        self::$namespace = $matches[1];
38 31
        self::$bundle = $matches[2];
39 31
        self::$controller = $matches[3];
40 31
        self::$action = substr($request->attributes->get('_controller'), strrpos($request->attributes->get('_controller'), ':') + 1);
41
42 31
        $gestionepermessi = $this->get('ficorebundle.gestionepermessi');
43 31
        self::$canRead = ($gestionepermessi->leggere(array('modulo' => self::$controller)) ? 1 : 0);
44 31
        self::$canDelete = ($gestionepermessi->cancellare(array('modulo' => self::$controller)) ? 1 : 0);
45 31
        self::$canCreate = ($gestionepermessi->creare(array('modulo' => self::$controller)) ? 1 : 0);
46 31
        self::$canUpdate = ($gestionepermessi->aggiornare(array('modulo' => self::$controller)) ? 1 : 0);
47 31
    }
48
49
    /**
50
     * Lists all tables entities.
51
     */
52 21
    public function indexAction(Request $request)
53
    {
54
        /* @var $em EntityManager */
55 21
        $this->setup($request);
56 21
        $namespace = $this->getNamespace();
57 21
        $bundle = $this->getBundle();
58 21
        $controller = $this->getController();
59
60 21
        if (!self::$canRead) {
61 15
            throw new AccessDeniedException("Non si hanno i permessi per visualizzare questo contenuto");
62
        }
63
64 8
        $container = $this->container;
65
66 8
        $idpassato = $request->get('id');
67
68 8
        $nomebundle = $namespace . $bundle . 'Bundle';
69
70 8
        $repotabelle = $this->get('OpzioniTabella_repository');
71
72 8
        $paricevuti = array('nomebundle' => $nomebundle, 'nometabella' => $controller, 'container' => $container);
73
74 8
        $griglia = $this->get("ficorebundle.griglia");
75 8
        $testatagriglia = $griglia->testataPerGriglia($paricevuti);
76
77 8
        $testatagriglia['multisearch'] = 1;
78 8
        $testatagriglia['showconfig'] = 1;
79 8
        $testatagriglia['overlayopen'] = 1;
80 8
        $testatagriglia['showadd'] = self::$canCreate;
81 8
        $testatagriglia['showedit'] = self::$canUpdate;
82 8
        $testatagriglia['showdel'] = self::$canDelete;
83 8
        $testatagriglia["filterToolbar_searchOnEnter"] = true;
84 8
        $testatagriglia["filterToolbar_searchOperators"] = true;
85
86 8
        $testatagriglia['parametritesta'] = json_encode($paricevuti);
87
88 8
        $this->setParametriGriglia(array('request' => $request));
0 ignored issues
show
introduced by
The method setParametriGriglia() does not exist on Fi\CoreBundle\Controller\FiCrudController. Maybe you want to declare this class abstract? ( Ignorable by Annotation )

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

88
        $this->/** @scrutinizer ignore-call */ 
89
               setParametriGriglia(array('request' => $request));
Loading history...
89 8
        $testatagriglia['parametrigriglia'] = json_encode(self::$parametrigriglia);
90
91 8
        $template = $nomebundle . ':' . $controller . ':index.html.twig';
92 8
        if (!$this->get('templating')->exists($template)) {
93
            $template = $controller . '/index.html.twig';
94
        }
95
96 8
        $testata = $repotabelle->editTestataFormTabelle($testatagriglia, $controller, $container);
97 8
        return $this->render(
98 8
            $template,
99
            array(
100 8
                    'nomecontroller' => $controller,
101 8
                    'testata' => $testata,
102 8
                    'canread' => self::$canRead,
103 8
                    'idpassato' => $idpassato,
104
                        )
105
        );
106
    }
107
108
    /**
109
     * Creates a new table entity.
110
     */
111 17
    public function createAction(Request $request)
112
    {
113 17
        $this->setup($request);
114 17
        $namespace = $this->getNamespace();
115 17
        $bundle = $this->getBundle();
116 17
        $controller = $this->getController();
117
118 17
        if (!self::$canCreate) {
119 15
            throw new AccessDeniedException("Non si hanno i permessi per creare questo contenuto");
120
        }
121
122 6
        $nomebundle = $namespace . $bundle . 'Bundle';
123 6
        $classbundle = $namespace . '\\' . $bundle . 'Bundle' . '\\Entity\\' . $controller;
124 6
        $formbundle = $namespace . '\\' . $bundle . 'Bundle' . '\\Form\\' . $controller;
125
126 6
        if (!class_exists($classbundle)) {
127
            $nomebundle = $namespace . $bundle . 'Bundle';
0 ignored issues
show
Unused Code introduced by
The assignment to $nomebundle is dead and can be removed.
Loading history...
128
            $classbundle = $namespace . '\\Entity\\' . $controller;
129
            $formbundle = $namespace . '\\Form\\' . $controller;
130
            $template = $controller . '/new.html.twig';
131
        } else {
132 6
            $template = $nomebundle . ':' . $controller . ':new.html.twig';
133
        }
134
135 6
        $entity = new $classbundle();
136 6
        $formType = $formbundle . 'Type';
137
138 6
        $form = $this->createForm(
139 6
            $formType,
140 6
            $entity,
141
            array('attr' => array(
142 6
                'id' => 'formdati' . $controller,
143
                ),
144 6
                'action' => $this->generateUrl($controller . '_create'),
145
                )
146
        );
147
148 6
        $form->submit($request->request->get($form->getName()));
149
150 6
        if ($form->isValid()) {
151 2
            $em = $this->getDoctrine()->getManager();
152 2
            $em->persist($entity);
153 2
            $em->flush();
154
155 2
            $continua = (int) $request->get('continua');
156 2
            if ($continua === 0) {
157 2
                return new Response('OK');
158
            } else {
159
                return $this->redirect($this->generateUrl($controller . '_edit', array('id' => $entity->getId())));
160
            }
161
        }
162
163 4
        return $this->render(
164 4
            $template,
165
            array(
166 4
                    'nomecontroller' => $controller,
167 4
                    'entity' => $entity,
168 4
                    'form' => $form->createView(),
169
                        )
170
        );
171
    }
172
173
    /**
174
     * Displays a form to create a new table entity.
175
     */
176 3
    public function newAction(Request $request)
177
    {
178 3
        $this->setup($request);
179 3
        $namespace = $this->getNamespace();
180 3
        $bundle = $this->getBundle();
181 3
        $controller = $this->getController();
182
183 3
        if (!self::$canCreate) {
184
            throw new AccessDeniedException("Non si hanno i permessi per creare questo contenuto");
185
        }
186
187 3
        $nomebundle = $namespace . $bundle . 'Bundle';
188 3
        $classbundle = $namespace . '\\' . $bundle . 'Bundle' . '\\Entity\\' . $controller;
189 3
        $formbundle = $namespace . '\\' . $bundle . 'Bundle' . '\\Form\\' . $controller;
190 3
        $formType = $formbundle . 'Type';
191 3
        if (!class_exists($classbundle)) {
192
            $nomebundle = $namespace . $bundle . 'Bundle';
0 ignored issues
show
Unused Code introduced by
The assignment to $nomebundle is dead and can be removed.
Loading history...
193
            $classbundle = $namespace . '\\Entity\\' . $controller;
194
            $formbundle = $namespace . '\\Form\\' . $controller;
195
            $formType = $formbundle . 'Type';
196
            $template = $controller . '/new.html.twig';
197
        } else {
198 3
            $template = $nomebundle . ':' . $controller . ':new.html.twig';
199
        }
200 3
        $entity = new $classbundle();
201
202 3
        $form = $this->createForm(
203 3
            $formType,
204 3
            $entity,
205
            array('attr' => array(
206 3
                'id' => 'formdati' . $controller,
207
                ),
208 3
                'action' => $this->generateUrl($controller . '_create'),
209
                )
210
        );
211
212 3
        return $this->render(
213 3
            $template,
214
            array(
215 3
                    'nomecontroller' => $controller,
216 3
                    'entity' => $entity,
217 3
                    'form' => $form->createView(),
218
                        )
219
        );
220
    }
221
222
    /**
223
     * Displays a form to edit an existing table entity.
224
     */
225 18
    public function editAction(Request $request, $id)
226
    {
227
        /* @var $em EntityManager */
228 18
        $this->setup($request);
229 18
        $namespace = $this->getNamespace();
230 18
        $bundle = $this->getBundle();
231 18
        $controller = $this->getController();
232
233 18
        if (!self::$canUpdate) {
234 15
            throw new AccessDeniedException("Non si hanno i permessi per modificare questo contenuto");
235
        }
236
237 7
        $nomebundle = $namespace . $bundle . 'Bundle';
238 7
        $formbundle = $namespace . '\\' . $bundle . 'Bundle' . '\\Form\\' . $controller;
239 7
        $formType = $formbundle . 'Type';
240 7
        if (!class_exists($formType)) {
241
            $nomebundle = $namespace . $bundle . 'Bundle';
242
            $formbundle = $namespace . '\\Form\\' . $controller;
243
            $formType = $formbundle . 'Type';
244
            $template = $controller . '/edit.html.twig';
245
        } else {
246 7
            $template = $nomebundle . ':' . $controller . ':edit.html.twig';
247
        }
248
249 7
        $elencomodifiche = $this->elencoModifiche($controller, $id);
0 ignored issues
show
introduced by
The method elencoModifiche() does not exist on Fi\CoreBundle\Controller\FiCrudController. Maybe you want to declare this class abstract? ( Ignorable by Annotation )

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

249
        /** @scrutinizer ignore-call */ 
250
        $elencomodifiche = $this->elencoModifiche($controller, $id);
Loading history...
250
251 7
        $em = $this->getDoctrine()->getManager();
252
253 7
        $entity = $em->getRepository($nomebundle . ':' . $controller)->find($id);
254
255 7
        if (!$entity) {
256
            throw $this->createNotFoundException('Unable to find ' . $controller . ' entity.');
257
        }
258
259 7
        $editForm = $this->createForm(
260 7
            $formType,
261 7
            $entity,
262
            array('attr' => array(
263 7
                'id' => 'formdati' . $controller,
264
                ),
265 7
                'action' => $this->generateUrl($controller . '_update', array('id' => $entity->getId())),
266
                )
267
        );
268
269 7
        $deleteForm = $this->createDeleteForm($id);
270
271 7
        return $this->render(
272 7
            $template,
273
            array(
274 7
                    'entity' => $entity,
275 7
                    'nomecontroller' => $controller,
276 7
                    'edit_form' => $editForm->createView(),
277 7
                    'delete_form' => $deleteForm->createView(),
278 7
                    'elencomodifiche' => $elencomodifiche,
279
                        )
280
        );
281
    }
282
283
    /**
284
     * Edits an existing table entity.
285
     */
286 17
    public function updateAction(Request $request, $id)
287
    {
288
        /* @var $em EntityManager */
289 17
        $this->setup($request);
290 17
        $namespace = $this->getNamespace();
291 17
        $bundle = $this->getBundle();
292 17
        $controller = $this->getController();
293
294 17
        if (!self::$canUpdate) {
295 15
            throw new AccessDeniedException("Non si hanno i permessi per aggiornare questo contenuto");
296
        }
297
298 6
        $nomebundle = $namespace . $bundle . 'Bundle';
299 6
        $formbundle = $namespace . '\\' . $bundle . 'Bundle' . '\\Form\\' . $controller;
300 6
        $formType = $formbundle . 'Type';
301
302 6
        if (!class_exists($formType)) {
303
            $nomebundle = $namespace . $bundle . 'Bundle';
304
            $formbundle = $namespace . '\\Form\\' . $controller;
305
            $formType = $formbundle . 'Type';
306
            $template = $controller . '/edit.html.twig';
307
        } else {
308 6
            $template = $nomebundle . ':' . $controller . ':edit.html.twig';
309
        }
310
311 6
        $repoStorico = $this->container->get('Storicomodifiche_repository');
312
313 6
        $em = $this->getDoctrine()->getManager();
314
315 6
        $entity = $em->getRepository($nomebundle . ':' . $controller)->find($id);
316
317 6
        if (!$entity) {
318
            throw $this->createNotFoundException('Unable to find ' . $controller . ' entity.');
319
        }
320
321 6
        $deleteForm = $this->createDeleteForm($id);
322
323 6
        $editForm = $this->createForm(
324 6
            $formType,
325 6
            $entity,
326
            array('attr' => array(
327 6
                'id' => 'formdati' . $controller,
328
                ),
329 6
                'action' => $this->generateUrl($controller . '_update', array('id' => $entity->getId())),
330
                )
331
        );
332
333 6
        $editForm->submit($request->request->get($editForm->getName()));
334
335 6
        if ($editForm->isValid()) {
336 3
            $originalData = $em->getUnitOfWork()->getOriginalEntityData($entity);
0 ignored issues
show
Bug introduced by
The method getUnitOfWork() does not exist on Doctrine\Persistence\ObjectManager. It seems like you code against a sub-type of Doctrine\Persistence\ObjectManager such as Doctrine\ORM\EntityManagerInterface or Doctrine\ORM\Decorator\EntityManagerDecorator. ( Ignorable by Annotation )

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

336
            $originalData = $em->/** @scrutinizer ignore-call */ getUnitOfWork()->getOriginalEntityData($entity);
Loading history...
337
338 3
            $em->persist($entity);
339 3
            $em->flush();
340
341 3
            $newData = $em->getUnitOfWork()->getOriginalEntityData($entity);
342 3
            $changes = $repoStorico->isRecordChanged($nomebundle, $controller, $originalData, $newData);
343
344 3
            if ($changes) {
345 1
                $repoStorico->saveHistory($controller, $changes, $id, $this->getUser());
346
            }
347
348 3
            $continua = (int) $request->get('continua');
349 3
            if ($continua === 0) {
350 3
                return new Response('OK');
351
            } else {
352
                return $this->redirect($this->generateUrl($controller . '_edit', array('id' => $id)));
353
            }
354
        }
355
356 3
        return $this->render(
357 3
            $template,
358
            array(
359 3
                    'entity' => $entity,
360 3
                    'edit_form' => $editForm->createView(),
361 3
                    'delete_form' => $deleteForm->createView(),
362 3
                    'nomecontroller' => $controller,
363
                        )
364
        );
365
    }
366
367
    /**
368
     * Edits an existing table entity.
369
     */
370 1
    public function aggiornaAction(Request $request)
371
    {
372
        /* @var $em EntityManager */
373 1
        $this->setup($request);
374 1
        $namespace = $this->getNamespace();
375 1
        $bundle = $this->getBundle();
376 1
        $controller = $this->getController();
377
378 1
        if (!self::$canUpdate) {
379
            throw new AccessDeniedException("Non si hanno i permessi per aggiornare questo contenuto");
380
        }
381
382 1
        $nomebundle = $namespace . $bundle . 'Bundle';
383
384 1
        $id = $request->get('id');
385
386 1
        $em = $this->getDoctrine()->getManager();
387
388 1
        $entity = $em->getRepository($nomebundle . ':' . $controller)->find($id);
389
390 1
        if (!$entity) {
391
            throw $this->createNotFoundException('Unable to find ' . $controller . ' entity.');
392
        }
393
394 1
        throw $this->createNotFoundException("Implementare a seconda dell'esigenza 'aggiornaAction' del controller "
395 1
                . $nomebundle
396 1
                . '/'
397 1
                . $controller);
398
    }
399
400
    /**
401
     * Deletes a table entity.
402
     */
403 17
    public function deleteAction(Request $request)
404
    {
405
        /* @var $em EntityManager */
406 17
        $this->setup($request);
407 17
        if (!self::$canDelete) {
408 15
            throw new AccessDeniedException("Non si hanno i permessi per aggiornare questo contenuto");
409
        }
410 6
        $namespace = $this->getNamespace();
411 6
        $bundle = $this->getBundle();
412 6
        $controller = $this->getController();
413
414 6
        $nomebundle = $namespace . $bundle . 'Bundle';
415
416
        try {
417 6
            $em = $this->getDoctrine()->getManager();
418 6
            $qb = $em->createQueryBuilder();
0 ignored issues
show
Bug introduced by
The method createQueryBuilder() does not exist on Doctrine\Persistence\ObjectManager. It seems like you code against a sub-type of Doctrine\Persistence\ObjectManager such as Doctrine\ORM\EntityManagerInterface or Doctrine\ORM\Decorator\EntityManagerDecorator. ( Ignorable by Annotation )

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

418
            /** @scrutinizer ignore-call */ 
419
            $qb = $em->createQueryBuilder();
Loading history...
419 6
            $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

419
            $ids = explode(',', /** @scrutinizer ignore-type */ $request->get('id'));
Loading history...
420 6
            $qb->delete($nomebundle . ':' . $controller, 'u')
421 6
                    ->andWhere('u.id IN (:ids)')
422 6
                    ->setParameter('ids', $ids);
423
424 6
            $query = $qb->getQuery();
425 6
            $query->execute();
426
        } catch (ForeignKeyConstraintViolationException $e) {
427
            return new Response('404');
428
        } catch (\Exception $e) {
429
            $response = new Response($e->getMessage());
430
            $response->setStatusCode('200');
431
            return $response;
432
        }
433
434 6
        return new Response('OK');
435
    }
436
437
    /**
438
     * Creates a form to delete a table entity by id.
439
     *
440
     * @param mixed $id The entity id
441
     *
442
     * @return Form The form
443
     */
444 6
    protected function createDeleteForm($id)
445
    {
446 6
        return $this->createFormBuilder(array('id' => $id))
447 6
                        ->add('id', get_class(new HiddenType()))
448 6
                        ->getForm();
449
    }
450
451 31
    protected function getNamespace()
452
    {
453 31
        return self::$namespace;
454
    }
455
456 31
    protected function getBundle()
457
    {
458 31
        return self::$bundle;
459
    }
460
461 31
    protected function getController()
462
    {
463 31
        return self::$controller;
464
    }
465
466
    protected function getAction()
467
    {
468
        return self::$action;
469
    }
470
}
471