DepartmentController::importDepartmentsFromCsv()   C
last analyzed

Complexity

Conditions 12
Paths 49

Size

Total Lines 95
Code Lines 63

Duplication

Lines 47
Ratio 49.47 %

Importance

Changes 0
Metric Value
dl 47
loc 95
rs 5.034
c 0
b 0
f 0
cc 12
eloc 63
nc 49
nop 2

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\Organization;
25
use AppBundle\Entity\Profile;
26
use AppBundle\Entity\Role;
27
use AppBundle\Entity\User;
28
use AppBundle\Form\Model\UnitImport;
29
use AppBundle\Form\Type\Import\UnitType;
30
use AppBundle\Security\OrganizationVoter;
31
use AppBundle\Utils\CsvImporter;
32
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
33
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
34
use Symfony\Component\Config\Definition\Exception\Exception;
35
use Symfony\Component\HttpFoundation\Request;
36
37
class DepartmentController extends Controller
38
{
39
    /**
40
     * @Route("/centro/importar/departamentos", name="organization_import_department_form", methods={"GET", "POST"})
41
     */
42 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...
43
    {
44
        $organization = $this->get('AppBundle\Service\UserExtensionService')->getCurrentOrganization();
45
        $this->denyAccessUnlessGranted(OrganizationVoter::MANAGE, $organization);
46
47
        $formData = new UnitImport();
48
        $form = $this->createForm(UnitType::class, $formData);
49
        $form->handleRequest($request);
50
51
        $stats = null;
52
        $breadcrumb = [];
53
54
        if ($form->isSubmitted() && $form->isValid()) {
55
56
            $stats = $this->importDepartmentsFromCsv($formData->getFile()->getPathname(), $organization);
57
58
            if (null !== $stats) {
59
                $this->addFlash('success', $this->get('translator')->trans('message.import_ok', [], 'import'));
60
                $breadcrumb[] = ['fixed' => $this->get('translator')->trans('title.import_result', [], 'import')];
61
            } else {
62
                $this->addFlash('error', $this->get('translator')->trans('message.import_error', [], 'import'));
63
            }
64
        }
65
        $title = $this->get('translator')->trans('title.department_import', [], 'import');
66
67
        return $this->render('admin/organization/import/department_form.html.twig', [
68
            'title' => $title,
69
            'breadcrumb' => $breadcrumb,
70
            'form' => $form->createView(),
71
            'stats' => $stats
72
        ]);
73
    }
74
75
    /**
76
     * @param string $file
77
     * @param Organization $organization
78
     * @return array|null
79
     */
80
    private function importDepartmentsFromCsv($file, Organization $organization)
81
    {
82
        $newDeptCount = 0;
83
        $existingDeptCount = 0;
84
85
        $em = $this->getDoctrine()->getManager();
86
        $base = $em->getRepository('AppBundle:Element')->findOneByOrganizationAndCurrentCode($organization, 'department');
87
88
        if (null === $base) {
89
            return null;
90
        }
91
92
        $importer = new CsvImporter($file, true);
93
94
        $deptCollection = [];
95
96
        try {
97
            /** @var Profile $headProfile */
98
            $headProfile = $em->getRepository('AppBundle:Profile')
99
                ->findOneByOrganizationAndCode($organization, 'department_head');
100
101
            if (null === $headProfile) {
102
                return null;
103
            }
104
105
            while ($data = $importer->get(100)) {
106
                foreach ($data as $userData) {
107
                    if (!isset($userData['Descripción'])) {
108
                        return null;
109
                    }
110
                    $deptName = $userData['Descripción'];
111
112 View Code Duplication
                    if (isset($deptCollection[$deptName])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
113
                        $dept = $deptCollection[$deptName];
114
                    } else {
115
                        $dept = $em->getRepository('AppBundle:Element')->getChildrenQueryBuilder($base)
116
                            ->andWhere('node.name = :department')
117
                            ->setParameter('department', $deptName)
118
                            ->getQuery()
119
                            ->getOneOrNullResult();
120
121
                        if (null === $dept) {
122
                            $dept = new Element();
123
                            $dept
124
                                ->setOrganization($organization)
125
                                ->setParent($base)
126
                                ->setName($deptName)
127
                                ->setCode($deptName)
128
                                ->setLocked(false);
129
130
                            $em->persist($dept);
131
132
                            $newDeptCount++;
133
                        } else {
134
                            $existingDeptCount++;
135
                        }
136
137
                        $deptCollection[$deptName] = $dept;
138
                    }
139
140
                    $head = $userData['Jefe de departamento'];
141
142 View Code Duplication
                    if ($head) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
143
                        /** @var User|null $user */
144
                        $user = $em->getRepository('AppBundle:User')->findOneByOrganizationAndFullName($organization, $head, new \DateTime());
145
                        if ($user) {
146
                            $role = $em->getRepository('AppBundle:Role')->findOneBy([
147
                                'element' => $dept,
148
                                'profile' => $headProfile,
149
                                'user' => $user
150
                            ]);
151
                            if (null === $role) {
152
                                $role = new Role();
153
                                $role
154
                                    ->setElement($dept)
155
                                    ->setProfile($headProfile)
156
                                    ->setUser($user);
157
                                $em->persist($role);
158
                                $dept->addRole($role);
159
                            }
160
                        }
161
                    }
162
                }
163
            }
164
            $em->flush();
165
        } catch (Exception $e) {
166
            return null;
167
        }
168
169
        return [
170
            'new_dept_count' => $newDeptCount,
171
            'existing_dept_count' => $existingDeptCount,
172
            'dept_collection' => $deptCollection
173
        ];
174
    }
175
}
176