ParteController   C
last analyzed

Complexity

Total Complexity 37

Size/Duplication

Total Lines 289
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 20

Test Coverage

Coverage 0%

Importance

Changes 5
Bugs 0 Features 0
Metric Value
wmc 37
c 5
b 0
f 0
lcom 1
cbo 20
dl 0
loc 289
ccs 0
cts 166
cp 0
rs 5.5647

7 Methods

Rating   Name   Duplication   Size   Complexity  
A pendienteAction() 0 11 1
A listarAction() 0 20 2
B detallePdfAction() 0 29 4
B eliminarAction() 0 43 6
C listadoNotificarAction() 0 53 11
B nuevoAction() 0 49 5
C detalleAction() 0 52 8
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\AvisoParte;
24
use AppBundle\Entity\ObservacionParte;
25
use AppBundle\Entity\Parte;
26
use AppBundle\Entity\Usuario;
27
use AppBundle\Form\Type\NuevaObservacionType;
28
use AppBundle\Form\Type\NuevoParteType;
29
use AppBundle\Form\Type\ParteType;
30
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
31
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
32
use Symfony\Component\HttpFoundation\RedirectResponse;
33
use Symfony\Component\HttpFoundation\Request;
34
use Symfony\Component\HttpFoundation\Response;
35
36
/**
37
 * @Route("/parte")
38
 */
