RaManagementController::createRaAction()   B
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 52

Duplication

Lines 18
Ratio 34.62 %

Importance

Changes 0
Metric Value
dl 18
loc 52
rs 8.7361
c 0
b 0
f 0
cc 5
nc 4
nop 1

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\StepupMiddlewareClientBundle\Identity\Dto\RaCandidateInstitution;
22
use Surfnet\StepupRa\RaBundle\Command\AccreditCandidateCommand;
23
use Surfnet\StepupRa\RaBundle\Command\AmendRegistrationAuthorityInformationCommand;
24
use Surfnet\StepupRa\RaBundle\Command\RetractRegistrationAuthorityCommand;
25
use Surfnet\StepupRa\RaBundle\Command\SearchRaCandidatesCommand;
26
use Surfnet\StepupRa\RaBundle\Command\SearchRaListingCommand;
27
use Surfnet\StepupRa\RaBundle\Form\Type\AmendRegistrationAuthorityInformationType;
28
use Surfnet\StepupRa\RaBundle\Form\Type\CreateRaType;
29
use Surfnet\StepupRa\RaBundle\Form\Type\RetractRegistrationAuthorityType;
30
use Surfnet\StepupRa\RaBundle\Form\Type\SearchRaCandidatesType;
31
use Surfnet\StepupRa\RaBundle\Form\Type\SearchRaListingType;
32
use Surfnet\StepupRa\RaBundle\Service\RaListingService;
33
use Surfnet\StepupRa\RaBundle\Value\RoleAtInstitution;
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
0 ignored issues
show
Deprecated Code introduced by
The class Symfony\Bundle\Framework...e\Controller\Controller has been deprecated with message: since Symfony 4.2, use "Symfony\Bundle\FrameworkBundle\Controller\AbstractController" instead.

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
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
        $identity = $this->getCurrentUser();
56
57
        $service = $this->getRaListingService();
58
59
        $command = new SearchRaListingCommand();
60
        $command->actorId = $identity->id;
61
        $command->pageNumber = (int) $request->get('p', 1);
62
        $command->orderBy = $request->get('orderBy');
63
        $command->orderDirection = $request->get('orderDirection');
64
65
        // The options that will populate the institution filter choice list.
66
        $raList = $service->search($command);
67
        $command->institutionFilterOptions = $raList->getFilterOption('institution');
68
        $command->raInstitutionFilterOptions = $raList->getFilterOption('raInstitution');
69
70
        $form = $this->createForm(SearchRaListingType::class, $command, ['method' => 'get']);
71
        $form->handleRequest($request);
72
73
        $raList = $service->search($command);
74
75
        $pagination = $this->getPaginator()->paginate(
76
            $raList->getTotalItems() > 0 ? $raList->getElements() : [],
77
            $raList->getCurrentPage(),
78
            $raList->getItemsPerPage()
79
        );
80
        $pagination->setTotalItemCount($raList->getTotalItems());
81
82
        $logger->notice(sprintf(
83
            'Searching for RA(A)s yielded "%d" results',
84
            $raList->getTotalItems()
85
        ));
86
87
        /** @var \Surfnet\StepupMiddlewareClientBundle\Identity\Dto\RaListing[] $raListings */
88
        $raListings = $raList->getElements();
89
90
        return $this->render(
91
            'SurfnetStepupRaRaBundle:ra_management:manage.html.twig',
92
            [
93
                'form' => $form->createView(),
94
                'raList' => $raListings,
95
                'numberOfResults' => $raList->getTotalItems(),
96
                'pagination' => $pagination,
97
            ]
98
        );
99
    }
100
101
    /**
102
     * @param Request $request
103
     * @return \Symfony\Component\HttpFoundation\Response
104
     */
105
    public function raCandidateSearchAction(Request $request)
