Completed
Push — feature/remove-old-raa-switche... ( e62d75 )
by Michiel
12:23
created

RaManagementController   A

Complexity

Total Complexity 30

Size/Duplication

Total Lines 336
Duplicated Lines 5.36 %

Coupling/Cohesion

Components 1
Dependencies 13

Importance

Changes 0
Metric Value
wmc 30
lcom 1
cbo 13
dl 18
loc 336
c 0
b 0
f 0
rs 10

11 Methods

Rating   Name   Duplication   Size   Complexity  
A manageAction() 0 39 2
A raCandidateSearchAction() 0 43 2
B createRaAction() 18 54 5
B amendRaInformationAction() 0 41 5
B changeRaRoleAction() 0 39 5
B retractRegistrationAuthorityAction() 0 45 6
A getRaListingService() 0 4 1
A getRaCandidateService() 0 4 1
A getInstitutionConfigurationOptionsService() 0 4 1
A getPaginator() 0 4 1
A getRaManagementInstitution() 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 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\CreateRaType;
30
use Surfnet\StepupRa\RaBundle\Form\Type\RetractRegistrationAuthorityType;
31
use Surfnet\StepupRa\RaBundle\Form\Type\SearchRaCandidatesType;
32
use Surfnet\StepupRa\RaBundle\Security\Authentication\Token\SamlToken;
33
use Surfnet\StepupRa\RaBundle\Service\InstitutionConfigurationOptionsService;
34
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
35
use Symfony\Component\HttpFoundation\Request;
36
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
37
38
/**
39
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
40
 */
41
class RaManagementController extends Controller
42
{
43
    /**
44
     * @param Request $request
45
     * @return \Symfony\Component\HttpFoundation\Response
46
     */
47
    public function manageAction(Request $request)
48
    {
49
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
50
51
        $logger = $this->get('logger');
52
        $institution = $this->getUser()->institution;
53
        $logger->notice(sprintf('Loading overview of RA(A)s for institution "%s"', $institution));
54
55
        $searchQuery = (new RaListingSearchQuery($this->getUser()->institution, 1))
56
            ->setInstitution($this->getRaManagementInstitution())
57
            ->setOrderBy($request->get('orderBy', 'commonName'))
58
            ->setOrderDirection($request->get('orderDirection', 'asc'));
59
60
        $service = $this->getRaListingService();
61
        $raList = $service->search($searchQuery);
62
63
        $pagination = $this->getPaginator()->paginate(
64
            $raList->getTotalItems() > 0 ? array_fill(0, $raList->getTotalItems(), 1) : [],
65
            $raList->getCurrentPage(),
66
            $raList->getItemsPerPage()
67
        );
68
69
        $logger->notice(sprintf(
70
            'Created overview of "%d" RA(A)s for institution "%s"',
71
            $raList->getTotalItems(),
72
            $institution
73
        ));
74
75
        /** @var \Surfnet\StepupMiddlewareClientBundle\Identity\Dto\RaListing[] $raListings */
76
        $raListings = $raList->getElements();
77
78
        return $this->render(
79
            'SurfnetStepupRaRaBundle:RaManagement:manage.html.twig',
80
            [
81
                'raList'     => $raListings,
82
                'pagination' => $pagination
83
            ]
84
        );
85
    }
86
87
    /**
88
     * @param Request $request
89
     * @return \Symfony\Component\HttpFoundation\Response
90
     */
91
    public function raCandidateSearchAction(Request $request)
92
    {
93
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
94
95
        $logger = $this->get('logger');
96
        $institution = $this->getUser()->institution;
97
98
        $logger->notice(sprintf('Searching for RaCandidates within institution "%s"', $institution));
99
100
        $command                   = new SearchRaCandidatesCommand();
101
        $command->actorInstitution = $institution;
102
        $command->institution      = $this->getRaManagementInstitution();
103
        $command->pageNumber       = (int) $request->get('p', 1);
104
        $command->orderBy          = $request->get('orderBy');
105
        $command->orderDirection   = $request->get('orderDirection');
106
107
        $form = $this->createForm(SearchRaCandidatesType::class, $command, ['method' => 'get']);
108
        $form->handleRequest($request);
109
110
        $service = $this->getRaCandidateService();
111
        $raCandidateList = $service->search($command);
112
113
        $pagination = $this->getPaginator()->paginate(
114
            $raCandidateList->getTotalItems() > 0 ? array_fill(4, $raCandidateList->getTotalItems(), 1) : [],
115
            $raCandidateList->getCurrentPage(),
116
            $raCandidateList->getItemsPerPage()
117
        );
118
119
        $logger->notice(sprintf(
120
            'Searching for RaCandidates within institution "%s" yielded "%s" results',
121
            $institution,
122
            $raCandidateList->getTotalItems()
123
        ));
124
125
        return $this->render(
126
            'SurfnetStepupRaRaBundle:RaManagement:raCandidateOverview.html.twig',
127
            [
128
                'form'         => $form->createView(),
129
                'raCandidates' => $raCandidateList,
130
                'pagination'   => $pagination
131
            ]
132
        );
133
    }
134
135
    /**
136
     * @param Request $request
137
     * @return \Symfony\Component\HttpFoundation\Response
138
     */
139
    public function createRaAction(Request $request)
140
    {
141
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
142
        $logger = $this->get('logger');
143
144
        $logger->notice('Page for Accreditation of Identity to Ra or Raa requested');
145
        $identityId = $request->get('identityId');
146
        $raCandidate = $this->getRaCandidateService()->getRaCandidate($identityId, $this->getRaManagementInstitution());
147
148
        if (!$raCandidate) {
149
            $logger->warning(sprintf('RaCandidate based on identity "%s" not found', $identityId));
150
            throw new NotFoundHttpException();
151
        }
152
153
        /**
154
         * @var SamlToken $token
155
         */
156
        $token  = $this->get('security.token_storage')->getToken();
157
        $raaSwitcherOptions = $this
158
            ->getInstitutionConfigurationOptionsService()
159
            ->getAvailableInstitutionsFor($token->getIdentityInstitution());
160
161
        $command                   = new AccreditCandidateCommand();
162
        $command->identityId       = $identityId;
163
        $command->institution      = $this->getRaManagementInstitution();
164
        $command->raInstitution    = $this->getUser()->institution;
165
        $command->availableInstitutions = $raaSwitcherOptions;
166
167
        // todo: make choicelist configurable
168
        $form = $this->createForm(CreateRaType::class, $command)->handleRequest($request);
169 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...
170
            $logger->debug('Accreditation form submitted, start processing command');
171
172
            $success = $this->getRaCandidateService()->accreditCandidate($command);
173
174
            if ($success) {
175
                $this->addFlash(
176
                    'success',
177
                    $this->get('translator')->trans('ra.management.create_ra.identity_accredited')
178
                );
179
180
                $logger->debug('Identity Accredited, redirecting to candidate overview');
181
                return $this->redirectToRoute('ra_management_ra_candidate_search');
182
            }
183
184
            $logger->debug('Identity Accreditation failed, adding error to form');
185
            $this->addFlash('error', 'ra.management.create_ra.error.middleware_command_failed');
186
        }
187
188
        return $this->render('SurfnetStepupRaRaBundle:RaManagement:createRa.html.twig', [
189
            'raCandidate' => $raCandidate,
190
            'form'        => $form->createView()
191
        ]);
192
    }