39
40
class ParteController extends BaseController
41
{
42
    /**
43
     * @Route("/nuevo", name="parte_nuevo",methods={"GET", "POST"})
44
     */
45
    public function nuevoAction(Request $peticion)
46
    {
47
        $parte = new Parte();
48
49
        /**
50
         * @var Usuario
51
         */
52
        $usuario = $this->getUser();
53
54
        $parte->setFechaCreacion(new \DateTime())
55
            ->setFechaSuceso(new \DateTime())
56
            ->setUsuario($usuario)
0 ignored issues
show
Bug introduced by
It seems like $usuario defined by $this->getUser() on line 52 can also be of type object; however, AppBundle\Entity\Parte::setUsuario() does only seem to accept null|object<AppBundle\Entity\Usuario>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
57
            ->setPrescrito(false);
58
59
        $formulario = $this->createForm(new NuevoParteType(), $parte, array(
60
            'admin' => $this->isGranted('ROLE_REVISOR')
61
        ));
62
63
        $formulario->handleRequest($peticion);
64
65
        if ($formulario->isSubmitted() && $formulario->isValid()) {
66
67
            // crear un parte por alumno y guardarlo en la base de datos
68
            $em = $this->getDoctrine()->getManager();
69
            $alumnos = $formulario->get('alumnos')->getData();
70
            foreach ($alumnos as $alumno) {
71
                $nuevoParte = clone $parte;
72
                $nuevoParte->setAlumno($alumno);
73
                $em->persist($nuevoParte);
74
            }
75
76
            $em->flush();
77
78
            $this->addFlash('success', (count($alumnos) == 1)
79
                ? 'Se ha creado un parte con éxito'
80
                : 'Se han creado ' . count($alumnos) . ' partes con éxito');
81
82
            // redireccionar a la portada
83
            return new RedirectResponse(
84
                $this->generateUrl('portada')
85
            );
86
        }
87
88
        return $this->render('AppBundle:Parte:nuevo.html.twig',
89
            array(
90
                'parte' => $parte,
91
                'formulario' => $formulario->createView()
92
            ));
93
    }
94
95
    /**
96
     * @Route("/notificar", name="parte_listado_notificar",methods={"GET", "POST"})
97
     */
98
    public function listadoNotificarAction(Request $request)
99
    {
100
        $usuario = $this->getUser();
101
        $em = $this->getDoctrine()->getManager();
102
103
        if (($request->getMethod() === 'POST') && (($request->request->get('noNotificada')) || ($request->request->get('notificada')))) {
104
105
            $id = $request->request->get(($request->request->get('notificada')) ? 'notificada' : 'noNotificada');
106
107
            $partes = ($this->isGranted('ROLE_REVISOR'))
108
            ? $em->getRepository('AppBundle:Parte')->findAllNoNotificadosPorAlumno($id)
109
            : $em->getRepository('AppBundle:Parte')->findAllNoNotificadosPorAlumnoYUsuario($id, $usuario);
110
111
            foreach ($partes as $parte) {
112
                $avisoParte = new AvisoParte();
113
                $avisoParte
114
                    ->setParte($parte)
115
                    ->setUsuario($usuario)
0 ignored issues
show
Bug introduced by
It seems like $usuario defined by $this->getUser() on line 100 can also be of type object; however, AppBundle\Entity\Aviso::setUsuario() does only seem to accept null|object<AppBundle\Entity\Usuario>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
116
                    ->setAnotacion($request->request->get('anotacion'))
117
                    ->setFecha(new \DateTime())
118
                    ->setTipo($em->getRepository('AppBundle:CategoriaAviso')->find($request->request->get('tipo')));
119
120
                if ($request->request->get('notificada')) {
121
                    $parte->setFechaAviso(new \DateTime());
122
                }
123
124
                $em->persist($avisoParte);
125
126
                $this->notificarParte($parte->getAlumno()->getGrupo()->getTutores(), $parte);
127
                if ($parte->getPrioritario()) {
128
                    $this->notificarParte($em->getRepository('AppBundle:Usuario')->getRevisores(), $parte);
129
                }
130
            }
131
            $em->flush();
132
        }
133
134
        $alumnos = ($this->isGranted('ROLE_REVISOR'))
135
            ? $em->getRepository('AppBundle:Alumno')->findAllConPartesAunNoNotificados()
136
            : $em->getRepository('AppBundle:Alumno')->findAllConPartesAunNoNotificadosPorUsuario($usuario);
137
138
        if (count($alumnos) == 0) {
139
            // redireccionar a la portada
140
            return new RedirectResponse(
141
                $this->generateUrl('portada')
142
            );
143
        }
144
        return $this->render('AppBundle:Parte:notificar.html.twig',
145
            array(
146
                'usuario' => $usuario,
147
                'alumnos' => $alumnos,
148
                'tipos' => $em->getRepository('AppBundle:CategoriaAviso')->findAll()
149
            ));
150
    }
151
152
    /**
153
     * @Route("/pendiente", name="parte_pendiente",methods={"GET"})
154
     * @Security("has_role('ROLE_REVISOR')")
155
     */
156
    public function pendienteAction()
157
    {
158
        $usuario = $this->getUser();
159
        $em = $this->getDoctrine()->getManager();
160
161
        return $this->render('AppBundle:Parte:pendiente.html.twig',
162
            array(
163
                'alumnos' => $em->getRepository('AppBundle:Alumno')->findAllConPartesPendientesSancion(),
164
                'usuario' => $usuario
165
            ));
166
    }
167
168
    /**
169
     * @Route("/listar", name="parte_listar",methods={"GET"})
170
     */
171
    public function listarAction()
172
    {
173
        $usuario = $this->getUser();
174
        $em = $this->getDoctrine()->getManager();
175
176
        if (!$this->isGranted('ROLE_REVISOR')) {
177
            $partes = $em->getRepository('AppBundle:Parte')
178
                ->findAllPorUsuarioOTutoria($usuario);
179
        }
180
        else {
181
            $partes = $em->getRepository('AppBundle:Parte')
182
                ->findAllOrdered();
183
        }
184
185
        return $this->render('AppBundle:Parte:listar.html.twig',
186
            array(
187
                'partes' => $partes,
188
                'usuario' => $usuario
189
            ));
190
    }
191
192
    /**
193
     * @Route("/detalle/{parte}", name="parte_detalle",methods={"GET", "POST"})
194
     */
195
    public function detalleAction(Parte $parte, Request $request)
196
    {
197
        $usuario = $this->getUser();
198
        
199
        $esRevisor = $this->isGranted('ROLE_REVISOR');
200
201
        if (!$esRevisor && !($parte->getAlumno()->getGrupo() == $usuario->getTutoria()) && $parte->getUsuario() != $usuario) {
202
            throw $this->createAccessDeniedException();
203
        }
204
205
        $formularioParte = $this->createForm(new ParteType(), $parte, array(
206
            'admin' => $esRevisor,
207
            'bloqueado' => (false === is_null($parte->getSancion()))
208
        ));
209
210
        $observacion = new ObservacionParte();
211
        $observacion->setParte($parte)
212
            ->setFecha(new \DateTime())
213
            ->setUsuario($usuario);
0 ignored issues
show
Bug introduced by
It seems like $usuario defined by $this->getUser() on line 197 can also be of type object; however, AppBundle\Entity\Observacion::setUsuario() does only seem to accept null|object<AppBundle\Entity\Usuario>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
214
215
        $formularioObservacion = $this->createForm(new NuevaObservacionType(), $observacion, array(
216
            'admin' => $esRevisor
217
        ));
218
219
        $formularioObservacion->handleRequest($request);
220
221
        if ($formularioObservacion->isSubmitted() && $formularioObservacion->isValid()) {
222
            $this->getDoctrine()->getManager()->persist($observacion);
223
            $this->getDoctrine()->getManager()->flush();
224
            $this->addFlash('success', 'Observación registrada correctamente');
225
        }
226
227
        $formularioParte->handleRequest($request);
228
229
        if ($formularioParte->isSubmitted() && $formularioParte->isValid()) {
230
231
            $this->getDoctrine()->getManager()->flush();
232
            $this->addFlash('success', 'Se han registrado correctamente los cambios en el parte');
233
234
            return new RedirectResponse(
235
                $this->generateUrl('parte_listar')
236
            );
237
        }
238
239
        return $this->render('AppBundle:Parte:detalle.html.twig',
240
            array(
241
                'parte' => $parte,
242
                'formulario_parte' => $formularioParte->createView(),
243
                'formulario_observacion' => $formularioObservacion->createView(),
244
                'usuario' => $usuario
245
            ));
246
    }
247
248
    /**
249
     * @Route("/imprimir/{parte}", name="parte_detalle_pdf",methods={"GET"})
250
     */
251
    public function detallePdfAction(Parte $parte)
252
    {
253
        $usuario = $this->getUser();
254
        $plantilla = $this->container->getParameter('parte');
255
        $logos = $this->container->getParameter('logos');
256
257
        $esRevisor = $this->isGranted('ROLE_REVISOR');
258
        $esTutor = ($parte->getAlumno()->getGrupo() != $usuario->getTutoria());
259
260
        if (!$esRevisor && !$esTutor && $parte->getUsuario() != $usuario) {
261
            throw $this->createAccessDeniedException();
262
        }
263
264
        $pdf = $this->generarPdf('Parte #' . $parte->getId(), $logos, $plantilla, 0, 'P' . $parte->getId());
265
266
        $html = $this->renderView('AppBundle:Parte:imprimir.html.twig',
267
            array(
268
                'parte' => $parte,
269
                'usuario' => $usuario,
270
                'localidad' => $this->container->getParameter('localidad')
271
            ));
272
273
        $pdf->writeHTML($html);
274
275
        $response = new Response($pdf->Output('parte_' . $parte->getId() . '.pdf'));
276
        $response->headers->set('Content-Type', 'application/pdf');
277
278
        return $response;
279
    }
280
281
    /**
282
     * @Route("/eliminar/{parte}", name="parte_eliminar",methods={"GET", "POST"})
283
     * @Security("has_role('ROLE_DIRECTIVO')")
284
     */
285
    public function eliminarAction(Parte $parte, Request $request)
286
    {
287
        if ($parte->getSancion()) {
288
            // los partes sancionados no se pueden eliminar
289
            return $this->createAccessDeniedException();
290
        }
291
292
        $formulario = $this->createFormBuilder()
293
            ->add('eliminar', 'submit',
294
                array(
295
                    'label' => 'Confirmar eliminación',
296
                    'attr' => array('class' => 'btn btn-danger')
297
                )
298
            )->getForm();
299
300
        $formulario->handleRequest($request);
301
302
        if ($formulario->isSubmitted() && $formulario->isValid()) {
303
            $this->notificar($parte->getAlumno()->getGrupo()->getTutores(), "Parte #" . $parte->getId() . " eliminado",
304
                "El parte #" . $parte->getId() . " de " . $parte->getAlumno() . " ha sido eliminado por " . $this->getUser());
305
306
            foreach($parte->getAvisos() as $aviso) {
307
                $this->getDoctrine()->getManager()->remove($aviso);
308
            }
309
            foreach($parte->getObservaciones() as $observacion) {
310
                $this->getDoctrine()->getManager()->remove($observacion);
311
            }
312
            $this->getDoctrine()->getManager()->remove($parte);
313
            $this->getDoctrine()->getManager()->flush();
314
315
            $this->addFlash('success', 'El parte ha sido eliminado correctamente de la base de datos');
316
317
            return new RedirectResponse(
318
                $this->generateUrl('parte_listar')
319
            );
320
        }
321
322
        return $this->render('AppBundle:Parte:eliminar.html.twig',
323
            array(
324
                'parte' => $parte,
325
                'formulario' => $formulario->createView()
326
            ));
327
    }
328
}
329