Completed
Push — master ( 18da6a...2d41be )
by Luis Ramón
14:40
created

AlumnoController   A

Complexity

Total Complexity 21

Size/Duplication

Total Lines 173
Duplicated Lines 14.45 %

Coupling/Cohesion

Components 1
Dependencies 13

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 21
lcom 1
cbo 13
dl 25
loc 173
ccs 0
cts 107
cp 0
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
B listarAction() 0 23 4
B detalleAction() 0 44 4
C importarAlumnadoDesdeCsv() 0 61 9
B importarAction() 25 25 4

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/*
3
  GESTCONV - Aplicación web para la gestión de la convivencia en centros educativos
4
5
  Copyright (C) 2015: 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\Alumno;
24
use AppBundle\Entity\Curso;
25
use AppBundle\Entity\Grupo;
26
use AppBundle\Form\Model\Importar;
27
use AppBundle\Form\Type\AlumnoType;
28
use AppBundle\Form\Type\ImportarType;
29
use AppBundle\Form\Type\RangoFechasType;
30
use AppBundle\Utils\CsvImporter;
31
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
32
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
33
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
34
use Symfony\Component\HttpFoundation\RedirectResponse;
35
use Symfony\Component\HttpFoundation\Request;
36
37
/**
38
 * @Route("/alumno")
39
 */
