Completed
Pull Request — develop (#179)
by
unknown
62:01 queued 45:04
created

RaManagementController::changeRaRoleAction()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 39

Duplication

Lines 0
Ratio 0 %

Importance

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