GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — user-entity ( 60964d...6b9ec2 )
by Luis Ramón
02:42
created

AdminController::genericIndexAction()   C

Complexity

Conditions 9
Paths 48

Size

Total Lines 52
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 0 Features 0
Metric Value
c 5
b 0
f 0
dl 0
loc 52
rs 6.5703
cc 9
eloc 31
nc 48
nop 4

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
  ÁTICA - Aplicación web para la gestión documental de centros educativos
4
5
  Copyright (C) 2015-2016: Luis Ramón López López
6
7
  This program is free software: you can redistribute it and/or modify
8
  it under the terms of the GNU Affero General Public License as published by
9
  the Free Software Foundation, either version 3 of the License, or
10
  (at your option) any later version.
11
12
  This program is distributed in the hope that it will be useful,
13
  but WITHOUT ANY WARRANTY; without even the implied warranty of
14
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
  GNU Affero General Public License for more details.
16
17
  You should have received a copy of the GNU Affero General Public License
18
  along with this program.  If not, see [http://www.gnu.org/licenses/].
19
*/
20
21
namespace AppBundle\Controller;
22
23
use AppBundle\Entity\Agreement;
24
use AppBundle\Entity\Company;
25
use AppBundle\Entity\Department;
26
use AppBundle\Entity\Group;
27
use AppBundle\Entity\NonSchoolDay;
28
use AppBundle\Entity\Training;
29
use AppBundle\Entity\User;
30
use AppBundle\Entity\Workcenter;
31
use Doctrine\ORM\EntityManager;
32
use Doctrine\ORM\Query;
33
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
34
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
35
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
36
use Symfony\Component\HttpFoundation\Request;
37
38
/**
39
 * @Route("/admin")
40
 */
41
class AdminController extends Controller
42
{
43
    public static $DEPARTMENT_ENTITY_DATA = [
44
            'entity' => 'department',
45
            'entityClassName' => 'AppBundle\Entity\Department',
46
            'entityFormType' => 'AppBundle\Form\Type\DepartmentType',
47
            'query' => 'SELECT d FROM AppBundle:Department d LEFT JOIN d.head h',
48
            'defaultSortFieldName' => 'd.name',
49
            'columns' => [
50
                ['size' => '5', 'sort_field' => 'd.name', 'name' => 'department.name'],
51
                ['size' => '4', 'sort_field' => 'h.displayName', 'name' => 'department.head'],
52
            ],
53
            'data_columns' => ['name', 'head']
54
        ];
55
56
    public static $COMPANY_ENTITY_DATA = [
57
        'entity' => 'company',
58
        'entityClassName' => 'AppBundle\Entity\Company',
59
        'entityFormType' => 'AppBundle\Form\Type\CompanyType',
60
        'query' => 'SELECT c FROM AppBundle:Company c',
61
        'defaultSortFieldName' => 'c.name',
62
        'columns' => [
63
            ['size' => '2', 'sort_field' => 'c.code', 'name' => 'company.code'],
64
            ['size' => '7', 'sort_field' => 'c.name', 'name' => 'company.name'],
65
        ],
66
        'data_columns' => ['code', 'name']
67
    ];
68
69
    public static $WORKCENTER_ENTITY_DATA = [
70
        'entity' => 'workcenter',
71
        'entityClassName' => 'AppBundle\Entity\Workcenter',
72
        'entityFormType' => 'AppBundle\Form\Type\WorkcenterType',
73
        'query' => 'SELECT w FROM AppBundle:Workcenter w JOIN w.company c',
74
        'defaultSortFieldName' => 'c.name',
75
        'columns' => [
76
            ['size' => '4', 'sort_field' => 'c.name', 'name' => 'form.company'],
77
            ['size' => '5', 'sort_field' => 'w.name', 'name' => 'form.name'],
78
        ],
79
        'data_columns' => ['company', 'name']
80
    ];
81
82
    public static $GROUP_ENTITY_DATA = [
83
        'entity' => 'group',
84
        'entityClassName' => 'AppBundle\Entity\Group',
85
        'entityFormType' => 'AppBundle\Form\Type\GroupType',
86
        'query' => 'SELECT g FROM AppBundle:Group g JOIN g.training t',
87
        'defaultSortFieldName' => 'g.name',
88
        'columns' => [
89
            ['size' => '4', 'sort_field' => 'g.name', 'name' => 'form.name'],
90
            ['size' => '5', 'sort_field' => 'g.training', 'name' => 'form.training']
91
        ],
92
        'data_columns' => ['name', 'training']
93
    ];
94
95
    public static $TRAINING_ENTITY_DATA = [
96
        'entity' => 'training',
97
        'entityClassName' => 'AppBundle\Entity\Training',
98
        'entityFormType' => 'AppBundle\Form\Type\TrainingType',
99
        'query' => 'SELECT t FROM AppBundle:Training t JOIN t.department d',
100
        'defaultSortFieldName' => 't.name',
101
        'columns' => [
102
            ['size' => '4', 'sort_field' => 't.name', 'name' => 'form.name'],
103
            ['size' => '3', 'sort_field' => 'd.name', 'name' => 'form.department'],
104
            ['size' => '2', 'sort_field' => 't.programHours', 'name' => 'form.program_hours']
105
        ],
106
        'data_columns' => ['name', 'department', 'programHours']
107
    ];
108
109
    public static $NON_SCHOOL_DAY_ENTITY_DATA = [
110
        'entity' => 'non_school_day',
111
        'entityClassName' => 'AppBundle\Entity\NonSchoolDay',
112
        'entityFormType' => 'AppBundle\Form\Type\NonSchoolDayType',
113
        'query' => 'SELECT n FROM AppBundle:NonSchoolDay n',
114
        'defaultSortFieldName' => 'n.date',
115
        'columns' => [
116
            ['size' => '2', 'sort_field' => 'n.date', 'name' => 'form.date'],
117
            ['size' => '7', 'sort_field' => 'n.name', 'name' => 'form.name']
118
        ],
119
        'data_columns' => ['date', 'name']
120
    ];
121
122
    public static $AGREEMENT_ENTITY_DATA = [
123
        'entity' => 'agreement',
124
        'entityClassName' => 'AppBundle\Entity\Agreement',
125
        'entityFormType' => 'AppBundle\Form\Type\AgreementType',
126
        'form_template' => 'agreement/form_agreement.html.twig',
127
        'query' => null,
128
        'defaultSortFieldName' => 's.lastName',
129
        'columns' => [
130
            ['size' => '4', 'sort_field' => 's.displayName', 'name' => 'form.student'],
131
            ['size' => '5', 'sort_field' => 'a.workcenter', 'name' => 'form.workcenter']
132
        ],
133
        'data_columns' => ['student', 'workcenter']
134
    ];
135
136
    /**
137
     * @Route("/", name="admin_menu", methods={"GET"})
138
     * @Security("is_granted('ROLE_ADMIN')")
139
     */
140
    public function indexAction()
141
    {
142
        $menuItem = $this->get('app.menu_builders_chain')->getMenuItemByRouteName('admin_menu');
143
        
144
        return $this->render('admin/menu.html.twig',
145
            [
146
                'menu_item' => $menuItem
147
            ]);
148
    }
149
150
    public function genericIndexAction($entityData, Request $request, $items = null, Query $query = null)
151
    {
152
        /** @var EntityManager $em */
153
        $em = $this->getDoctrine()->getManager();
154
155
        if (null === $query) {
156
            $query = $em->createQuery($entityData['query']);
157
158
            if (null !== $items) {
159
                $query->setParameters($items);
160
            }
161
        }
162
163
        $paginator  = $this->get('knp_paginator');
164
        $pagination = $paginator->paginate(
165
            $query,
166
            $request->query->getInt('page', 1),
167
            $this->getParameter('page.size'),
168
            [
169
                'defaultSortFieldName' => $entityData['defaultSortFieldName'],
170
                'defaultSortDirection' => 'asc'
171
            ]
172
        );
173
174
        $menuItem = $this->get('app.menu_builders_chain')->getMenuItemByRouteName(isset($entityData['parent'])
175
            ? $entityData['parent']
176
            : $request->get('_route'));
177
178
        $options = [
179
            'menu_item' => $menuItem,
180
            'title' => isset($entityData['title'])? $entityData['title'] : null,
181
            'pagination' => $pagination,
182
            'entity' => $entityData['entity'],
183
            'columns' => $entityData['columns'],
184
            'data_columns' => $entityData['data_columns']
185
        ];
186
187
        if (isset($entityData['breadcrumb'])) {
188
            $options['breadcrumb'] = $entityData['breadcrumb'];
189
        }
190
191
        if (isset($entityData['back_path'])) {
192
            $options['back_path'] = $entityData['back_path'];
193
        }
194
195
        if (isset($entityData['path_options'])) {
196
            $options['path_options'] = $entityData['path_options'];
197
        }
198
199
        return $this->render(isset($entityData['manage_template']) ? $entityData['manage_template']
200
            : 'admin/manage_generic.html.twig', $options);
201
    }
202
203
    public function genericFormAction($entityData, $element, Request $request)
204
    {
205
        $em = $this->getDoctrine()->getManager();
206
207
        $new = (null === $element);
208
        if ($new) {
209
            $element = new $entityData['entityClassName'];
210
            $em->persist($element);
211
        }
212
213
        $form = $this->createForm($entityData['entityFormType'], $element);
214
215
        $form->handleRequest($request);
216
217
        $menuItem = $this->get('app.menu_builders_chain')->getMenuItemByRouteName('admin_' . $entityData['entity']);
218
219 View Code Duplication
        if ($form->isSubmitted() && $form->isValid()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
220
221
            // Probar a guardar los cambios
222
            try {
223
                $em->flush();
224
                $this->addFlash('success', $this->get('translator')->trans('alert.saved', [], 'user'));
225
                return $this->redirectToRoute($menuItem->getRouteName(), $menuItem->getRouteParams());
226
            } catch (\Exception $e) {
227
                $this->addFlash('error', $this->get('translator')->trans('alert.not_saved', [], 'user'));
228
            }
229
        }
230
231
        $title = ((string) $element) ?: $this->get('translator')->trans('form.new', [], $entityData['entity']);
232
233
        return $this->render(isset($entityData['form_template']) ? $entityData['form_template'] : 'admin/form_generic.html.twig', [
234
            'form' => $form->createView(),
235
            'new' => $new,
236
            'menu_item' => $menuItem,
237
            'breadcrumb' => [
238
                ['fixed' => $title]
239
            ],
240
            'element' => $element,
241
            'title' => $title,
242
            'entity' => $entityData['entity']
243
        ]);
244
    }
245
246
    public function genericDeleteAction($entityData, $element, Request $request)
247
    {
248
        if ('POST' === $request->getMethod() && $request->request->has('delete')) {
249
250
            // Eliminar el departamento de la base de datos
251
            $this->getDoctrine()->getManager()->remove($element);
252
            try {
253
                $this->getDoctrine()->getManager()->flush();
254
                $this->addFlash('success', $this->get('translator')->trans('alert.deleted', [], $entityData['entity']));
255
            } catch (\Exception $e) {
256
                $this->addFlash('error', $this->get('translator')->trans('alert.not_deleted', [], $entityData['entity']));
257
            }
258
            return $this->redirectToRoute('admin_' . $entityData['entity']);
259
        }
260
261
        $title = (string) $element;
262
263
        $breadcrumb = [
264
            ['fixed' => $title, 'path' => 'admin_' . $entityData['entity'] . '_form', 'options' => ['id' => $element->getId()]],
265
            ['caption' => 'menu.delete']
266
        ];
267
268
        return $this->render(':admin:delete_generic.html.twig', [
269
            'menu_item' => $this->get('app.menu_builders_chain')->getMenuItemByRouteName('admin_departments'),
270
            'breadcrumb' => $breadcrumb,
271
            'title' => $title,
272
            'element' => $element,
273
            'entity' => $entityData['entity']
274
        ]);
275
    }
276
277
    /**
278
     * @Route("/departamentos", name="admin_department", methods={"GET"})
279
     */
280
    public function departmentsIndexAction(Request $request)
281
    {
282
        return $this->genericIndexAction(self::$DEPARTMENT_ENTITY_DATA, $request);
283
    }
284
285
    /**
286
     * @Route("/departamentos/nuevo", name="admin_department_new", methods={"GET", "POST"})
287
     * @Route("/departamentos/{id}", name="admin_department_form", methods={"GET", "POST"}, requirements={"id": "\d+"})
288
     */
289
    public function departmentsFormAction(Department $element = null, Request $request)
290
    {
291
        return $this->genericFormAction(self::$DEPARTMENT_ENTITY_DATA, $element, $request);
292
    }
293
294
    /**
295
     * @Route("/departamentos/eliminar/{id}", name="admin_department_delete", methods={"GET", "POST"}, requirements={"id": "\d+"} )
296
     */
297
    public function deleteElementAction(Department $element, Request $request)
298
    {
299
        return $this->genericDeleteAction(self::$DEPARTMENT_ENTITY_DATA, $element, $request);
300
    }
301
302
    /**
303
     * @Route("/empresas", name="admin_company", methods={"GET"})
304
     */
305
    public function companiesIndexAction(Request $request)
306
    {
307
        return $this->genericIndexAction(self::$COMPANY_ENTITY_DATA, $request);
308
    }
309
310
    /**
311
     * @Route("/empresas/nueva", name="admin_company_new", methods={"GET", "POST"})
312
     * @Route("/empresas/{id}", name="admin_company_form", methods={"GET", "POST"}, requirements={"id": "\d+"})
313
     */
314
    public function companyFormAction(Company $element = null, Request $request)
315
    {
316
        return $this->genericFormAction(self::$COMPANY_ENTITY_DATA, $element, $request);
317
    }
318
319
    /**
320
     * @Route("/empresas/eliminar/{id}", name="admin_company_delete", methods={"GET", "POST"}, requirements={"id": "\d+"} )
321
     */
322
    public function companyDeleteAction(Company $element, Request $request)
323
    {
324
        return $this->genericDeleteAction(self::$COMPANY_ENTITY_DATA, $element, $request);
325
    }
326
327
    /**
328
     * @Route("/grupos", name="admin_group", methods={"GET"})
329
     */
330
    public function groupIndexAction(Request $request)
331
    {
332
        return $this->genericIndexAction(self::$GROUP_ENTITY_DATA, $request);
333
    }
334
335
    /**
336
     * @Route("/grupos/nuevo", name="admin_group_new", methods={"GET", "POST"})
337
     * @Route("/grupos/{id}", name="admin_group_form", methods={"GET", "POST"}, requirements={"id": "\d+"})
338
     */
339
    public function groupFormAction(Group $element = null, Request $request)
340
    {
341
        return $this->genericFormAction(self::$GROUP_ENTITY_DATA, $element, $request);
342
    }
343
344
    /**
345
     * @Route("/grupos/eliminar/{id}", name="admin_group_delete", methods={"GET", "POST"}, requirements={"id": "\d+"} )
346
     */
347
    public function groupDeleteAction(Group $element, Request $request)
348
    {
349
        return $this->genericDeleteAction(self::$GROUP_ENTITY_DATA, $element, $request);
350
    }
351
352
    /**
353
     * @Route("/ensenanzas", name="admin_training", methods={"GET"})
354
     */
355
    public function trainingIndexAction(Request $request)
356
    {
357
        return $this->genericIndexAction(self::$TRAINING_ENTITY_DATA, $request);
358
    }
359
360
    /**
361
     * @Route("/ensenanzas/nueva", name="admin_training_new", methods={"GET", "POST"})
362
     * @Route("/ensenanzas/{id}", name="admin_training_form", methods={"GET", "POST"}, requirements={"id": "\d+"})
363
     */
364
    public function trainingFormAction(Training $element = null, Request $request)
365
    {
366
        return $this->genericFormAction(self::$TRAINING_ENTITY_DATA, $element, $request);
367
    }
368
369
    /**
370
     * @Route("/ensenanzas/eliminar/{id}", name="admin_training_delete", methods={"GET", "POST"}, requirements={"id": "\d+"} )
371
     */
372
    public function trainingDeleteAction(Training $element, Request $request)
373
    {
374
        return $this->genericDeleteAction(self::$TRAINING_ENTITY_DATA, $element, $request);
375
    }
376
377
    /**
378
     * @Route("/diasnolectivos", name="admin_non_school_day", methods={"GET"})
379
     */
380
    public function nonSchoolDayIndexAction(Request $request)
381
    {
382
        return $this->genericIndexAction(self::$NON_SCHOOL_DAY_ENTITY_DATA, $request);
383
    }
384
385
    /**
386
     * @Route("/diasnolectivos/nuevo", name="admin_non_school_day_new", methods={"GET", "POST"})
387
     * @Route("/diasnolectivos/{id}", name="admin_non_school_day_form", methods={"GET", "POST"})
388
     */
389
    public function nonSchoolDayFormAction(NonSchoolDay $element = null, Request $request)
390
    {
391
        return $this->genericFormAction(self::$NON_SCHOOL_DAY_ENTITY_DATA, $element, $request);
392
    }
393
394
    /**
395
     * @Route("/diasnolectivos/eliminar/{id}", name="admin_non_school_day_delete", methods={"GET", "POST"})
396
     */
397
    public function workcenterDeleteAction(Workcenter $element, Request $request)
398
    {
399
        return $this->genericDeleteAction(self::$WORKCENTER_ENTITY_DATA, $element, $request);
400
    }
401
402
    /**
403
     * @Route("/centros", name="admin_workcenter", methods={"GET"})
404
     */
405
    public function workcenterIndexAction(Request $request)
406
    {
407
        return $this->genericIndexAction(self::$WORKCENTER_ENTITY_DATA, $request);
408
    }
409
410
    /**
411
     * @Route("/centros/nuevo", name="admin_workcenter_new", methods={"GET", "POST"})
412
     * @Route("/centros/{id}", name="admin_workcenter_form", methods={"GET", "POST"})
413
     */
414
    public function workcenterFormAction(Workcenter $element = null, Request $request)
415
    {
416
        return $this->genericFormAction(self::$WORKCENTER_ENTITY_DATA, $element, $request);
417
    }
418
419
    /**
420
     * @Route("/centros/eliminar/{id}", name="admin_workcenter_delete", methods={"GET", "POST"})
421
     */
422
    public function nonSchoolDayDeleteAction(Workcenter $element, Request $request)
423
    {
424
        return $this->genericDeleteAction(self::$WORKCENTER_ENTITY_DATA, $element, $request);
425
    }
426
427
    /**
428
     * @Route("/acuerdos", name="admin_agreement", methods={"GET"})
429
     */
430
    public function agreementIndexAction(Request $request)
431
    {
432
        /** @var EntityManager $em */
433
        $em = $this->getDoctrine()->getManager();
434
435
        // Obtener:
436
        // - todos los acuerdos si es administrador
437
        // - los de los alumnos de mi(s) tutoría(s) si soy tutor de un grupo
438
        // - los de el departamento si soy jefe de departamentp
439
440
            /** @var User $user */
441
        $user = $this->getUser();
442
443
        $qb = $em->getRepository('AppBundle:Agreement')
444
            ->createQueryBuilder('a')
445
            ->innerJoin('a.student', 's')
446
            ->innerJoin('s.studentGroup', 'g');
447
448 View Code Duplication
        if (!$user->isGlobalAdministrator()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
449
            $qb = $qb
450
                ->innerJoin('g.training', 't')
451
                ->innerJoin('t.department', 'd')
452
                ->where('g.id IN (:groups)')
453
                ->orWhere('d.head = :user')
454
                ->setParameter('groups', $user->getTutorizedGroups()->toArray())
455
                ->setParameter('user', $user);
456
        }
457
        return $this->genericIndexAction(self::$AGREEMENT_ENTITY_DATA, $request, null, $qb->getQuery());
458
    }
459
460
    /**
461
     * @Route("/acuerdos/nuevo", name="admin_agreement_new", methods={"GET", "POST"})
462
     * @Route("/acuerdos/{id}", name="admin_agreement_form", methods={"GET", "POST"})
463
     */
464
    public function agreementFormAction(Agreement $element = null, Request $request)
465
    {
466
        return $this->genericFormAction(self::$AGREEMENT_ENTITY_DATA, $element, $request);
467
    }
468
469
    /**
470
     * @Route("/acuerdos/eliminar/{id}", name="admin_agreement_delete", methods={"GET", "POST"})
471
     */
472
    public function agreementDeleteAction(Agreement $element, Request $request)
473
    {
474
        return $this->genericDeleteAction(self::$AGREEMENT_ENTITY_DATA, $element, $request);
475
    }
476
}
477