UnitController::indexAction()   B
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 32
Code Lines 21

Duplication

Lines 32
Ratio 100 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 32
loc 32
rs 8.5806
cc 4
eloc 21
nc 3
nop 1
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 UnitController extends Controller
38
{
39
    /**
40
     * @Route("/centro/importar/unidades", name="organization_import_unit_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->importUnitsFromCsv($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.unit_import', [], 'import');
66
67
        return $this->render('admin/organization/import/unit_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 importUnitsFromCsv($file, Organization $organization)
81
    {
82
        $newUnitCount = 0;
83
        $existingUnitCount = 0;
84
85
        $em = $this->getDoctrine()->getManager();
86
        $base = $em->getRepository('AppBundle:Element')->findOneByOrganizationAndCurrentCode($organization, 'unit');
0 ignored issues
show
Bug introduced by
The method findOneByOrganizationAndCurrentCode() does not exist on Doctrine\Common\Persistence\ObjectRepository. Did you maybe mean findOneBy()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
87
88
        if (null === $base) {
89
            return null;
90
        }
91
92
        $importer = new CsvImporter($file, true);
93
94
        $unitCollection = [];
95
96
        try {
97
            /** @var Profile $tutorProfile */
98
            $tutorProfile = $em->getRepository('AppBundle:Profile')
0 ignored issues
show
Bug introduced by
The method findOneByOrganizationAndCode() does not exist on Doctrine\Common\Persistence\ObjectRepository. Did you maybe mean findOneBy()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
99
                ->findOneByOrganizationAndCode($organization, 'tutor');
100
101
            if (null === $tutorProfile) {
102
                return null;
103
            }
104
105
            while ($data = $importer->get(100)) {
106
                foreach ($data as $userData) {
107
                    if (!isset($userData['Unidad'])) {
108
                        return null;
109
                    }
110
                    $unitName = $userData['Unidad'];
111
112 View Code Duplication
                    if (isset($unitCollection[$unitName])) {
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
                        $unit = $unitCollection[$unitName];
114
                    } else {
115
                        $unit = $em->getRepository('AppBundle:Element')->getChildrenQueryBuilder($base)
116
                            ->andWhere('node.name = :unit')
117
                            ->setParameter('unit', $unitName)
118
                            ->getQuery()
119
                            ->getOneOrNullResult();
120
121
                        if (null === $unit) {
122
                            $unit = new Element();
123
                            $unit
124
                                ->setOrganization($organization)
125
                                ->setParent($base)
126
                                ->setName($unitName)
127
                                ->setCode($unitName)
128
                                ->setLocked(false);
129
130
                            $em->persist($unit);
131
132
                            $newUnitCount++;
133
                        } else {
134
                            $existingUnitCount++;
135
                        }
136
137
                        $unitCollection[$unitName] = $unit;
138
                    }
139
140
                    preg_match_all('/\b(.*) \(.*\)/U', $userData['Tutor/a'], $matches, PREG_SET_ORDER, 0);
141
142
                    $matches = array_map(function($element) {
143
                        return $element[1];
144
                    }, $matches);
145
                    $matches = array_unique($matches);
146
147 View Code Duplication
                    if (null !== $matches) {
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...
148
                        foreach ($matches as $tutor) {
149
                            /** @var User|null $user */
150
                            $user = $em->getRepository('AppBundle:User')->findOneByOrganizationAndFullName($organization, $tutor, new \DateTime());
0 ignored issues
show
Bug introduced by
The method findOneByOrganizationAndFullName() does not exist on Doctrine\Common\Persistence\ObjectRepository. Did you maybe mean findOneBy()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
151
                            if ($user) {
152
                                $role = $em->getRepository('AppBundle:Role')->findOneBy([
153
                                    'element' => $unit,
154
                                    'profile' => $tutorProfile,
155
                                    'user' => $user
156
                                ]);
157
                                if (null === $role) {
158
                                    $role = new Role();
159
                                    $role
160
                                        ->setElement($unit)
161
                                        ->setProfile($tutorProfile)
162
                                        ->setUser($user);
163
                                    $em->persist($role);
164
                                    $unit->addRole($role);
165
                                }
166
                            }
167
                        }
168
                    }
169
                }
170
            }
171
            $em->flush();
172
        } catch (Exception $e) {
173
            return null;
174
        }
175
176
        return [
177
            'new_unit_count' => $newUnitCount,
178
            'existing_unit_count' => $existingUnitCount,
179
            'unit_collection' => $unitCollection
180
        ];
181
    }
182
}
183