Completed
Push — master ( d9bece...2ea354 )
by Andrea
10:06
created

FiCrudController   A

Complexity

Total Complexity 24

Size/Duplication

Total Lines 377
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 15

Test Coverage

Coverage 80.38%

Importance

Changes 4
Bugs 0 Features 0
Metric Value
wmc 24
c 4
b 0
f 0
lcom 1
cbo 15
dl 0
loc 377
ccs 168
cts 209
cp 0.8038
rs 9.1666

13 Methods

Rating   Name   Duplication   Size   Complexity  
A setup() 0 12 1
A createDeleteForm() 0 6 1
A getNamespace() 0 4 1
A getBundle() 0 4 1
A getController() 0 4 1
A getAction() 0 4 1
A createAction() 0 48 3
B newAction() 0 33 1
B editAction() 0 45 2
B updateAction() 0 67 5
B aggiornaAction() 0 25 2
B deleteAction() 0 32 2
B indexAction() 0 44 3
1
<?php
2
3
namespace Fi\CoreBundle\Controller;
4
5
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
6
use Symfony\Component\HttpFoundation\Request;
7
use Symfony\Component\HttpFoundation\Response;
8
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
9
10
class FiCrudController extends Controller
11
{
12
13
    public static $namespace;
14
    public static $bundle;
15
    public static $controller;
16
    public static $action;
17
    public static $parametrigriglia;
18
19 13
    protected function setup(Request $request)
20
    {
21 13
        $matches = array();
22 13
        $controllo = new \ReflectionClass(get_class($this));
23
24 13
        preg_match('/(.*)\\\(.*)Bundle\\\Controller\\\(.*)Controller/', $controllo->name, $matches);
25
26 13
        self::$namespace = $matches[1];
27 13
        self::$bundle = $matches[2];
28 13
        self::$controller = $matches[3];
29 13
        self::$action = substr($request->attributes->get('_controller'), strrpos($request->attributes->get('_controller'), ':') + 1);
30 13
    }
31
    /**
32
     * Lists all tables entities.
33
     */
34 4
    public function indexAction(Request $request)
35
    {
36
        /* @var $em \Doctrine\ORM\EntityManager */
37 4
        $this->setup($request);
38 4
        $namespace = $this->getNamespace();
39 4
        $bundle = $this->getBundle();
40 4
        $controller = $this->getController();
41 4
        $container = $this->container;
42
43 4
        $gestionepermessi = $this->get('ficorebundle.gestionepermessi');
44 4
        $canRead = ($gestionepermessi->leggere(array('modulo' => $controller)) ? 1 : 0);
45 4
        if (!$canRead) {
46
            throw new AccessDeniedException("Non si hanno i permessi per visualizzare questo contenuto");
47
        }
48 4
        $idpassato = $request->get('id');
49
50 4
        $nomebundle = $namespace . $bundle . 'Bundle';
51
52 4
        $repotabelle = $this->get('OpzioniTabella_repository');
53
54 4
        $paricevuti = array('nomebundle' => $nomebundle, 'nometabella' => $controller, 'container' => $container);
55
56 4
        $testatagriglia = Griglia::testataPerGriglia($paricevuti);
57
58 4
        $testatagriglia['multisearch'] = 1;
59 4
        $testatagriglia['showconfig'] = 1;
60 4
        $testatagriglia['overlayopen'] = 1;
61
62 4
        $testatagriglia['parametritesta'] = json_encode($paricevuti);
63
64 4
        $this->setParametriGriglia(array('request' => $request));
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Fi\CoreBundle\Controller\FiCrudController as the method setParametriGriglia() does only exist in the following sub-classes of Fi\CoreBundle\Controller\FiCrudController: Fi\CoreBundle\Controller\FfprincipaleController, Fi\CoreBundle\Controller\FfsecondariaController, Fi\CoreBundle\Controller\FiController, Fi\CoreBundle\Controller\FiCoreController, Fi\CoreBundle\Controller...uApplicazioneController, Fi\CoreBundle\Controller\MenuController, Fi\CoreBundle\Controller\OperatoriController, Fi\CoreBundle\Controller\OpzioniTabellaController, Fi\CoreBundle\Controller\PermessiController, Fi\CoreBundle\Controller\RuoliController, Fi\CoreBundle\Controller\StampatabellaController, Fi\CoreBundle\Controller...ricomodificheController, Fi\CoreBundle\Controller\TabelleController. 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...
65 4
        $testatagriglia['parametrigriglia'] = json_encode(self::$parametrigriglia);
66
67 4
        $testata = $repotabelle->editTestataFormTabelle($testatagriglia, $controller, $container);
68 4
        return $this->render(
69 4
            $nomebundle . ':' . $controller . ':index.html.twig',
70
            array(
71 4
                    'nomecontroller' => $controller,
72 4
                    'testata' => $testata,
73 4
                    'canread' => $canRead,
74 4
                    'idpassato' => $idpassato,
75
                        )
76 4
        );
77
    }
78
79
    /**
80
     * Creates a new table entity.
81
     */
82 2
    public function createAction(Request $request)
83
    {
84 2
        $this->setup($request);
85 2
        $namespace = $this->getNamespace();
86 2
        $bundle = $this->getBundle();
87 2
        $controller = $this->getController();
88
89 2
        $nomebundle = $namespace . $bundle . 'Bundle';
90 2
        $classbundle = $namespace . '\\' . $bundle . 'Bundle' . '\\Entity\\' . $controller;
91 2
        $formbundle = $namespace . '\\' . $bundle . 'Bundle' . '\\Form\\' . $controller;
92
93 2
        $entity = new $classbundle();
94 2
        $formType = $formbundle . 'Type';
95
96 2
        $form = $this->createForm(
97 2
            $formType,
98 2
            $entity,
99
            array('attr' => array(
100 2
                'id' => 'formdati' . $controller,
101 2
                ),
102 2
                'action' => $this->generateUrl($controller . '_create'),
103
                )
104 2
        );
105
106 2
        $form->submit($request->request->get($form->getName()));
107
108 2
        if ($form->isValid()) {
109 2
            $em = $this->getDoctrine()->getManager();
110 2
            $em->persist($entity);
111 2
            $em->flush();
112
113 2
            $continua = $request->get('continua');
114 2
            if ($continua == 0) {
115 2
                return new Response('OK');
116
            } else {
117
                return $this->redirect($this->generateUrl($controller . '_edit', array('id' => $entity->getId())));
118
            }
119
        }
120
121
        return $this->render(
122
            $nomebundle . ':' . $controller . ':new.html.twig',
123
            array(
124
                    'nomecontroller' => $controller,
125
                    'entity' => $entity,
126
                    'form' => $form->createView(),
127
                        )
128
        );
129
    }
130
131
    /**
132
     * Displays a form to create a new table entity.
133
     */
134 2
    public function newAction(Request $request)
135
    {
136 2
        $this->setup($request);
137 2
        $namespace = $this->getNamespace();
138 2
        $bundle = $this->getBundle();
139 2
        $controller = $this->getController();
140
141 2
        $nomebundle = $namespace . $bundle . 'Bundle';
142 2
        $classbundle = $namespace . '\\' . $bundle . 'Bundle' . '\\Entity\\' . $controller;
143 2
        $formbundle = $namespace . '\\' . $bundle . 'Bundle' . '\\Form\\' . $controller;
144 2
        $formType = $formbundle . 'Type';
145
146 2
        $entity = new $classbundle();
147
148 2
        $form = $this->createForm(
149 2
            $formType,
150 2
            $entity,
151
            array('attr' => array(
152 2
                'id' => 'formdati' . $controller,
153 2
                ),
154 2
                'action' => $this->generateUrl($controller . '_create'),
155
                )
156 2
        );
157
158 2
        return $this->render(
159 2
            $nomebundle . ':' . $controller . ':new.html.twig',
160
            array(
161 2
                    'nomecontroller' => $controller,
162 2
                    'entity' => $entity,
163 2
                    'form' => $form->createView(),
164
                        )
165 2
        );
166
    }
167
168
    /**
169
     * Displays a form to edit an existing table entity.
170
     */
171 2
    public function editAction(Request $request, $id)
172
    {
173
        /* @var $em \Doctrine\ORM\EntityManager */
174 2
        $this->setup($request);
175 2
        $namespace = $this->getNamespace();
176 2
        $bundle = $this->getBundle();
177 2
        $controller = $this->getController();
178
179 2
        $nomebundle = $namespace . $bundle . 'Bundle';
180 2
        $formbundle = $namespace . '\\' . $bundle . 'Bundle' . '\\Form\\' . $controller;
181 2
        $formType = $formbundle . 'Type';
182
183 2
        $elencomodifiche = $this->elencoModifiche($nomebundle, $controller, $id);
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Fi\CoreBundle\Controller\FiCrudController as the method elencoModifiche() does only exist in the following sub-classes of Fi\CoreBundle\Controller\FiCrudController: Fi\CoreBundle\Controller\FfprincipaleController, Fi\CoreBundle\Controller\FfsecondariaController, Fi\CoreBundle\Controller\FiController, Fi\CoreBundle\Controller\FiCoreController, Fi\CoreBundle\Controller...uApplicazioneController, Fi\CoreBundle\Controller\MenuController, Fi\CoreBundle\Controller\OperatoriController, Fi\CoreBundle\Controller\OpzioniTabellaController, Fi\CoreBundle\Controller\PermessiController, Fi\CoreBundle\Controller\RuoliController, Fi\CoreBundle\Controller\StampatabellaController, Fi\CoreBundle\Controller...ricomodificheController, Fi\CoreBundle\Controller\TabelleController. 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...
184
185 2
        $em = $this->getDoctrine()->getManager();
186
187 2
        $entity = $em->getRepository($nomebundle . ':' . $controller)->find($id);
188
189 2
        if (!$entity) {
190
            throw $this->createNotFoundException('Unable to find ' . $controller . ' entity.');
191
        }
192
193 2
        $editForm = $this->createForm(
194 2
            $formType,
195 2
            $entity,
196
            array('attr' => array(
197 2
                'id' => 'formdati' . $controller,
198 2
                ),
199 2
                'action' => $this->generateUrl($controller . '_update', array('id' => $entity->getId())),
200
                )
201 2
        );
202
203 2
        $deleteForm = $this->createDeleteForm($id);
204
205 2
        return $this->render(
206 2
            $nomebundle . ':' . $controller . ':edit.html.twig',
207
            array(
208 2
                    'entity' => $entity,
209 2
                    'nomecontroller' => $controller,
210 2
                    'edit_form' => $editForm->createView(),
211 2
                    'delete_form' => $deleteForm->createView(),
212 2
                    'elencomodifiche' => $elencomodifiche,
213
                        )
214 2
        );
215
    }
216
217
    /**
218
     * Edits an existing table entity.
219
     */
220 2
    public function updateAction(Request $request, $id)
221
    {
222
        /* @var $em \Doctrine\ORM\EntityManager */
223 2
        $this->setup($request);
224 2
        $namespace = $this->getNamespace();
225 2
        $bundle = $this->getBundle();
226 2
        $controller = $this->getController();
227
228 2
        $nomebundle = $namespace . $bundle . 'Bundle';
229 2
        $formbundle = $namespace . '\\' . $bundle . 'Bundle' . '\\Form\\' . $controller;
230 2
        $formType = $formbundle . 'Type';
231
232 2
        $repoStorico = $this->container->get('Storicomodifiche_repository');
233
234 2
        $em = $this->getDoctrine()->getManager();
235
236 2
        $entity = $em->getRepository($nomebundle . ':' . $controller)->find($id);
237
238 2
        if (!$entity) {
239
            throw $this->createNotFoundException('Unable to find ' . $controller . ' entity.');
240
        }
241
242 2
        $deleteForm = $this->createDeleteForm($id);
243
244 2
        $editForm = $this->createForm(
245 2
            $formType,
246 2
            $entity,
247
            array('attr' => array(
248 2
                'id' => 'formdati' . $controller,
249 2
                ),
250 2
                'action' => $this->generateUrl($controller . '_update', array('id' => $entity->getId())),
251
                )
252 2
        );
253
254 2
        $editForm->submit($request->request->get($editForm->getName()));
255
256 2
        if ($editForm->isValid()) {
257 2
            $originalData = $em->getUnitOfWork()->getOriginalEntityData($entity);
258
259 2
            $em->persist($entity);
260 2
            $em->flush();
261
262 2
            $newData = $em->getUnitOfWork()->getOriginalEntityData($entity);
263 2
            $changes = $repoStorico->isRecordChanged($nomebundle, $controller, $originalData, $newData);
264
265 2
            if ($changes) {
266 1
                $repoStorico->saveHistory($controller, $changes, $id, $this->getUser());
267 1
            }
268
269 2
            $continua = $request->get('continua');
270 2
            if ($continua == 0) {
271 2
                return new Response('OK');
272
            } else {
273
                return $this->redirect($this->generateUrl($controller . '_edit', array('id' => $id)));
274
            }
275
        }
276
277
        return $this->render(
278
            $nomebundle . ':' . $controller . ':edit.html.twig',
279
            array(
280
                    'entity' => $entity,
281
                    'edit_form' => $editForm->createView(),
282
                    'delete_form' => $deleteForm->createView(),
283
                    'nomecontroller' => $controller,
284
                        )
285
        );
286
    }
287
288
    /**
289
     * Edits an existing table entity.
290
     */
291
    public function aggiornaAction(Request $request)
292
    {
293
        /* @var $em \Doctrine\ORM\EntityManager */
294
        $this->setup($request);
295
        $namespace = $this->getNamespace();
296
        $bundle = $this->getBundle();
297
        $controller = $this->getController();
298
299
        $nomebundle = $namespace . $bundle . 'Bundle';
300
301
        $id = $this->get('request')->request->get('id');
302
303
        $em = $this->getDoctrine()->getManager();
304
305
        $entity = $em->getRepository($nomebundle . ':' . $controller)->find($id);
306
307
        if (!$entity) {
308
            throw $this->createNotFoundException('Unable to find ' . $controller . ' entity.');
309
        }
310
311
        throw $this->createNotFoundException("Implementare a seconda dell'esigenza 'aggiornaAction' del controller "
312
                . $nomebundle
313
                . '/'
314
                . $controller);
315
    }
316
317
    /**
318
     * Deletes a table entity.
319
     */
320 2
    public function deleteAction(Request $request)
321
    {
322
        /* @var $em \Doctrine\ORM\EntityManager */
323 2
        $this->setup($request);
324 2
        $namespace = $this->getNamespace();
325 2
        $bundle = $this->getBundle();
326 2
        $controller = $this->getController();
327
328 2
        $nomebundle = $namespace . $bundle . 'Bundle';
329
330
        //if (!$request->isXmlHttpRequest()) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
331
        //    $request->checkCSRFProtection();
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
332
        //}
333
        try {
334 2
            $em = $this->getDoctrine()->getManager();
335 2
            $qb = $em->createQueryBuilder();
336 2
            $ids = explode(',', $request->get('id'));
337 2
            $qb->delete($nomebundle . ':' . $controller, 'u')
338 2
                    ->andWhere('u.id IN (:ids)')
339 2
                    ->setParameter('ids', $ids);
340
341 2
            $query = $qb->getQuery();
342 2
            $query->execute();
343 2
        } catch (\Exception $e) {
344
            $response = new Response();
345
            $response->setStatusCode('200');
346
347
            return new Response('404');
348
        }
349
350 2
        return new Response('OK');
351
    }
352
353
    /**
354
     * Creates a form to delete a table entity by id.
355
     *
356
     * @param mixed $id The entity id
357
     *
358
     * @return \Symfony\Component\Form\Form The form
359
     */
360
    protected function createDeleteForm($id)
361
    {
362
        return $this->createFormBuilder(array('id' => $id))
363
                        ->add('id', get_class(new \Symfony\Component\Form\Extension\Core\Type\HiddenType()))
364
                        ->getForm();
365
    }
366
    
367 13
    protected function getNamespace()
368
    {
369 13
        return self::$namespace;
370
    }
371
372 13
    protected function getBundle()
373
    {
374 13
        return self::$bundle;
375
    }
376
377 13
    protected function getController()
378
    {
379 13
        return self::$controller;
380
    }
381
382
    protected function getAction()
383
    {
384
        return self::$action;
385
    }
386
}
387