Completed
Pull Request — develop (#162)
by Michiel
06:09 queued 03:26
created

RaManagementController   A

Complexity

Total Complexity 29

Size/Duplication

Total Lines 316
Duplicated Lines 30.06 %

Coupling/Cohesion

Components 1
Dependencies 19

Importance

Changes 0
Metric Value
wmc 29
lcom 1
cbo 19
dl 95
loc 316
rs 10
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A manageAction() 0 39 2
A raCandidateSearchAction() 0 42 2
A getRaListingService() 0 4 1
A getRaCandidateService() 0 4 1
A getPaginator() 0 4 1
B createRaAction() 18 55 6
B amendRaInformationAction() 39 39 5
A changeRaRoleAction() 38 38 5
B retractRegistrationAuthorityAction() 0 44 6

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 Surfnet\StepupMiddlewareClient\Identity\Dto\RaListingSearchQuery;
22
use Surfnet\StepupRa\RaBundle\Command\AccreditCandidateCommand;
23
use Surfnet\StepupRa\RaBundle\Command\AmendRegistrationAuthorityInformationCommand;
24
use Surfnet\StepupRa\RaBundle\Command\ChangeRaRoleCommand;
25
use Surfnet\StepupRa\RaBundle\Command\RetractRegistrationAuthorityCommand;
26
use Surfnet\StepupRa\RaBundle\Command\SearchRaCandidatesCommand;
27
use Surfnet\StepupRa\RaBundle\Form\Type\AmendRegistrationAuthorityInformationType;
28
use Surfnet\StepupRa\RaBundle\Form\Type\ChangeRaRoleType;
29
use Surfnet\StepupRa\RaBundle\Form\Type\RetractRegistrationAuthorityType;
30
use Surfnet\StepupRa\RaBundle\Form\Type\SearchRaCandidatesType;
31
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
32
use Symfony\Component\Form\FormError;
33
use Symfony\Component\HttpFoundation\Request;
34
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
35
36
/**
37
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
38
 */
39
class RaManagementController extends Controller
40
{
41
    /**
42
     * @param Request $request
43
     * @return \Symfony\Component\HttpFoundation\Response
44
     */
45
    public function manageAction(Request $request)
46
    {
47
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
48
49
        $logger = $this->get('logger');
50
        $institution = $this->getUser()->institution;
51
52
        $logger->notice(sprintf('Loading overview of RA(A)s for institution "%s"', $institution));
53
54
        $searchQuery = (new RaListingSearchQuery($this->getUser()->institution, 1))
55
            ->setOrderBy($request->get('orderBy', 'commonName'))
56
            ->setOrderDirection($request->get('orderDirection', 'asc'));
57
58
        $service = $this->getRaListingService();
59
        $raList = $service->search($searchQuery);
60
61
        $pagination = $this->getPaginator()->paginate(
62
            $raList->getTotalItems() > 0 ? array_fill(0, $raList->getTotalItems(), 1) : [],
63
            $raList->getCurrentPage(),
64
            $raList->getItemsPerPage()
65
        );
66
67
        $logger->notice(sprintf(
68
            'Created overview of "%d" RA(A)s for institution "%s"',
69
            $raList->getTotalItems(),
70
            $institution
71
        ));
72
73
        /** @var \Surfnet\StepupMiddlewareClientBundle\Identity\Dto\RaListing[] $raListings */
74
        $raListings = $raList->getElements();
75
76
        return $this->render(
77
            'SurfnetStepupRaRaBundle:RaManagement:manage.html.twig',
78
            [
79
                'raList'     => $raListings,
80
                'pagination' => $pagination
81
            ]
82
        );
83
    }
84
85
    /**
86
     * @param Request $request
87
     * @return \Symfony\Component\HttpFoundation\Response
88
     */
89
    public function raCandidateSearchAction(Request $request)
90
    {
91
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
92
93
        $logger = $this->get('logger');
94
        $institution = $this->getUser()->institution;
95
96
        $logger->notice(sprintf('Searching for RaCandidates within institution "%s"', $institution));
97
98
        $command                 = new SearchRaCandidatesCommand();
99
        $command->institution    = $institution;
100
        $command->pageNumber     = (int) $request->get('p', 1);
101
        $command->orderBy        = $request->get('orderBy');
102
        $command->orderDirection = $request->get('orderDirection');
103
104
        $form = $this->createForm(SearchRaCandidatesType::class, $command, ['method' => 'get']);
105
        $form->handleRequest($request);
106
107
        $service = $this->getRaCandidateService();
108
        $raCandidateList = $service->search($command);
109
110
        $pagination = $this->getPaginator()->paginate(
111
            $raCandidateList->getTotalItems() > 0 ? array_fill(4, $raCandidateList->getTotalItems(), 1) : [],
112
            $raCandidateList->getCurrentPage(),
113
            $raCandidateList->getItemsPerPage()
114
        );
115
116
        $logger->notice(sprintf(
117
            'Searching for RaCandidates within institution "%s" yielded "%s" results',
118
            $institution,
119
            $raCandidateList->getTotalItems()
120
        ));
121
122
        return $this->render(
123
            'SurfnetStepupRaRaBundle:RaManagement:raCandidateOverview.html.twig',
124
            [
125
                'form'         => $form->createView(),
126
                'raCandidates' => $raCandidateList,
127
                'pagination'   => $pagination
128
            ]
129
        );
130
    }
131
132
    /**
133
     * @param Request $request
134
     * @return \Symfony\Component\HttpFoundation\Response
135
     */
136
    public function createRaAction(Request $request)
137
    {
138
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
139
        $logger = $this->get('logger');
140
141
        $logger->notice('Page for Accreditation of Identity to Ra or Raa requested');
142
        $identityId = $request->get('identityId');
143
        $raCandidate = $this->getRaCandidateService()->getRaCandidateByIdentityId($identityId);
144
145
        if (!$raCandidate) {
146
            $logger->warning(sprintf('RaCandidate based on identity "%s" not found', $identityId));
147
            throw new NotFoundHttpException();
148
        }
149
150
        if ($raCandidate->institution !== $this->getUser()->institution) {
151
            $user = $this->getUser();
152
            $logger->warning(sprintf(
153
                'Identity "%s" of "%s" illegally tried to accredit tried to accredit Identity "%s" of "%s"',
154
                $user->id,
155
                $user->institution,
156
                $raCandidate->identityId,
157
                $raCandidate->institution
158
            ));
159
            throw $this->createAccessDeniedException();
160
        }
161
162
        $command              = new AccreditCandidateCommand();
163
        $command->identityId  = $identityId;
164
        $command->institution = $raCandidate->institution;
165
166
        $form = $this->createForm(CreateRaType::class, $command)->handleRequest($request);
167 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...
168
            $logger->debug('Accreditation form submitted, start processing command');
169
170
            $success = $this->getRaCandidateService()->accreditCandidate($command);
171
172
            if ($success) {
173
                $this->addFlash(
174
                    'success',
175
                    $this->get('translator')->trans('ra.management.create_ra.identity_accredited')
176
                );
177
178
                $logger->debug('Identity Accredited, redirecting to candidate overview');
179
                return $this->redirectToRoute('ra_management_ra_candidate_search');
180
            }
181
182
            $logger->debug('Identity Accreditation failed, adding error to form');
183
            $form->addError(new FormError('ra.management.create_ra.error.middleware_command_failed'));
184
        }
185
186
        return $this->render('SurfnetStepupRaRaBundle:RaManagement:createRa.html.twig', [
187
            'raCandidate' => $raCandidate,
188
            'form'        => $form->createView()
189
        ]);
190
    }
191
192
    /**
193
     * @param Request $request
194
     * @param         $identityId
195
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
196
     */
197 View Code Duplication
    public function amendRaInformationAction(Request $request, $identityId)
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...
198
    {
199
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
200
201
        $logger = $this->get('logger');
202
        $logger->notice(sprintf("Loading information amendment form for RA(A) '%s'", $identityId));
203
204
        $raListing = $this->getRaListingService()->get($identityId);
205
206
        if (!$raListing) {
207
            $logger->warning(sprintf("RA listing for identity ID '%s' not found", $identityId));
208
            throw new NotFoundHttpException(sprintf("RA listing for identity ID '%s' not found", $identityId));
209
        }
210
211
        $command = new AmendRegistrationAuthorityInformationCommand();
212
        $command->identityId = $raListing->identityId;
213
        $command->location = $raListing->location;
214
        $command->contactInformation = $raListing->contactInformation;
215
216
        $form = $this->createForm(AmendRegistrationAuthorityInformationType::class, $command)->handleRequest($request);
217
        if ($form->isSubmitted() && $form->isValid()) {
218
            $logger->notice(sprintf("RA(A) '%s' information amendment form submitted, processing", $identityId));
219
220
            if ($this->get('ra.service.ra')->amendRegistrationAuthorityInformation($command)) {
221
                $this->addFlash('success', $this->get('translator')->trans('ra.management.amend_ra_info.info_amended'));
222
223
                $logger->notice(sprintf("RA(A) '%s' information successfully amended", $identityId));
224
                return $this->redirectToRoute('ra_management_manage');
225
            }
226
227
            $logger->notice(sprintf("Information of RA(A) '%s' failed to be amended, informing user", $identityId));
228
            $form->addError(new FormError('ra.management.amend_ra_info.error.middleware_command_failed'));
229
        }
230
231
        return $this->render('SurfnetStepupRaRaBundle:RaManagement:amendRaInformation.html.twig', [
232
            'raListing' => $raListing,
233
            'form' => $form->createView(),
234
        ]);
235
    }
236
237
    /**
238
     * @param Request $request
239
     * @param         $identityId
240
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
241
     */
242 View Code Duplication
    public function changeRaRoleAction(Request $request, $identityId)
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...
243
    {
244
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
245
        $logger = $this->get('logger');
246
247
        $logger->notice(sprintf("Loading change Ra Role form for RA(A) '%s'", $identityId));
248
249
        $raListing = $this->getRaListingService()->get($identityId);
250
        if (!$raListing) {
251
            $logger->warning(sprintf("RA listing for identity ID '%s' not found", $identityId));
252
            throw new NotFoundHttpException(sprintf("RA listing for identity ID '%s' not found", $identityId));
253
        }
254
255
        $command              = new ChangeRaRoleCommand();
256
        $command->identityId  = $raListing->identityId;
257
        $command->institution = $raListing->institution;
258
        $command->role        = $raListing->role;
259
260
        $form = $this->createForm(ChangeRaRoleType::class, $command)->handleRequest($request);
261
        if ($form->isSubmitted() && $form->isValid()) {
262
            $logger->notice(sprintf('RA(A) "%s" Change Role form submitted, processing', $identityId));
263
264
            if ($this->get('ra.service.ra')->changeRegistrationAuthorityRole($command)) {
265
                $logger->notice('Role successfully changed');
266
267
                $this->addFlash('success', $this->get('translator')->trans('ra.management.change_ra_role_changed'));
268
                return $this->redirectToRoute('ra_management_manage');
269
            }
270
271
            $logger->notice(sprintf('Role of RA(A) "%s" could not be changed, informing user', $identityId));
272
            $form->addError(new FormError('ra.management.change_ra_role.middleware_command_failed'));
273
        }
274
275
        return $this->render('SurfnetStepupRaRaBundle:RaManagement:changeRaRole.html.twig', [
276
            'raListing' => $raListing,
277
            'form'      => $form->createView()
278
        ]);
279
    }
280
281
    /**
282
     * @param Request $request
283
     * @param         $identityId
284
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
285
     */
286
    public function retractRegistrationAuthorityAction(Request $request, $identityId)
287
    {
288
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
289
        $logger = $this->get('logger');
290
291
        $logger->notice(sprintf("Loading retract registration authority form for RA(A) '%s'", $identityId));
292
293
        $raListing = $this->getRaListingService()->get($identityId);
294
        if (!$raListing) {
295
            $logger->warning(sprintf("RA listing for identity ID '%s' not found", $identityId));
296
            throw new NotFoundHttpException(sprintf("RA listing for identity ID '%s' not found", $identityId));
297
        }
298
299
        $command = new RetractRegistrationAuthorityCommand();
300
        $command->identityId = $identityId;
301
302
        $form = $this->createForm(RetractRegistrationAuthorityType::class, $command)->handleRequest($request);
303
        if ($form->isSubmitted() && $form->isValid()) {
304
            if ($form->get('cancel')->isClicked()) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Form\FormInterface as the method isClicked() does only exist in the following implementations of said interface: Symfony\Component\Form\SubmitButton.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
305
                $logger->notice('Retraction of registration authority cancelled');
306
                return $this->redirectToRoute('ra_management_manage');
307
            }
308
309
            $logger->notice(sprintf('Confirmed retraction of RA credentials for identity "%s"', $identityId));
310
311
            if ($this->get('ra.service.ra')->retractRegistrationAuthority($command)) {
312
                $logger->notice(sprintf('Registration authority for identity "%s" retracted', $identityId));
313
314
                $this->addFlash('success', $this->get('translator')->trans('ra.management.retract_ra.success'));
315
                return $this->redirectToRoute('ra_management_manage');
316
            }
317
318
            $logger->notice(sprintf(
319
                'Could not retract Registration Authority credentials for identity "%s"',
320
                $identityId
321
            ));
322
            $form->addError(new FormError('ra.management.retract_ra.middleware_command_failed'));
323
        }
324
325
        return $this->render('SurfnetStepupRaRaBundle:RaManagement:confirmRetractRa.html.twig', [
326
            'raListing' => $raListing,
327
            'form'      => $form->createView()
328
        ]);
329
    }
330
331
    /**
332
     * @return \Surfnet\StepupMiddlewareClientBundle\Identity\Service\RaListingService
333
     */
334
    private function getRaListingService()
335
    {
336
        return $this->get('surfnet_stepup_middleware_client.identity.service.ra_listing');
337
    }
338
339
    /**
340
     * @return \Surfnet\StepupRa\RaBundle\Service\RaCandidateService
341
     */
342
    private function getRaCandidateService()
343
    {
344
        return $this->get('ra.service.ra_candidate');
345
    }
346
347
    /**
348
     * @return \Knp\Component\Pager\Paginator
349
     */
350
    private function getPaginator()
351
    {
352
        return $this->get('knp_paginator');
353
    }
354
}
355