OrganizationController::indexAction()   C
last analyzed

Complexity

Conditions 8
Paths 22

Size

Total Lines 36
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 36
rs 5.3846
cc 8
eloc 23
nc 22
nop 2
1
<?php
2
/*
3
  ÁTICA - Aplicación web para la gestión documental de centros educativos
4
5
  Copyright (C) 2015-2017: 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\Admin;
22
23
use AppBundle\Entity\Organization;
24
use AppBundle\Form\Type\OrganizationType;
25
use AppBundle\Service\CoreData;
26
use AppBundle\Service\UserExtensionService;
27
use Doctrine\ORM\QueryBuilder;
28
use Pagerfanta\Adapter\DoctrineORMAdapter;
29
use Pagerfanta\Pagerfanta;
30
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
31
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
32
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
33
use Symfony\Component\HttpFoundation\Request;
34
35
/**
36
 * @Route("/admin/organizaciones")
37
 * @Security("is_granted('ROLE_ADMIN')")
38
 */
39
class OrganizationController extends Controller
40
{
41
    /**
42
     * @Route("/nueva", name="admin_organization_form_new", methods={"GET", "POST"})
43
     * @Route("/{id}", name="admin_organization_form_edit", requirements={"id" = "\d+"}, methods={"GET", "POST"})
44
     */
45
    public function indexAction(Organization $organization = null, Request $request)
46
    {
47
        $em = $this->getDoctrine()->getManager();
48
49
        if (null === $organization) {
50
            $organization = new Organization();
51
            $em->persist($organization);
52
        }
53
54
        $form = $this->createForm(OrganizationType::class, $organization, [
55
            'new' => $organization->getId() === null
56
        ]);
57
58
        $form->handleRequest($request);
59
60
        if ($form->isSubmitted() && $form->isValid()) {
61
            try {
62
                if (null === $organization->getElement()) {
63
                    $organization->setElement($this->get(CoreData::class)->createOrganizationElements($organization));
64
                }
65
                $em->flush();
66
                $this->addFlash('success', $this->get('translator')->trans('message.saved', [], 'organization'));
67
                return $this->redirectToRoute('admin_organization_list');
68
            } catch (\Exception $e) {
69
                $this->addFlash('error', $this->get('translator')->trans('message.save_error', [], 'organization'));
70
            }
71
        }
72
73
        return $this->render('admin/organization/form.html.twig', [
74
            'menu_path' => 'admin_organization_list',
75
            'breadcrumb' => [['fixed' => $organization->getId() ? (string) $organization : $this->get('translator')->trans('title.new', [], 'organization')]],
76
            'title' => $this->get('translator')->trans($organization->getId() ? 'title.edit' : 'title.new', [], 'organization'),
77
            'form' => $form->createView(),
78
            'user' => $organization
79
        ]);
80
    }
81
82
    /**
83
     * @Route("/listar/{page}", name="admin_organization_list", requirements={"page" = "\d+"}, defaults={"page" = "1"}, methods={"GET"})
84
     */
85 View Code Duplication
    public function listAction($page, 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...
86
    {
87
        /** @var QueryBuilder $queryBuilder */
88
        $queryBuilder = $this->getDoctrine()->getManager()->createQueryBuilder();
89
90
        $queryBuilder
91
            ->select('o')
92
            ->from('AppBundle:Organization', 'o')
93
            ->orderBy('o.name');
94
95
        $q = $request->get('q', null);
96
        if ($q) {
97
            $queryBuilder
98
                ->where('o.id = :q')
99
                ->orWhere('o.name LIKE :tq')
100
                ->orWhere('o.code LIKE :tq')
101
                ->orWhere('o.emailAddress LIKE :tq')
102
                ->orWhere('o.phoneNumber LIKE :tq')
103
                ->orWhere('o.city LIKE :tq')
104
                ->setParameter('tq', '%'.$q.'%')
105
                ->setParameter('q', $q);
106
        }
107
108
        $adapter = new DoctrineORMAdapter($queryBuilder, false);
109
        $pager = new Pagerfanta($adapter);
110
        $pager
111
            ->setMaxPerPage($this->getParameter('page.size'))
112
            ->setCurrentPage($q ? 1 : $page);
113
114
        $title = $this->get('translator')->trans('title.list', [], 'organization');
115
116
        return $this->render('admin/organization/list.html.twig', [
117
            'title' => $title,
118
            'pager' => $pager,
119
            'q' => $q,
120
            'domain' => 'organization'
121
        ]);
122
    }
123
124
    /**
125
     * @Route("/operacion", name="admin_organization_operation", methods={"POST"})
126
     */
127
    public function operationAction(Request $request)
128
    {
129
        list($redirect, $organizations) = $this->processOperations($request);
130
131
        if ($redirect) {
132
            return $this->redirectToRoute('admin_organization_list');
133
        }
134
135
        return $this->render('admin/organization/delete.html.twig', [
136
            'menu_path' => 'admin_organization_list',
137
            'breadcrumb' => [['fixed' => $this->get('translator')->trans('title.delete', [], 'organization')]],
138
            'title' => $this->get('translator')->trans('title.delete', [], 'organization'),
139
            'organizations' => $organizations
140
        ]);
141
    }
142
143
    /**
144
     * Borrar los datos de las organizaciones pasados como parámetros
145
     *
146
     * @param Organization[] $organizations
147
     */
148
    private function deleteOrganizations($organizations)
149
    {
150
        $em = $this->getDoctrine()->getManager();
151
152
        /* Borrar primero las pertenencias */
153
        $em->createQueryBuilder()
154
            ->delete('AppBundle:Membership', 'm')
155
            ->where('m.organization IN (:items)')
156
            ->setParameter('items', $organizations)
157
            ->getQuery()
158
            ->execute();
159
160
        /* Desconectar las organizaciones de los elementos */
161
        $em->createQueryBuilder()
162
            ->update('AppBundle:Organization', 'o')
163
            ->where('o IN (:items)')
164
            ->set('o.element', ':value')
165
            ->setParameter('items', $organizations)
166
            ->setParameter('value', null)
167
            ->getQuery()
168
            ->execute();
169
170
        /* Borrar luegos los perfiles */
171
        $em->createQueryBuilder()
172
            ->delete('AppBundle:Profile', 'p')
173
            ->where('p.organization IN (:items)')
174
            ->setParameter('items', $organizations)
175
            ->getQuery()
176
            ->execute();
177
178
        /* Los actores y las referencias se eliminan por el onDelete="CASCADE" de los elementos */
179
180
        /* Borrar luegos los elementos */
181
        $em->createQueryBuilder()
182
            ->delete('AppBundle:Element', 'e')
183
            ->where('e.organization IN (:items)')
184
            ->setParameter('items', $organizations)
185
            ->getQuery()
186
            ->execute();
187
188
        /* Finalmente las organizaciones */
189
        $em->createQueryBuilder()
190
            ->delete('AppBundle:Organization', 'o')
191
            ->where('o IN (:items)')
192
            ->setParameter('items', $organizations)
193
            ->getQuery()
194
            ->execute();
195
    }
196
197
    /**
198
     * @param Request $request
199
     * @param $organizations
200
     * @param \Doctrine\Common\Persistence\ObjectManager $em
201
     * @return bool
202
     */
203
    private function processRemoveOrganizations(Request $request, $organizations, $em)
204
    {
205
        $redirect = false;
206
        if ($request->get('confirm', '') === 'ok') {
207
            try {
208
                $this->deleteOrganizations($organizations);
209
                $em->flush();
210
                $this->addFlash('success', $this->get('translator')->trans('message.deleted', [], 'organization'));
211
            } catch (\Exception $e) {
212
                $this->addFlash('error', $this->get('translator')->trans('message.delete_error', [], 'organization'));
213
            }
214
            $redirect = true;
215
        }
216
        return $redirect;
217
    }
218
219
    /**
220
     * @param Request $request
221
     * @param \Doctrine\Common\Persistence\ObjectManager $em
222
     * @return bool
223
     */
224
    private function processSwitchOrganization(Request $request, $em)
225
    {
226
        $organization = $em->getRepository('AppBundle:Organization')->find($request->request->get('switch', null));
227
        if ($organization) {
228
            $this->get('session')->set('organization_id', $organization->getId());
229
            $this->addFlash('success', $this->get('translator')->trans('message.switched', ['%name%' => $organization->getName()], 'organization'));
230
            return true;
231
        }
232
        return false;
233
    }
234
235
    /**
236
     * @param Request $request
237
     * @return array
238
     */
239
    private function processOperations(Request $request)
240
    {
241
        $em = $this->getDoctrine()->getManager();
242
243
        $redirect = false;
244
        if ($request->request->has('switch')) {
245
            $redirect = $this->processSwitchOrganization($request, $em);
246
        }
247
248
        $items = $request->request->get('organizations', []);
249
        if (count($items) === 0) {
250
            $redirect = true;
251
        }
252
253
        $organizations = [];
254
        if (!$redirect) {
255
            $organizations = $em->getRepository('AppBundle:Organization')->findAllInListByIdButCurrent($items, $this->get(UserExtensionService::class)->getCurrentOrganization());
256
            $redirect = $this->processRemoveOrganizations($request, $organizations, $em);
257
        }
258
        return array($redirect, $organizations);
259
    }
260
}
261