40
41
class AlumnoController extends Controller
42
{
43
    /**
44
     * @Route("/tutoria", name="alumno_tutoria",methods={"GET"})
45
     * @Route("/todo", name="alumno_listar_todo",methods={"GET"})
46
     * @Security("has_role('ROLE_DIRECTIVO') or has_role('ROLE_ORIENTADOR') or (has_role('ROLE_TUTOR') and request.get('_route') == 'alumno_tutoria')")
47
     */
48
    public function listarAction(Request $request)
49
    {
50
        $usuario = $this->getUser();
51
        $em = $this->getDoctrine()->getManager();
52
53
        $fechasPorDefecto = array('desde' => null, 'hasta' => null);
54
55
        $form = $this->createForm(new RangoFechasType(), $fechasPorDefecto);
56
        $form->handleRequest($request);
57
58
        $tutor = ($request->get('_route') === 'alumno_tutoria') ? $usuario : null;
59
60
        $alumnado = $em->getRepository('AppBundle:Alumno')->getResumenConvivencia($tutor, $form->isValid() ? $form->getData() : $fechasPorDefecto);
61
62
        return $this->render(($request->get('_route') === 'alumno_tutoria')
63
                ? 'AppBundle:Alumno:tutoria.html.twig'
64
                : 'AppBundle:Alumno:listar.html.twig',
65
            array(
66
                'formulario_fechas' => $form->createView(),
67
                'items' => $alumnado,
68
                'usuario' => $usuario
69
            ));
70
    }
71
72
    /**
73
     * @Route("/detalle/tutoria/{alumno}", name="alumno_tutoria_detalle", methods={"GET", "POST"})
74
     * @Route("/detalle/{alumno}", name="alumno_detalle", methods={"GET", "POST"})
75
     * @Security("has_role('ROLE_DIRECTIVO') or has_role('ROLE_ORIENTADOR') or (has_role('ROLE_TUTOR') and request.get('_route') == 'alumno_tutoria_detalle')")
76
     */
77
    public function detalleAction(Alumno $alumno, Request $request)
78
    {
79
        $usuario = $this->getUser();
80
        $em = $this->getDoctrine()->getManager();
81
82
        $formularioAlumno = $this->createForm(new AlumnoType(), $alumno, array(
83
            'admin' => $this->isGranted('ROLE_DIRECTIVO'),
84
            'bloqueado' => ($alumno->getGrupo() != $usuario->getTutoria())
85
        ));
86
87
        $formularioAlumno->handleRequest($request);
88
89
        $vuelta = ($request->get('_route') === 'alumno_tutoria_detalle')
90
            ? array(
91
                'ruta' => 'alumno_tutoria',
92
                'descripcion' => 'Gestionar tutoría',
93
                'boton' => 'Volver al listado del grupo'
94
            )
95
            : array(
96
                'ruta' => 'alumno_listar_todo',
97
                'descripcion' => 'Gestionar alumnado',
98
                'boton' => 'Volver al listado de alumnado'
99
            );
100
101
        if ($formularioAlumno->isSubmitted() && $formularioAlumno->isValid()) {
102
            $em->persist($alumno);
103
            $em->flush();
104
            $this->addFlash('success', 'Los cambios han sido registrados correctamente');
105
            return new RedirectResponse(
106
                $this->generateUrl($vuelta['ruta'])
107
            );
108
        }
109
110
        $sanciones = $em->getRepository('AppBundle:Sancion')->findAllPorAlumno($alumno);
111
112
        return $this->render('AppBundle:Alumno:detalle.html.twig',
113
            array(
114
                'vuelta' => $vuelta,
115
                'alumno' => $alumno,
116
                'sanciones' => $sanciones,
117
                'formulario_alumno' => $formularioAlumno->createView(),
118
                'usuario' => $usuario
119
            ));
120
    }
121
122
    protected function importarAlumnadoDesdeCsv($fichero)
123
    {
124
        $em = $this->getDoctrine()->getManager();
125
126
        $importer = new CsvImporter($fichero, true);
127
        $curso = $em->getRepository('AppBundle:Curso')->createQueryBuilder('c')
128
            ->select('c')->setMaxResults(1)->getQuery()
129
            ->getOneOrNullResult();
130
131
        if (!$curso) {
132
            $curso = new Curso();
133
            $curso->setDescripcion('Importado');
134
            $em->persist($curso);
135
        }
136
137
        $grupos = array();
138
139
        while($data = $importer->get(100)) {
140
            foreach($data as $alumnoData) {
141
142
                if ($alumnoData['Unidad']) {
143
                    $alumno = $em->getRepository('AppBundle:Alumno')
144
                        ->findOneByNie($alumnoData['Nº Id. Escolar']);
145
                    if (!$alumno) {
146
                        $alumno = new Alumno();
147
                    }
148
149
                    if (!isset($grupos[$alumnoData['Unidad']])) {
150
                        $grupo = $em->getRepository('AppBundle:Grupo')
151
                            ->findOneByDescripcion($alumnoData['Unidad']);
152
153
                        if (!$grupo) {
154
                            $grupo = new Grupo;
155
                            $grupo->setDescripcion($alumnoData['Unidad'])->setCurso($curso);
156
                            $em->persist($grupo);
157
                        }
158
159
                        $grupos[$alumnoData['Unidad']] = $grupo;
160
                    }
161
                    else {
162
                        $grupo = $grupos[$alumnoData['Unidad']];
163
                    }
164
165
                    $alumno->setNie($alumnoData['Nº Id. Escolar'])
166
                        ->setApellido1($alumnoData['Primer apellido'])
167
                        ->setApellido2($alumnoData['Segundo apellido'])
168
                        ->setNombre($alumnoData['Nombre'])
169
                        ->setFechaNacimiento($alumnoData['Fecha de nacimiento'] != '' ? \DateTime::createFromFormat('d/m/Y', $alumnoData['Fecha de nacimiento']) : null)
170
                        ->setTutor1($alumnoData['Nombre Primer tutor'] . ' ' . $alumnoData['Primer apellido Primer tutor'] . ' ' . $alumnoData['Segundo apellido Primer tutor'])
171
                        ->setTutor2($alumnoData['Nombre Segundo tutor'] . ' ' . $alumnoData['Primer apellido Segundo tutor'] . ' ' . $alumnoData['Segundo apellido Segundo tutor'])
172
                        ->setTelefono1($alumnoData['Teléfono'])
173
                        ->setTelefono2($alumnoData['Teléfono de urgencia'])
174
                        ->setGrupo($grupo);
175
176
                    $em->persist($alumno);
177
                }
178
            }
179
        }
180
        $em->flush();
181
        return true;
182
    }
183
184
    /**
185
     * @Route("/importar", name="alumno_importar",methods={"GET", "POST"})
186
     * @Security("has_role('ROLE_DIRECTIVO')")
187
     */
188 View Code Duplication
    public function importarAction(Request $request)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
189
    {
190
        $datos = new Importar();
191
        $form = $this->createForm(new ImportarType(), $datos);
192
        $form->handleRequest($request);
193
194
        if ($form->isSubmitted() && $form->isValid()) {
195
196
            if ($this->importarAlumnadoDesdeCsv($datos->getFichero()->getPathname())) {
197
                $this->addFlash('success', 'Los datos se han importado correctamente');
198
            }
199
            else {
200
                $this->addFlash('error', 'Ha ocurrido un error en la importación');
201
            }
202
203
            return new RedirectResponse(
204
                $this->generateUrl('alumno_listar_todo')
205
            );
206
        }
207
208
        return $this->render('AppBundle:Alumno:importar.html.twig',
209
            array(
210
                'formulario' => $form->createView()
211
            ));
212
    }
213
}
214