SubjectController::importSubjectsFromCsv()   F
last analyzed

Complexity

Conditions 30
Paths 1984

Size

Total Lines 187
Code Lines 126

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 187
rs 2
c 1
b 0
f 0
cc 30
eloc 126
nc 1984
nop 3

How to fix   Long Method    Complexity   

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-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\Organization\Import;
22
23
use AppBundle\Entity\Element;
24
use AppBundle\Entity\ElementRepository;
25
use AppBundle\Entity\Organization;
26
use AppBundle\Entity\Profile;
27
use AppBundle\Entity\Role;
28
use AppBundle\Entity\User;
29
use AppBundle\Form\Model\SubjectImport;
30
use AppBundle\Form\Type\Import\SubjectType;
31
use AppBundle\Security\OrganizationVoter;
32
use AppBundle\Utils\CsvImporter;
33
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
34
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
35
use Symfony\Component\Config\Definition\Exception\Exception;
36
use Symfony\Component\HttpFoundation\Request;
37
38
class SubjectController extends Controller
39
{
40
    /**
41
     * @Route("/centro/importar/asignaturas", name="organization_import_subject_form", methods={"GET", "POST"})
42
     */
43 View Code Duplication
    public function indexAction(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...
44
    {
45
        $organization = $this->get('AppBundle\Service\UserExtensionService')->getCurrentOrganization();
46
        $this->denyAccessUnlessGranted(OrganizationVoter::MANAGE, $organization);
47
48
        $formData = new SubjectImport();
49
        $form = $this->createForm(SubjectType::class, $formData);
50
        $form->handleRequest($request);
51
52
        $stats = null;
53
        $breadcrumb = [];
54
55
        if ($form->isSubmitted() && $form->isValid()) {
56
57
            $stats = $this->importSubjectsFromCsv($formData->getFile()->getPathname(), $organization, [
58
                'add_new_teachers' => $formData->getAddNewTeachers(),
59
                'remove_existing_teachers' => $formData->getRemoveExistingTeachers()
60
            ]);
61
62
            if (null !== $stats) {
63
                $this->addFlash('success', $this->get('translator')->trans('message.import_ok', [], 'import'));
64
                $breadcrumb[] = ['fixed' => $this->get('translator')->trans('title.import_result', [], 'import')];
65
            } else {
66
                $this->addFlash('error', $this->get('translator')->trans('message.import_error', [], 'import'));
67
            }
68
        }
69
        $title = $this->get('translator')->trans('title.subject_import', [], 'import');
70
71
        return $this->render('admin/organization/import/subject_form.html.twig', [
72
            'title' => $title,
73
            'breadcrumb' => $breadcrumb,
74
            'form' => $form->createView(),
75
            'stats' => $stats
76
        ]);
77
    }
78
79
    /**
80
     * @param string $file
81
     * @param Organization $organization
82
     * @param array $options
83
     * @return array|null
84
     */
85
    private function importSubjectsFromCsv($file, Organization $organization, array $options = [])
86
    {
87
        $addNewTeachers = isset($options['add_new_teachers']) && $options['add_new_teachers'];
88
        $removeExistingTeachers = isset($options['remove_existing_teachers']) && $options['remove_existing_teachers'];
89
90
        $newCount = 0;
91
        $existingCount = 0;
92
93
        $em = $this->getDoctrine()->getManager();
94
95
        /** @var ElementRepository $elementRepository */
96
        $elementRepository = $em->getRepository('AppBundle:Element');
97
98
        $baseSubject = $elementRepository->findOneByOrganizationAndCurrentCode($organization, 'subject');
99
        $baseUnit = $elementRepository->findOneByOrganizationAndCurrentCode($organization, 'unit');
100
101
        if (null === $baseSubject || null === $baseUnit) {
102
            return null;
103
        }
104
105
        $importer = new CsvImporter($file, true);
106
107
        $unitCollection = [];
108
        $unitFolderCollection = [];
109
        $collection = [];
110
111
        $teacherCollection = [];
112
        $teacherCache = [];
113
114
        try {
115
            /** @var Profile $teacherProfile */
116
            $teacherProfile = $em->getRepository('AppBundle:Profile')
117
                ->findOneByOrganizationAndCode($organization, 'teacher');
118
119
            if (null === $teacherProfile) {
120
                return null;
121
            }
122
123
            while ($data = $importer->get(100)) {
124
                foreach ($data as $userData) {
125
                    if (!isset($userData['Unidad'], $userData['Materia'], $userData['Profesor/a'])) {
126
                        return null;
127
                    }
128
                    $unitName = $userData['Unidad'];
129
130
                    if (isset($unitCollection[$unitName])) {
131
                        $unit = $unitCollection[$unitName];
132
                    } else {
133
                        $unit = $elementRepository->getChildrenQueryBuilder($baseUnit)
134
                            ->andWhere('node.code = :unit')
135
                            ->setParameter('unit', $unitName)
136
                            ->getQuery()
137
                            ->getOneOrNullResult();
138
139
                        $unitCollection[$unitName] = $unit;
140
                    }
141
142
                    if ($unit) {
143
                        $subjectName = $userData['Unidad'].' - '.$userData['Materia'];
144
                        $displayName = $unit->getName().' - '.$userData['Materia'];
145
146
                        $new = false;
147
                        $subject = null;
148
149
                        if (!isset($teacherCollection[$subjectName]['subject'])) {
150
                            if (isset($unitFolderCollection[$unitName])) {
151
                                $unitFolder = $unitFolderCollection[$unitName];
152
                            } else {
153
                                $unitFolder = $elementRepository->getChildrenQueryBuilder($baseSubject)
154
                                    ->andWhere('node.code = :unit')
155
                                    ->setParameter('unit', $unitName)
156
                                    ->getQuery()
157
                                    ->getOneOrNullResult();
158
159
                                if (null === $unitFolder) {
160
                                    $unitFolder = new Element();
161
                                    $unitFolder
162
                                        ->setOrganization($organization)
163
                                        ->setParent($baseSubject)
164
                                        ->setName($unit->getName())
165
                                        ->setCode($unit->getCode())
166
                                        ->setFolder(true);
167
168
                                    $unitFolder->addLabel($unit);
169
170
                                    $em->persist($unitFolder);
171
172
                                    $new = true;
173
                                }
174
                                $unitFolderCollection[$unitName] = $unitFolder;
175
                            }
176
177
                            if (!$new) {
178
                                $subject = $elementRepository->getChildrenQueryBuilder($baseSubject)
179
                                    ->andWhere('node.code = :subject')
180
                                    ->setParameter('subject', $subjectName)
181
                                    ->leftJoin('node.labels', 'l')
182
                                    ->andWhere('l = :unit')
183
                                    ->setParameter('unit', $unit)
184
                                    ->getQuery()
185
                                    ->getOneOrNullResult();
186
                            }
187
188
                            if (null === $subject) {
189
                                $subject = new Element();
190
                                $subject
191
                                    ->setOrganization($organization)
192
                                    ->setParent($unitFolder)
193
                                    ->setName($displayName)
194
                                    ->setCode($subjectName)
195
                                    ->setFolder(false)
196
                                    ->setLocked(false);
197
198
                                $em->persist($subject);
199
                                $newCount++;
200
                            } else {
201
                                $existingCount++;
202
                            }
203
                            $subject->addLabel($unit);
204
                            $teacherCollection[$subjectName] = ['subject' => $subject, 'teachers' => []];
205
                            $collection[] = $subject;
206
                        }
207
208
                        $tutor = $userData['Profesor/a'];
209
210
                        if (isset($teacherCache[$tutor]) && !in_array($teacherCache[$tutor], $teacherCollection[$subjectName]['teachers'])) {
211
                            $teacherCollection[$subjectName]['teachers'][] = $teacherCache[$tutor];
212
                        } else {
213
                            /** @var User|null $user */
214
                            $user = $em->getRepository('AppBundle:User')->findOneByOrganizationAndFullName($organization, $tutor, new \DateTime());
215
                            if ($user && !in_array($user, $teacherCollection[$subjectName]['teachers'])) {
216
                                $teacherCollection[$subjectName]['teachers'][] = $user;
217
                                $teacherCache[$tutor] = $user;
218
                            }
219
                        }
220
                    }
221
                }
222
            }
223
224
            if ($addNewTeachers || $removeExistingTeachers) {
225
                foreach ($teacherCollection as $data) {
226
                    /** @var Element $subject */
227
                    $subject = $data['subject'];
228
                    $oldRoles = $subject->getRoles();
229
                    $oldTeachers = [];
230
                    $oldTeachersReferences = [];
231
                    foreach ($oldRoles as $role) {
232
                        if ($role->getProfile() === $teacherProfile) {
233
                            $oldTeachers[] = $role->getUser();
234
                            $oldTeachersReferences[$role->getUser()->getId()] = $role;
235
                        }
236
                    }
237
238
                    $insert = array_diff($data['teachers'], $oldTeachers);
239
                    $delete = array_diff($oldTeachers, $data['teachers']);
240
241
                    if ($removeExistingTeachers) {
242
                        /** @var User $teacher */
243
                        foreach ($delete as $teacher) {
244
                            $em->remove($oldTeachersReferences[$teacher->getId()]);
245
                        }
246
                    }
247
248
                    if ($addNewTeachers) {
249
                        foreach ($insert as $teacher) {
250
                            $role = new Role();
251
                            $role
252
                                ->setElement($subject)
253
                                ->setProfile($teacherProfile)
254
                                ->setUser($teacher);
255
                            $em->persist($role);
256
                            $subject->addRole($role);
257
                        }
258
                    }
259
                }
260
            }
261
            $em->flush();
262
        } catch (Exception $e) {
263
            return null;
264
        }
265
266
        return [
267
            'new_count' => $newCount,
268
            'existing_count' => $existingCount,
269
            'collection' => $collection
270
        ];
271
    }
272
}
273