193
194
    /**
195
     * @param Request $request
196
     * @param         $identityId
197
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
198
     */
199
    public function amendRaInformationAction(Request $request, $identityId)
200
    {
201
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
202
203
        $logger = $this->get('logger');
204
        $logger->notice(sprintf("Loading information amendment form for RA(A) '%s'", $identityId));
205
206
        $raListing = $this->getRaListingService()->get($identityId, $this->getUser()->institution);
207
208
        if (!$raListing) {
209
            $logger->warning(sprintf("RA listing for identity ID '%s' not found", $identityId));
210
            throw new NotFoundHttpException(sprintf("RA listing for identity ID '%s' not found", $identityId));
211
        }
212
213
        $command = new AmendRegistrationAuthorityInformationCommand();
214
        $command->identityId = $raListing->identityId;
215
        $command->location = $this->getUser()->institution;
216
        $command->contactInformation = $raListing->contactInformation;
217
        // todo: institution
218
        $command->institution = $raListing->institution;
0 ignored issues
show
Bug introduced by
The property institution does not seem to exist in Surfnet\StepupRa\RaBundl...orityInformationCommand.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
219
220
        $form = $this->createForm(AmendRegistrationAuthorityInformationType::class, $command)->handleRequest($request);
221
        if ($form->isSubmitted() && $form->isValid()) {
222
            $logger->notice(sprintf("RA(A) '%s' information amendment form submitted, processing", $identityId));
223
224
            if ($this->get('ra.service.ra')->amendRegistrationAuthorityInformation($command)) {
225
                $this->addFlash('success', $this->get('translator')->trans('ra.management.amend_ra_info.info_amended'));
226
227
                $logger->notice(sprintf("RA(A) '%s' information successfully amended", $identityId));
228
                return $this->redirectToRoute('ra_management_manage');
229
            }
230
231
            $logger->notice(sprintf("Information of RA(A) '%s' failed to be amended, informing user", $identityId));
232
            $this->addFlash('error', 'ra.management.amend_ra_info.error.middleware_command_failed');
233
        }
234
235
        return $this->render('SurfnetStepupRaRaBundle:RaManagement:amendRaInformation.html.twig', [
236
            'raListing' => $raListing,
237
            'form' => $form->createView(),
238
        ]);
239
    }
240
241
    /**
242
     * @param Request $request
243
     * @param         $identityId
244
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
245
     */
246
    public function changeRaRoleAction(Request $request, $identityId)