106
    {
107
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
108
109
        $logger = $this->get('logger');
110
        $identity = $this->getCurrentUser();
111
        $institution = $identity->institution;
112
113
        $logger->notice(sprintf('Searching for RaCandidates within institution "%s"', $institution));
114
115
        $service = $this->getRaCandidateService();
116
117
        $command                   = new SearchRaCandidatesCommand();
118
        $command->actorId          = $identity->id;
119
        $command->actorInstitution = $institution;
0 ignored issues
show
Bug introduced by
The property actorInstitution does not seem to exist. Did you mean institution?

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...
120
        $command->raInstitution    = null;
121
        $command->pageNumber       = (int) $request->get('p', 1);
122
        $command->orderBy          = $request->get('orderBy');
123
        $command->orderDirection   = $request->get('orderDirection');
124
125
        $raCandidateList = $service->search($command);
126
127
        // The options that will populate the institution filter choice list.
128
        $command->institutionFilterOptions = $raCandidateList->getFilterOption('institution');
129
130
        $form = $this->createForm(SearchRaCandidatesType::class, $command, ['method' => 'get']);
131
        $form->handleRequest($request);
132
133
        $raCandidateList = $service->search($command);
134
135
        $pagination = $this->getPaginator()->paginate(
136
            $raCandidateList->getTotalItems() > 0 ? $raCandidateList->getElements() : [],
137
            $raCandidateList->getCurrentPage(),
138
            $raCandidateList->getItemsPerPage()
139
        );
140
        $pagination->setTotalItemCount($raCandidateList->getTotalItems());
141
142
        $logger->notice(sprintf(
143
            'Searching for RaCandidates within institution "%s" yielded "%s" results',
144
            $institution,
145
            $raCandidateList->getTotalItems()
146
        ));
147
148
        return $this->render(
149
            'SurfnetStepupRaRaBundle:ra_management:ra_candidate_overview.html.twig',
150
            [
151
                'form'         => $form->createView(),
152
                'raCandidates' => $raCandidateList,
153
                'pagination'   => $pagination
154
            ]
155
        );
156
    }
157
158
    /**
159
     * @param Request $request
160
     * @return \Symfony\Component\HttpFoundation\Response
161
     */
162
    public function createRaAction(Request $request)
163
    {
164
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
165
        $logger = $this->get('logger');
166
167
        $logger->notice('Page for Accreditation of Identity to Ra or Raa requested');
168
        $identityId = $request->get('identityId');
169
170
        $raCandidate = $this->getRaCandidateService()->getRaCandidate($identityId, $this->getUser()->id);
171
172
        if (!$raCandidate->raCandidate) {
173
            $logger->warning(sprintf('RaCandidate based on identity "%s" not found', $identityId));
174
            throw new NotFoundHttpException();
175
        }
176
177
        $options = array_map(function (RaCandidateInstitution $institution) {
178
            return $institution->institution;
179
        }, $raCandidate->institutions->getElements());
180
        $selectOptions = array_combine($options, $options);
181
182
        $command = new AccreditCandidateCommand();
183
        $command->identityId = $identityId;
184
        $command->institution = $raCandidate->raCandidate->institution;
185
        $command->roleAtInstitution = new RoleAtInstitution();
186
        $command->roleAtInstitution->setInstitution($this->getUser()->institution);
187
        $command->availableInstitutions = $selectOptions;
188
189
        $form = $this->createForm(CreateRaType::class, $command)->handleRequest($request);
190 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...
191
            $logger->debug('Accreditation form submitted, start processing command');
192
193
            $success = $this->getRaCandidateService()->accreditCandidate($command);
194
195
            if ($success) {
196
                $this->addFlash(
197
                    'success',
198
                    $this->get('translator')->trans('ra.management.create_ra.identity_accredited')
199
                );
200
201
                $logger->debug('Identity Accredited, redirecting to candidate overview');
202
                return $this->redirectToRoute('ra_management_ra_candidate_search');
203
            }
204
205
            $logger->debug('Identity Accreditation failed, adding error to form');
206
            $this->addFlash('error', 'ra.management.create_ra.error.middleware_command_failed');
207
        }
208
209
        return $this->render('SurfnetStepupRaRaBundle:ra_management:create_ra.html.twig', [
210
            'raCandidate' => $raCandidate->raCandidate,
211
            'form'        => $form->createView()
212
        ]);
213
    }
214
215
    /**
216
     * @param Request $request
217
     * @param         $identityId
218
     * @param         $raInstitution
219
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
220
     */
221
    public function amendRaInformationAction(Request $request, $identityId, $raInstitution)
