TeacherController   A
last analyzed

Complexity

Total Complexity 18

Size/Duplication

Total Lines 160
Duplicated Lines 22.5 %

Coupling/Cohesion

Components 1
Dependencies 11

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 18
c 3
b 0
f 0
lcom 1
cbo 11
dl 36
loc 160
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B indexAction() 36 36 4
F importTeachersFromCsv() 0 111 14

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
  Á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\Membership;
24
use AppBundle\Entity\Organization;
25
use AppBundle\Entity\User;
26
use AppBundle\Form\Model\TeacherImport;
27
use AppBundle\Form\Type\Import\TeacherType;
28
use AppBundle\Security\OrganizationVoter;
29
use AppBundle\Utils\CsvImporter;
30
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
31
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
32
use Symfony\Component\Config\Definition\Exception\Exception;
33
use Symfony\Component\HttpFoundation\Request;
34
35
class TeacherController extends Controller
36
{
37
    /**
38
     * @Route("/centro/importar/profesorado", name="organization_import_teacher_form", methods={"GET", "POST"})
39
     */
40 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...
41
    {
42
        $organization = $this->get('AppBundle\Service\UserExtensionService')->getCurrentOrganization();
43
        $this->denyAccessUnlessGranted(OrganizationVoter::MANAGE, $organization);
44
45
        $formData = new TeacherImport();
46
        $form = $this->createForm(TeacherType::class, $formData);
47
        $form->handleRequest($request);
48
49
        $stats = null;
50
        $breadcrumb = [];
51
52
        if ($form->isSubmitted() && $form->isValid()) {
53
54
            $stats = $this->importTeachersFromCsv($formData->getFile()->getPathname(), $organization, [
55
                'generate_password' => $formData->getGeneratePassword(),
56
                'external_check' => $formData->isExternalPassword()
57
            ]);
58
59
            if (null !== $stats) {
60
                $this->addFlash('success', $this->get('translator')->trans('message.import_ok', [], 'import'));
61
                $breadcrumb[] = ['fixed' => $this->get('translator')->trans('title.import_result', [], 'import')];
62
            } else {
63
                $this->addFlash('error', $this->get('translator')->trans('message.import_error', [], 'import'));
64
            }
65
        }
66
        $title = $this->get('translator')->trans('title.teacher_import', [], 'import');
67
68
        return $this->render('admin/organization/import/teacher_form.html.twig', [
69
            'title' => $title,
70
            'breadcrumb' => $breadcrumb,
71
            'form' => $form->createView(),
72
            'generate_password' => $formData->getGeneratePassword(),
73
            'stats' => $stats
74
        ]);
75
    }
76
77
    /**
78
     * @param string $file
79
     * @param Organization $organization
80
     * @param array $options
81
     * @return array|null
82
     */
83
    private function importTeachersFromCsv($file, Organization $organization, $options = [])
84
    {
85
        $generatePassword = isset($options['generate_password']) && $options['generate_password'];
86
        $external = isset($options['external_check']) && $options['external_check'];
87
        $newUserCount = 0;
88
        $newMemberships = 0;
89
        $existingUsers = 0;
90
        $existingMemberships = 0;
91
92
        $em = $this->getDoctrine()->getManager();
93
94
        $importer = new CsvImporter($file, true);
95
        $encoder = $this->container->get('security.password_encoder');
96
97
        $userCollection = [];
98
        $newUserCollection = [];
99
100
        try {
101
            while ($data = $importer->get(100)) {
102
                foreach ($data as $userData) {
103
                    if (!isset($userData['Usuario IdEA'])) {
104
                        return null;
105
                    }
106
                    $userName = $userData['Usuario IdEA'];
107
108
                    $user = $em->getRepository('AppBundle:User')->findOneBy(['loginUsername' => $userName]);
109
                    $alreadyProcessed = isset($userCollection[$userName]);
110
111
                    if (null === $user) {
112
                        if ($alreadyProcessed) {
113
                            $user = $userCollection[$userName];
114
                        } else {
115
                            $user = new User();
116
                            $fullName = explode(', ', $userData['Empleado/a']);
117
118
                            $user
119
                                ->setLoginUsername($userName)
120
                                ->setFirstName($fullName[1])
121
                                ->setLastName($fullName[0])
122
                                ->setInternalCode($userData['Empleado/a'])
123
                                ->setEnabled(true)
124
                                ->setGlobalAdministrator(false)
125
                                ->setGender(User::GENDER_NEUTRAL)
126
                                ->setAllowExternalCheck($external)
127
                                ->setExternalCheck($external);
128
129
                            if ($generatePassword) {
130
                                $user
131
                                    ->setPassword($encoder->encodePassword($user, $userData['Usuario IdEA']));
132
                            }
133
134
                            $em->persist($user);
135
136
                            $userCollection[$userName] = $user;
137
                            $newUserCollection[$userName] = $user;
138
139
                            $newUserCount++;
140
                        }
141
                    } else {
142
                        if (!$alreadyProcessed) {
143
                            $existingUsers++;
144
                            $userCollection[$userName] = $user;
145
                        }
146
                    }
147
148
                    $validFrom = \DateTime::createFromFormat('d/m/Y H:i:s', $userData['Fecha de toma de posesión'].'00:00:00');
149
                    $validUntil = ($userData['Fecha de cese']) ? \DateTime::createFromFormat('d/m/Y H:i:s', $userData['Fecha de cese'].'23:59:59') : null;
150
151
                    if (false === $validFrom) {
152
                        continue;
153
                    }
154
155
                    /** @var Membership $membership */
156
                    $membership = $em->getRepository('AppBundle:Membership')->findOneBy([
157
                        'organization' => $organization,
158
                        'user' => $user,
159
                        'validFrom' => $validFrom
160
                    ]);
161
162
                    if (null === $membership) {
163
                        $membership = new Membership();
164
                        $membership
165
                            ->setOrganization($organization)
166
                            ->setUser($user)
167
                            ->setValidFrom($validFrom)
168
                            ->setValidUntil($validUntil);
169
170
                        $em->persist($membership);
171
172
                        $newMemberships++;
173
                    } else {
174
                        $membership
175
                            ->setValidUntil($validUntil);
176
177
                        $existingMemberships++;
178
                    }
179
                }
180
            }
181
            $em->flush();
182
        } catch (Exception $e) {
183
            return null;
184
        }
185
186
        return [
187
            'new_user_count' => $newUserCount,
188
            'new_membership_count' => $newMemberships,
189
            'existing_user_count' => $existingUsers,
190
            'existing_membership_count' => $existingMemberships,
191
            'user_collection' => $newUserCollection
192
        ];
193
    }
194
}
195