Completed
Push — develop ( b9b24c...1466e6 )
by Michiel
02:02
created

RaManagementController   A

Complexity

Total Complexity 29

Size/Duplication

Total Lines 316
Duplicated Lines 30.06 %

Coupling/Cohesion

Components 1
Dependencies 18

Importance

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