RaLocationController::manageAction()   B
last analyzed

Complexity

Conditions 9
Paths 96

Size

Total Lines 62

Duplication

Lines 19
Ratio 30.65 %

Importance

Changes 0
Metric Value
dl 19
loc 62
rs 7.2735
c 0
b 0
f 0
cc 9
nc 96
nop 1

How to fix   Long Method   

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
/**
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 Surfnet\StepupRa\RaBundle\Command\SelectInstitutionCommand;
27
use Surfnet\StepupRa\RaBundle\Form\Type\ChangeRaLocationType;
28
use Surfnet\StepupRa\RaBundle\Form\Type\CreateRaLocationType;
29
use Surfnet\StepupRa\RaBundle\Form\Type\RemoveRaLocationType;
30
use Surfnet\StepupRa\RaBundle\Form\Type\SelectInstitutionType;
31
use Surfnet\StepupRa\RaBundle\Service\ProfileService;
32
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
33
use Symfony\Component\Form\FormError;
34
use Symfony\Component\HttpFoundation\Request;
35
use Symfony\Component\HttpFoundation\Response;
36
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
37
38
/**
39
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects) By making the Form Type classes explicit, MD now realizes couping
40
 *                                                 is to high.
41
 */
42
final class RaLocationController extends Controller
0 ignored issues
show
Deprecated Code introduced by
The class Symfony\Bundle\Framework...e\Controller\Controller has been deprecated with message: since Symfony 4.2, use "Symfony\Bundle\FrameworkBundle\Controller\AbstractController" instead.

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
43
{
44
    /**
45
     * @Template
46
     * @param Request $request
47
     * @return array|Response
48
     */
49
    public function manageAction(Request $request)
50
    {
51
        $this->denyAccessUnlessGranted(['ROLE_RA']);
52
53
        $institutionParameter = $request->get('institution');
54
55
        $identity = $this->getCurrentUser();
56
        $this->get('logger')->notice('Starting search for locations');
57
58
        $profile = $this->getProfileService()->findByIdentityId($identity->id);
59
60 View Code Duplication
        if ($this->isGranted('ROLE_SRAA')) {
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...
61
            $institution = $identity->institution;
62
            $choices = $this->getInstitutionListingService()->getAll();
63
        } else {
64
            $choices = $profile->getRaaInstitutions();
65
            $institution = reset($choices);
66
        }
67
68
        if (in_array($institutionParameter, $choices)) {
69
            $institution = $institutionParameter;
70
        }
71
72
        // Only show the form if more than one institutions where found.
73 View Code Duplication
        if (count($choices) > 1) {
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...
74
            $command = new SelectInstitutionCommand();
75
            $command->institution = $institution;
76
            $command->availableInstitutions = $choices;
77
78
            $form = $this->createForm(SelectInstitutionType::class, $command);
79
            $form->handleRequest($request);
80
81
            if ($form->isSubmitted() && $form->isValid()) {
82
                $institution = $command->institution;
83
            }
84
        }
85
86
87
        $command = new SearchRaLocationsCommand();
88
        $command->institution = $institution;
89
        $command->orderBy = $request->get('orderBy');
90
        $command->orderDirection = $request->get('orderDirection');
91
92
        $locations = $this->getRaLocationService()->search($command);
93
94
        $removalForm = $this->createForm(RemoveRaLocationType::class, new RemoveRaLocationCommand());
95
96
        $this->get('logger')->notice(sprintf(
97
            'Searching for RA locations yielded "%d" results',
98
            $locations->getTotalItems()
99
        ));
100
101
        return [
102
            'form'                  => isset($form) ? $form->createView() : null,
103
            'institution'           => $institution,
104
            'locations'             => $locations,
105
            'removalForm'           => $removalForm->createView(),
106
            'orderBy'               => $command->orderBy,
107
            'orderDirection'        => $command->orderDirection ?: 'asc',
108
            'inverseOrderDirection' => $command->orderDirection === 'asc' ? 'desc' : 'asc',
109
        ];
110
    }
111
112
    public function createAction(Request $request)
113
    {
114
        $this->denyAccessUnlessGranted(['ROLE_RA']);
115
        $logger = $this->get('logger');
116
117
        $institution = $request->get('institution');
118
119
        $identity = $this->getCurrentUser();
120
        $command = new CreateRaLocationCommand();
121
        $command->institution = $institution;
122
        $command->currentUserId = $identity->id;
123
124
        $form = $this->createForm(CreateRaLocationType::class, $command)->handleRequest($request);
125
126 View Code Duplication
        if ($form->isSubmitted() && $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...
127
            $logger->debug('RA Location form submitted, start processing command');
128
129
            $success = $this->getRaLocationService()->create($command);
130
131
            if ($success) {
132
                $this->addFlash(
133
                    'success',
134
                    $this->get('translator')->trans('ra.create_ra_location.created')
135
                );
136
137
                $logger->debug('RA Location added, redirecting to the RA location overview');
138
                return $this->redirectToRoute('ra_locations_manage', ['institution' => $command->institution]);
139
            }
140
141
            $logger->debug('RA Location creation failed, adding error to form');
142
            $this->addFlash('error', 'ra.create_ra_location.error.middleware_command_failed');
143
        }
144
145
        return $this->render('SurfnetStepupRaRaBundle:ra_location:create.html.twig', [
146
            'form' => $form->createView()
147
        ]);
148
    }
149
150
    public function changeAction(Request $request)
151
    {
152
        $this->denyAccessUnlessGranted(['ROLE_RA']);
153
        $logger = $this->get('logger');
154
155
        $requestedLocationId = $request->get('locationId');
156
        $raLocation = $this->getRaLocationService()->find($requestedLocationId);
157
158
        if (!$raLocation) {
159
            $logger->warning(sprintf('RaLocation for id "%s" not found', $requestedLocationId));
160
            throw new NotFoundHttpException();
161
        }
162
163
        $identity = $this->getCurrentUser();
164
165
        $command = new ChangeRaLocationCommand();
166
        $command->institution = $raLocation->institution;
167
        $command->currentUserId = $identity->id;
168
        $command->id = $raLocation->id;
169
        $command->name = $raLocation->name;
170
        $command->location = $raLocation->location;
171
        $command->contactInformation = $raLocation->contactInformation;
172
173
        $form = $this->createForm(ChangeRaLocationType::class, $command)->handleRequest($request);
174
175 View Code Duplication
        if ($form->isSubmitted() && $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...
176
            $logger->debug('RA Location form submitted, start processing command');
177
178
            $success = $this->getRaLocationService()->change($command);
179
180
            if ($success) {
181
                $this->addFlash(
182
                    'success',
183
                    $this->get('translator')->trans('ra.create_ra_location.changed')
184
                );
185
186
                $logger->debug('RA Location added, redirecting to the RA location overview');
187
                return $this->redirectToRoute('ra_locations_manage', ['institution' => $command->institution]);
188
            }
189
190
            $logger->debug('RA Location creation failed, adding error to form');
191
            $this->addFlash('error', 'ra.create_ra_location.error.middleware_command_failed');
192
        }
193
194
        return $this->render('SurfnetStepupRaRaBundle:ra_location:change.html.twig', [
195
            'form' => $form->createView()
196
        ]);
197
    }
198
199
    /**
200
     * @param Request $request
201
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
202
     */
203 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...
204
    {
205
        $this->denyAccessUnlessGranted(['ROLE_RA']);
206
207
        $logger = $this->get('logger');
208
209
        $logger->notice('Received request to remove RA location');
210
211
        $command = new RemoveRaLocationCommand();
212
        $command->currentUserId = $this->getCurrentUser()->id;
213
214
        $form = $this->createForm(RemoveRaLocationType::class, $command);
215
        $form->handleRequest($request);
216
217
        $logger->info(sprintf(
218
            'Sending middleware request to remove RA location "%s" belonging to "%s" on behalf of "%s"',
219
            $command->locationId,
220
            $command->institution,
221
            $command->currentUserId
222
        ));
223
224
        $translator = $this->get('translator');
225
        $flashBag = $this->get('session')->getFlashBag();
226
        if ($this->getRaLocationService()->remove($command)) {
227
            $logger->notice('RA Location removal Succeeded');
228
            $flashBag->add('success', $translator->trans('ra.ra_location.revocation.removed'));
229
        } else {
230
            $logger->notice('RA Location removal Failed');
231
            $flashBag->add('error', $translator->trans('ra.ra_location.revocation.could_not_remove'));
232
        }
233
234
        $logger->notice('Redirecting back to RA Location Manage Page');
235
236
        return $this->redirectToRoute('ra_locations_manage', ['institution' => $command->institution]);
237
    }
238
239
    /**
240
     * @return \Surfnet\StepupRa\RaBundle\Service\RaLocationService
241
     */
242
    private function getRaLocationService()
243
    {
244
        return $this->get('ra.service.ra_location');
245
    }
246
247
    /**
248
     * @return \Surfnet\StepupMiddlewareClientBundle\Identity\Dto\Identity
249
     */
250
    private function getCurrentUser()
251
    {
252
        return $this->get('security.token_storage')->getToken()->getUser();
253
    }
254
255
    /**
256
     * @return ProfileService
257
     */
258
    private function getProfileService()
259
    {
260
        return $this->get('ra.service.profile');
261
    }
262
263
    /**
264
     * @return InstitutionListingService
265
     */
266
    private function getInstitutionListingService()
267
    {
268
        return $this->get('ra.service.institution_listing');
269
    }
270
}
271