222
    {
223
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
224
225
        $logger = $this->get('logger');
226
        $logger->notice(sprintf("Loading information amendment form for RA(A) '%s'", $identityId));
227
228
        $raListing = $this->getRaListingService()->get($identityId, $raInstitution, $this->getUser()->id);
229
230 View Code Duplication
        if (!$raListing) {
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...
231
            $logger->warning(sprintf("RA listing for identity ID '%s' not found", $identityId));
232
            throw new NotFoundHttpException(sprintf("RA listing for identity ID '%s' not found", $identityId));
233
        }
234
235
        $command = new AmendRegistrationAuthorityInformationCommand();
236
        $command->identityId = $raListing->identityId;
237
        $command->location = $raListing->location;
238
        $command->contactInformation = $raListing->contactInformation;
239
        $command->institution = $raListing->raInstitution;
240
241
        $form = $this->createForm(AmendRegistrationAuthorityInformationType::class, $command)->handleRequest($request);
242
        if ($form->isSubmitted() && $form->isValid()) {
243
            $logger->notice(sprintf("RA(A) '%s' information amendment form submitted, processing", $identityId));
244
245 View Code Duplication
            if ($this->get('ra.service.ra')->amendRegistrationAuthorityInformation($command)) {
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...
246
                $this->addFlash('success', $this->get('translator')->trans('ra.management.amend_ra_info.info_amended'));
247
248
                $logger->notice(sprintf("RA(A) '%s' information successfully amended", $identityId));
249
                return $this->redirectToRoute('ra_management_manage');
250
            }
251
252
            $logger->notice(sprintf("Information of RA(A) '%s' failed to be amended, informing user", $identityId));
253
            $this->addFlash('error', 'ra.management.amend_ra_info.error.middleware_command_failed');
254
        }
255
256
        return $this->render('SurfnetStepupRaRaBundle:ra_management:amend_ra_information.html.twig', [
257
            'raListing' => $raListing,
258
            'form' => $form->createView(),
259
        ]);
260
    }
261
262
    /**
263
     * @param Request $request
264
     * @param         $identityId
265
     * @param         $raInstitution
266
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
267
     */
268
    public function retractRegistrationAuthorityAction(Request $request, $identityId, $raInstitution)
269
    {
270
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
271
        $logger = $this->get('logger');
272
273
        $logger->notice(sprintf("Loading retract registration authority form for RA(A) '%s'", $identityId));
274
275
        $raListing = $this->getRaListingService()->get($identityId, $raInstitution, $this->getUser()->id);
276 View Code Duplication
        if (!$raListing) {
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...
277
            $logger->warning(sprintf("RA listing for identity ID '%s@%s' not found", $identityId, $this->getUser()->institution));
278
            throw new NotFoundHttpException(sprintf("RA listing for identity ID '%s' not found", $identityId));
279
        }
280
281
        $command = new RetractRegistrationAuthorityCommand();
282
        $command->identityId = $identityId;
283
        $command->institution = $raListing->raInstitution;
284
285
        $form = $this->createForm(RetractRegistrationAuthorityType::class, $command)->handleRequest($request);
286
        if ($form->isSubmitted() && $form->isValid()) {
287
            if ($form->get('button-group')->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...
288
                $logger->notice('Retraction of registration authority cancelled');
289
                return $this->redirectToRoute('ra_management_manage');
290
            }
291
292
            $logger->notice(sprintf('Confirmed retraction of RA credentials for identity "%s"', $identityId));
293
294 View Code Duplication
            if ($this->get('ra.service.ra')->retractRegistrationAuthority($command)) {
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...
295
                $logger->notice(sprintf('Registration authority for identity "%s" retracted', $identityId));
296
297
                $this->addFlash('success', $this->get('translator')->trans('ra.management.retract_ra.success'));
298
                return $this->redirectToRoute('ra_management_manage');
299
            }
300
301
            $logger->notice(sprintf(
302
                'Could not retract Registration Authority credentials for identity "%s"',
303
                $identityId
304
            ));
305
            $this->addFlash('error', 'ra.management.retract_ra.middleware_command_failed');
306
        }
307
308
        return $this->render('SurfnetStepupRaRaBundle:ra_management:confirm_retract_ra.html.twig', [
309
            'raListing' => $raListing,
310
            'form'      => $form->createView()
311
        ]);
312
    }
313
314
    /**
315
     * @return RaListingService
316
     */
317
    private function getRaListingService()
318
    {
319
        return $this->get('ra.service.ra_listing');
320
    }
321
322
    /**
323
     * @return \Surfnet\StepupRa\RaBundle\Service\RaCandidateService
324
     */
325
    private function getRaCandidateService()
326
    {
327
        return $this->get('ra.service.ra_candidate');
328
    }
329
330
    /**
331
     * @return \Surfnet\StepupMiddlewareClientBundle\Identity\Dto\Identity
332
     */
333
    private function getCurrentUser()
334
    {
335
        return $this->get('security.token_storage')->getToken()->getUser();
336
    }
337
338
    /**
339
     * @return \Knp\Component\Pager\Paginator
340
     */
341
    private function getPaginator()
342
    {
343
        return $this->get('knp_paginator');
344
    }
345
}
346