247
    {
248
        // todo: remove?
249
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
250
        $logger = $this->get('logger');
251
252
        $logger->notice(sprintf("Loading change Ra Role form for RA(A) '%s'", $identityId));
253
254
        $raListing = $this->getRaListingService()->get($identityId, $this->getUser()->institution);
255
        if (!$raListing) {
256
            $logger->warning(sprintf("RA listing for identity ID '%s' not found", $identityId));
257
            throw new NotFoundHttpException(sprintf("RA listing for identity ID '%s' not found", $identityId));
258
        }
259
260
        $command              = new ChangeRaRoleCommand();
261
        $command->identityId  = $raListing->identityId;
262
        $command->institution = $this->getUser()->institution;
263
        $command->role        = $raListing->role;
264
265
        $form = $this->createForm(ChangeRaRoleType::class, $command)->handleRequest($request);
266
        if ($form->isSubmitted() && $form->isValid()) {
267
            $logger->notice(sprintf('RA(A) "%s" Change Role form submitted, processing', $identityId));
268
269
            if ($this->get('ra.service.ra')->changeRegistrationAuthorityRole($command)) {
270
                $logger->notice('Role successfully changed');
271
272
                $this->addFlash('success', $this->get('translator')->trans('ra.management.change_ra_role_changed'));
273
                return $this->redirectToRoute('ra_management_manage');
274
            }
275
276
            $logger->notice(sprintf('Role of RA(A) "%s" could not be changed, informing user', $identityId));
277
            $this->addFlash('error', 'ra.management.change_ra_role.middleware_command_failed');
278
        }
279
280
        return $this->render('SurfnetStepupRaRaBundle:RaManagement:changeRaRole.html.twig', [
281
            'raListing' => $raListing,
282
            'form'      => $form->createView()
283
        ]);
284
    }
285
286
    /**
287
     * @param Request $request
288
     * @param         $identityId
289
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
290
     */
291
    public function retractRegistrationAuthorityAction(Request $request, $identityId)
292
    {
293
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
294
        $logger = $this->get('logger');
295
296
        $logger->notice(sprintf("Loading retract registration authority form for RA(A) '%s'", $identityId));
297
298
        $raListing = $this->getRaListingService()->get($identityId, $this->getUser()->institution);
299
        if (!$raListing) {
300
            $logger->warning(sprintf("RA listing for identity ID '%s' not found", $identityId));
301
            throw new NotFoundHttpException(sprintf("RA listing for identity ID '%s' not found", $identityId));
302
        }
303
304
        $command = new RetractRegistrationAuthorityCommand();
305
        $command->identityId = $identityId;
306
        $command->institution = $this->getUser()->institution;
307
308
        $form = $this->createForm(RetractRegistrationAuthorityType::class, $command)->handleRequest($request);
309
        if ($form->isSubmitted() && $form->isValid()) {
310
            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...
311
                $logger->notice('Retraction of registration authority cancelled');
312
                return $this->redirectToRoute('ra_management_manage');
313
            }
314
315
            $logger->notice(sprintf('Confirmed retraction of RA credentials for identity "%s"', $identityId));
316
317
            if ($this->get('ra.service.ra')->retractRegistrationAuthority($command)) {
318
                $logger->notice(sprintf('Registration authority for identity "%s" retracted', $identityId));
319
320
                $this->addFlash('success', $this->get('translator')->trans('ra.management.retract_ra.success'));
321
                return $this->redirectToRoute('ra_management_manage');
322
            }
323
324
            $logger->notice(sprintf(
325
                'Could not retract Registration Authority credentials for identity "%s"',
326
                $identityId
327
            ));
328
            $this->addFlash('error', 'ra.management.retract_ra.middleware_command_failed');
329
        }
330
331
        return $this->render('SurfnetStepupRaRaBundle:RaManagement:confirmRetractRa.html.twig', [
332
            'raListing' => $raListing,
333
            'form'      => $form->createView()
334
        ]);
335
    }
336
337
    /**
338
     * @return \Surfnet\StepupMiddlewareClientBundle\Identity\Service\RaListingService
339
     */
340
    private function getRaListingService()
341
    {
342
        return $this->get('surfnet_stepup_middleware_client.identity.service.ra_listing');
343
    }
344
345
    /**
346
     * @return \Surfnet\StepupRa\RaBundle\Service\RaCandidateService
347
     */
348
    private function getRaCandidateService()
349
    {
350
        return $this->get('ra.service.ra_candidate');
351
    }
352
353
    /**
354
     * @return InstitutionConfigurationOptionsService
355
     */
356
    private function getInstitutionConfigurationOptionsService()
357
    {
358
        return $this->get('ra.service.institution_configuration_options');
359
    }
360
361
    /**
362
     * @return \Knp\Component\Pager\Paginator
363
     */
364
    private function getPaginator()
365
    {
366
        return $this->get('knp_paginator');
367
    }
368
369
    /**
370
     * @return string
371
     */
372
    private function getRaManagementInstitution()
373
    {
374
        return $this->getUser()->institution;
375
    }
376
}
377