Completed
Push — feature/composer-update ( dfcd50 )
by Boy
13:58
created

RaManagementController   C

Complexity

Total Complexity 25

Size/Duplication

Total Lines 316
Duplicated Lines 24.37 %

Coupling/Cohesion

Components 1
Dependencies 19

Importance

Changes 14
Bugs 1 Features 9
Metric Value
wmc 25
c 14
b 1
f 9
lcom 1
cbo 19
dl 77
loc 316
rs 6.875

9 Methods

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

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 Symfony\Bundle\FrameworkBundle\Controller\Controller;
28
use Symfony\Component\Form\FormError;
29
use Symfony\Component\HttpFoundation\Request;
30
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
31
32
/**
33
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
34
 */
35
class RaManagementController extends Controller
36
{
37
    /**
38
     * @param Request $request
39
     * @return \Symfony\Component\HttpFoundation\Response
40
     */
41
    public function manageAction(Request $request)
42
    {
43
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
44
45
        $logger = $this->get('logger');
46
        $institution = $this->getUser()->institution;
47
48
        $logger->notice(sprintf('Loading overview of RA(A)s for institution "%s"', $institution));
49
50
        $searchQuery = (new RaListingSearchQuery($this->getUser()->institution, 1))
51
            ->setOrderBy($request->get('orderBy', 'commonName'))
52
            ->setOrderDirection($request->get('orderDirection', 'asc'));
53
54
        $service = $this->getRaListingService();
55
        $raList = $service->search($searchQuery);
56
57
        $pagination = $this->getPaginator()->paginate(
58
            $raList->getTotalItems() > 0 ? array_fill(0, $raList->getTotalItems(), 1) : [],
59
            $raList->getCurrentPage(),
60
            $raList->getItemsPerPage()
61
        );
62
63
        $logger->notice(sprintf(
64
            'Created overview of "%d" RA(A)s for institution "%s"',
65
            $raList->getTotalItems(),
66
            $institution
67
        ));
68
69
        /** @var \Surfnet\StepupMiddlewareClientBundle\Identity\Dto\RaListing[] $raListings */
70
        $raListings = $raList->getElements();
71
72
        return $this->render(
73
            'SurfnetStepupRaRaBundle:RaManagement:manage.html.twig',
74
            [
75
                'raList'     => $raListings,
76
                'pagination' => $pagination
77
            ]
78
        );
79
    }
80
81
    /**
82
     * @param Request $request
83
     * @return \Symfony\Component\HttpFoundation\Response
84
     */
85
    public function raCandidateSearchAction(Request $request)
86
    {
87
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
88
89
        $logger = $this->get('logger');
90
        $institution = $this->getUser()->institution;
91
92
        $logger->notice(sprintf('Searching for RaCandidates within institution "%s"', $institution));
93
94
        $command                 = new SearchRaCandidatesCommand();
95
        $command->institution    = $institution;
96
        $command->pageNumber     = $request->get('p', 1);
97
        $command->orderBy        = $request->get('orderBy');
98
        $command->orderDirection = $request->get('orderDirection');
99
100
        $form = $this->createForm('ra_search_ra_candidates', $command, ['method' => 'get']);
101
        $form->handleRequest($request);
102
103
        $service = $this->getRaCandidateService();
104
        $raCandidateList = $service->search($command);
105
106
        $pagination = $this->getPaginator()->paginate(
107
            $raCandidateList->getTotalItems() > 0 ? array_fill(4, $raCandidateList->getTotalItems(), 1) : [],
108
            $raCandidateList->getCurrentPage(),
109
            $raCandidateList->getItemsPerPage()
110
        );
111
112
        $logger->notice(sprintf(
113
            'Searching for RaCandidates within institution "%s" yielded "%s" results',
114
            $institution,
115
            $raCandidateList->getTotalItems()
116
        ));
117
118
        return $this->render(
119
            'SurfnetStepupRaRaBundle:RaManagement:raCandidateOverview.html.twig',
120
            [
121
                'form'         => $form->createView(),
122
                'raCandidates' => $raCandidateList,
123
                'pagination'   => $pagination
124
            ]
125
        );
126
    }
127
128
    /**
129
     * @param Request $request
130
     * @return \Symfony\Component\HttpFoundation\Response
131
     */
132
    public function createRaAction(Request $request)
133
    {
134
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
135
        $logger = $this->get('logger');
136
137
        $logger->notice('Page for Accreditation of Identity to Ra or Raa requested');
138
        $identityId = $request->get('identityId');
139
        $raCandidate = $this->getRaCandidateService()->getRaCandidateByIdentityId($identityId);
140
141
        if (!$raCandidate) {
142
            $logger->warning(sprintf('RaCandidate based on identity "%s" not found', $identityId));
143
            throw new NotFoundHttpException();
144
        }
145
146
        if ($raCandidate->institution !== $this->getUser()->institution) {
147
            $user = $this->getUser();
148
            $logger->warning(sprintf(
149
                'Identity "%s" of "%s" illegally tried to accredit tried to accredit Identity "%s" of "%s"',
150
                $user->id,
151
                $user->institution,
152
                $raCandidate->identityId,
153
                $raCandidate->institution
154
            ));
155
            throw $this->createAccessDeniedException();
156
        }
157
158
        $command              = new AccreditCandidateCommand();
159
        $command->identityId  = $identityId;
160
        $command->institution = $raCandidate->institution;
161
162
        $form = $this->createForm('ra_management_create_ra', $command)->handleRequest($request);
163
        if ($form->isValid()) {
164
            $logger->debug('Accreditation form submitted, start processing command');
165
166
            $success = $this->getRaCandidateService()->accreditCandidate($command);
167
168
            if ($success) {
169
                $this->addFlash(
170
                    'success',
171
                    $this->get('translator')->trans('ra.management.create_ra.identity_accredited')
172
                );
173
174
                $logger->debug('Identity Accredited, redirecting to candidate overview');
175
                return $this->redirectToRoute('ra_management_ra_candidate_search');
176
            }
177
178
            $logger->debug('Identity Accreditation failed, adding error to form');
179
            $form->addError(new FormError('ra.management.create_ra.error.middleware_command_failed'));
180
        }
181
182
        return $this->render('SurfnetStepupRaRaBundle:RaManagement:createRa.html.twig', [
183
            'raCandidate' => $raCandidate,
184
            'form'        => $form->createView()
185
        ]);
186
    }
187
188
    /**
189
     * @param Request $request
190
     * @param         $identityId
191
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
192
     */
193 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...
194
    {
195
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
196
197
        $logger = $this->get('logger');
198
        $logger->notice(sprintf("Loading information amendment form for RA(A) '%s'", $identityId));
199
200
        $raListing = $this->getRaListingService()->get($identityId);
201
202
        if (!$raListing) {
203
            $logger->warning(sprintf("RA listing for identity ID '%s' not found", $identityId));
204
            throw new NotFoundHttpException(sprintf("RA listing for identity ID '%s' not found", $identityId));
205
        }
206
207
        $command = new AmendRegistrationAuthorityInformationCommand();
208
        $command->identityId = $raListing->identityId;
209
        $command->location = $raListing->location;
210
        $command->contactInformation = $raListing->contactInformation;
211
212
        $form = $this->createForm('ra_management_amend_ra_info', $command)->handleRequest($request);
213
        if ($form->isValid()) {
214
            $logger->notice(sprintf("RA(A) '%s' information amendment form submitted, processing", $identityId));
215
216
            if ($this->get('ra.service.ra')->amendRegistrationAuthorityInformation($command)) {
217
                $this->addFlash('success', $this->get('translator')->trans('ra.management.amend_ra_info.info_amended'));
218
219
                $logger->notice(sprintf("RA(A) '%s' information successfully amended", $identityId));
220
                return $this->redirectToRoute('ra_management_manage');
221
            }
222
223
            $logger->notice(sprintf("Information of RA(A) '%s' failed to be amended, informing user", $identityId));
224
            $form->addError(new FormError('ra.management.amend_ra_info.error.middleware_command_failed'));
225
        }
226
227
        return $this->render('SurfnetStepupRaRaBundle:RaManagement:amendRaInformation.html.twig', [
228
            'raListing' => $raListing,
229
            'form' => $form->createView(),
230
        ]);
231
    }
232
233
    /**
234
     * @param Request $request
235
     * @param         $identityId
236
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
237
     */
238 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...
239
    {
240
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
241
        $logger = $this->get('logger');
242
243
        $logger->notice(sprintf("Loading change Ra Role form for RA(A) '%s'", $identityId));
244
245
        $raListing = $this->getRaListingService()->get($identityId);
246
        if (!$raListing) {
247
            $logger->warning(sprintf("RA listing for identity ID '%s' not found", $identityId));
248
            throw new NotFoundHttpException(sprintf("RA listing for identity ID '%s' not found", $identityId));
249
        }
250
251
        $command              = new ChangeRaRoleCommand();
252
        $command->identityId  = $raListing->identityId;
253
        $command->institution = $raListing->institution;
254
        $command->role        = $raListing->role;
255
256
        $form = $this->createForm('ra_management_change_ra_role', $command)->handleRequest($request);
257
        if ($form->isValid()) {
258
            $logger->notice(sprintf('RA(A) "%s" Change Role form submitted, processing', $identityId));
259
260
            if ($this->get('ra.service.ra')->changeRegistrationAuthorityRole($command)) {
261
                $logger->notice('Role successfully changed');
262
263
                $this->addFlash('success', $this->get('translator')->trans('ra.management.change_ra_role_changed'));
264
                return $this->redirectToRoute('ra_management_manage');
265
            }
266
267
            $logger->notice(sprintf('Role of RA(A) "%s" could not be changed, informing user', $identityId));
268
            $form->addError(new FormError('ra.management.change_ra_role.middleware_command_failed'));
269
        }
270
271
        return $this->render('SurfnetStepupRaRaBundle:RaManagement:changeRaRole.html.twig', [
272
            'raListing' => $raListing,
273
            'form'      => $form->createView()
274
        ]);
275
    }
276
277
    /**
278
     * @param Request $request
279
     * @param         $identityId
280
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
281
     */
282
    public function retractRegistrationAuthorityAction(Request $request, $identityId)
283
    {
284
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
285
        $logger = $this->get('logger');
286
287
        $logger->notice(sprintf("Loading retract registration authority form for RA(A) '%s'", $identityId));
288
289
        $raListing = $this->getRaListingService()->get($identityId);
290
        if (!$raListing) {
291
            $logger->warning(sprintf("RA listing for identity ID '%s' not found", $identityId));
292
            throw new NotFoundHttpException(sprintf("RA listing for identity ID '%s' not found", $identityId));
293
        }
294
295
        $command = new RetractRegistrationAuthorityCommand();
296
        $command->identityId = $identityId;
297
298
        $form = $this->createForm('ra_management_retract_registration_authority', $command)->handleRequest($request);
299
        if ($form->isValid()) {
300
            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...
301
                $logger->notice('Retraction of registration authority cancelled');
302
                return $this->redirectToRoute('ra_management_manage');
303
            }
304
305
            $logger->notice(sprintf('Confirmed retraction of RA credentials for identity "%s"', $identityId));
306
307
            if ($this->get('ra.service.ra')->retractRegistrationAuthority($command)) {
308
                $logger->notice(sprintf('Registration authority for identity "%s" retracted', $identityId));
309
310
                $this->addFlash('success', $this->get('translator')->trans('ra.management.retract_ra.success'));
311
                return $this->redirectToRoute('ra_management_manage');
312
            }
313
314
            $logger->notice(sprintf(
315
                'Could not retract Registration Authority credentials for identity "%s"',
316
                $identityId
317
            ));
318
            $form->addError(new FormError('ra.management.retract_ra.middleware_command_failed'));
319
        }
320
321
        return $this->render('SurfnetStepupRaRaBundle:RaManagement:confirmRetractRa.html.twig', [
322
            'raListing' => $raListing,
323
            'form'      => $form->createView()
324
        ]);
325
    }
326
327
    /**
328
     * @return \Surfnet\StepupMiddlewareClientBundle\Identity\Service\RaListingService
329
     */
330
    private function getRaListingService()
331
    {
332
        return $this->get('surfnet_stepup_middleware_client.identity.service.ra_listing');
333
    }
334
335
    /**
336
     * @return \Surfnet\StepupRa\RaBundle\Service\RaCandidateService
337
     */
338
    private function getRaCandidateService()
339
    {
340
        return $this->get('ra.service.ra_candidate');
341
    }
342
343
    /**
344
     * @return \Knp\Component\Pager\Paginator
345
     */
346
    private function getPaginator()
347
    {
348
        return $this->get('knp_paginator');
349
    }
350
}
351