Completed
Pull Request — develop (#113)
by Boy
07:07 queued 03:37
created

RaLocationController   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 191
Duplicated Lines 37.17 %

Coupling/Cohesion

Components 1
Dependencies 13

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 15
c 1
b 0
f 1
lcom 1
cbo 13
dl 71
loc 191
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
B manageAction() 0 29 3
B createAction() 18 36 3
B changeAction() 18 60 5
B removeAction() 35 35 2
A getRaLocationService() 0 4 1
A getCurrentUser() 0 4 1

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
/**
4
 * Copyright 2014 SURFnet bv
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * you may not use this file except in compliance with the License.
8
 * You may obtain a copy of the License at
9
 *
10
 *     http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * See the License for the specific language governing permissions and
16
 * limitations under the License.
17
 */
18
19
namespace Surfnet\StepupRa\RaBundle\Controller;
20
21
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
22
use Surfnet\StepupRa\RaBundle\Command\ChangeRaLocationCommand;
23
use Surfnet\StepupRa\RaBundle\Command\CreateRaLocationCommand;
24
use Surfnet\StepupRa\RaBundle\Command\RemoveRaLocationCommand;
25
use Surfnet\StepupRa\RaBundle\Command\SearchRaLocationsCommand;
26
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
27
use Symfony\Component\Form\FormError;
28
use Symfony\Component\HttpFoundation\Request;
29
use Symfony\Component\HttpFoundation\Response;
30
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
31
32
final class RaLocationController extends Controller
33
{
34
    /**
35
     * @Template
36
     * @param Request $request
37
     * @return array|Response
38
     */
39
    public function manageAction(Request $request)
40
    {
41
        $this->denyAccessUnlessGranted(['ROLE_RA']);
42
43
        $identity = $this->getCurrentUser();
44
        $this->get('logger')->notice('Starting search for locations');
45
46
        $command = new SearchRaLocationsCommand();
47
        $command->institution = $identity->institution;
48
        $command->orderBy = $request->get('orderBy');
49
        $command->orderDirection = $request->get('orderDirection');
50
51
        $locations = $this->getRaLocationService()->search($command);
52
53
        $removalForm = $this->createForm('ra_remove_ra_location', new RemoveRaLocationCommand());
54
55
        $this->get('logger')->notice(sprintf(
56
            'Searching for RA locations yielded "%d" results',
57
            $locations->getTotalItems()
58
        ));
59
60
        return [
61
            'locations'             => $locations,
62
            'removalForm'           => $removalForm->createView(),
63
            'orderBy'               => $command->orderBy,
64
            'orderDirection'        => $command->orderDirection ?: 'asc',
65
            'inverseOrderDirection' => $command->orderDirection === 'asc' ? 'desc' : 'asc',
66
        ];
67
    }
68
69
    public function createAction(Request $request)
70
    {
71
        $this->denyAccessUnlessGranted(['ROLE_RA']);
72
        $logger = $this->get('logger');
73
74
        $identity = $this->getCurrentUser();
75
        $command = new CreateRaLocationCommand();
76
        $command->currentUserId = $this->getCurrentUser()->id;
77
        $command->institution = $identity->institution;
78
        $command->currentUserId = $identity->id;
79
80
        $form = $this->createForm('ra_create_ra_location', $command)->handleRequest($request);
81
82 View Code Duplication
        if ($form->isValid()) {
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...
83
            $logger->debug('RA Location form submitted, start processing command');
84
85
            $success = $this->getRaLocationService()->create($command);
86
87
            if ($success) {
88
                $this->addFlash(
89
                    'success',
90
                    $this->get('translator')->trans('ra.create_ra_location.created')
91
                );
92
93
                $logger->debug('RA Location added, redirecting to the RA location overview');
94
                return $this->redirectToRoute('ra_locations_manage');
95
            }
96
97
            $logger->debug('RA Location creation failed, adding error to form');
98
            $form->addError(new FormError('ra.create_ra_location.error.middleware_command_failed'));
99
        }
100
101
        return $this->render('SurfnetStepupRaRaBundle:RaLocation:create.html.twig', [
102
            'form' => $form->createView()
103
        ]);
104
    }
105
106
    public function changeAction(Request $request)
107
    {
108
        $this->denyAccessUnlessGranted(['ROLE_RA']);
109
        $logger = $this->get('logger');
110
111
        $requestedLocationId = $request->get('locationId');
112
        $raLocation = $this->getRaLocationService()->find($requestedLocationId);
113
114
        if (!$raLocation) {
115
            $logger->warning(sprintf('RaLocation for id "%s" not found', $requestedLocationId));
116
            throw new NotFoundHttpException();
117
        }
118
119
        $identity = $this->getCurrentUser();
120
121
        if ($raLocation->institution !== $identity->institution) {
122
            $logger->warning(
123
                sprintf(
124
                    'RaLocation "%s" found but of institution "%s" while we require "%s"',
125
                    $raLocation->id,
126
                    $raLocation->institution,
127
                    $identity->institution
128
                )
129
            );
130
        }
131
132
        $command = new ChangeRaLocationCommand();
133
        $command->currentUserId = $this->getCurrentUser()->id;
134
        $command->institution = $identity->institution;
135
        $command->currentUserId = $identity->id;
136
        $command->id = $raLocation->id;
137
        $command->name = $raLocation->name;
138
        $command->location = $raLocation->location;
139
        $command->contactInformation = $raLocation->contactInformation;
140
141
        $form = $this->createForm('ra_change_ra_location', $command)->handleRequest($request);
142
143 View Code Duplication
        if ($form->isValid()) {
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...
144
            $logger->debug('RA Location form submitted, start processing command');
145
146
            $success = $this->getRaLocationService()->change($command);
147
148
            if ($success) {
149
                $this->addFlash(
150
                    'success',
151
                    $this->get('translator')->trans('ra.create_ra_location.changed')
152
                );
153
154
                $logger->debug('RA Location added, redirecting to the RA location overview');
155
                return $this->redirectToRoute('ra_locations_manage');
156
            }
157
158
            $logger->debug('RA Location creation failed, adding error to form');
159
            $form->addError(new FormError('ra.create_ra_location.error.middleware_command_failed'));
160
        }
161
162
        return $this->render('SurfnetStepupRaRaBundle:RaLocation:change.html.twig', [
163
            'form' => $form->createView()
164
        ]);
165
    }
166
167
    /**
168
     * @param Request $request
169
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
170
     */
171 View Code Duplication
    public function removeAction(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...
172
    {
173
        $this->denyAccessUnlessGranted(['ROLE_RA']);
174
175
        $logger = $this->get('logger');
176
177
        $logger->notice('Received request to remove RA location');
178
179
        $command = new RemoveRaLocationCommand();
180
        $command->currentUserId = $this->getCurrentUser()->id;
181
182
        $form = $this->createForm('ra_remove_ra_location', $command);
183
        $form->handleRequest($request);
184
185
        $logger->info(sprintf(
186
            'Sending middleware request to remove RA location "%s" belonging to "%s" on behalf of "%s"',
187
            $command->locationId,
188
            $command->institution,
189
            $command->currentUserId
190
        ));
191
192
        $translator = $this->get('translator');
193
        $flashBag = $this->get('session')->getFlashBag();
194
        if ($this->getRaLocationService()->remove($command)) {
195
            $logger->notice('RA Location removal Succeeded');
196
            $flashBag->add('success', $translator->trans('ra.ra_location.revocation.removed'));
197
        } else {
198
            $logger->notice('RA Location removal Failed');
199
            $flashBag->add('error', $translator->trans('ra.ra_location.revocation.could_not_remove'));
200
        }
201
202
        $logger->notice('Redirecting back to RA Location Manage Page');
203
204
        return $this->redirectToRoute('ra_locations_manage');
205
    }
206
207
    /**
208
     * @return \Surfnet\StepupRa\RaBundle\Service\RaLocationService
209
     */
210
    private function getRaLocationService()
211
    {
212
        return $this->get('ra.service.ra_location');
213
    }
214
215
    /**
216
     * @return \Surfnet\StepupMiddlewareClientBundle\Identity\Dto\Identity
217
     */
218
    private function getCurrentUser()
219
    {
220
        return $this->get('security.token_storage')->getToken()->getUser();
221
    }
222
}
223