Completed
Pull Request — develop (#302)
by Michiel
04:10 queued 02:06
created

execute()   C

Complexity

Conditions 9
Paths 120

Size

Total Lines 90

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 90
rs 6.5292
c 0
b 0
f 0
cc 9
nc 120
nop 2

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 2020 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\StepupMiddleware\MiddlewareBundle\Console\Command;
20
21
use Exception;
22
use Rhumsaa\Uuid\Uuid;
23
use Surfnet\Stepup\Identity\Value\Institution;
24
use Surfnet\Stepup\Identity\Value\NameId;
25
use Surfnet\StepupMiddleware\ApiBundle\Identity\Entity\UnverifiedSecondFactor;
26
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\CreateIdentityCommand;
27
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\ProvePhonePossessionCommand;
28
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\VerifyEmailCommand;
29
use Symfony\Component\Console\Input\InputArgument;
30
use Symfony\Component\Console\Input\InputInterface;
31
use Symfony\Component\Console\Output\OutputInterface;
32
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
33
34
/**
35
 * @SuppressWarnings(PHPMD.ExcessiveClassLength)
36
 */
37
final class BootstrapIdentityWithSmsSecondFactorCommand extends AbstractBootstrapCommand
38
{
39
    protected function configure()
40
    {
41
        $this
42
            ->setDescription('Creates an identity with a SMS second factor')
43
            ->addArgument('name-id', InputArgument::REQUIRED, 'The NameID of the identity to create')
44
            ->addArgument('institution', InputArgument::REQUIRED, 'The institution of the identity to create')
45
            ->addArgument('common-name', InputArgument::REQUIRED, 'The Common Name of the identity to create')
46
            ->addArgument('email', InputArgument::REQUIRED, 'The e-mail address of the identity to create')
47
            ->addArgument('preferred-locale', InputArgument::REQUIRED, 'The preferred locale of the identity to create')
48
            ->addArgument(
49
                'phone-number',
50
                InputArgument::REQUIRED,
51
                'The phone number of the user should be formatted like "+31 (0) 612345678"'
52
            )
53
            ->addArgument(
54
                'registration-status',
55
                InputArgument::REQUIRED,
56
                'Valid arguments: unverified, verified, vetted'
57
            )
58
            ->addArgument('actor-id', InputArgument::REQUIRED, 'The id of the vetting actor');
59
    }
60
61
    protected function execute(InputInterface $input, OutputInterface $output)
62
    {
63
        $this->tokenStorage->setToken(
64
            new AnonymousToken('cli.bootstrap-identity-with-sms-token', 'cli', ['ROLE_SS', 'ROLE_RA'])
0 ignored issues
show
Documentation introduced by
array('ROLE_SS', 'ROLE_RA') is of type array<integer,string,{"0":"string","1":"string"}>, but the function expects a array<integer,object<Sym...curity\Core\Role\Role>>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
65
        );
66
        $nameId = new NameId($input->getArgument('name-id'));
67
        $institutionText = $input->getArgument('institution');
68
        $institution = new Institution($institutionText);
0 ignored issues
show
Bug introduced by
It seems like $institutionText defined by $input->getArgument('institution') on line 67 can also be of type array<integer,string> or null; however, Surfnet\Stepup\Identity\...titution::__construct() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
69
        $mailVerificationRequired = $this->requiresMailVerification($institutionText);
70
        $commonName = $input->getArgument('common-name');
71
        $email = $input->getArgument('email');
72
        $preferredLocale = $input->getArgument('preferred-locale');
73
        $registrationStatus = $input->getArgument('registration-status');
74
        $phoneNumber = $input->getArgument('phone-number');
75
        $actorId = $input->getArgument('actor-id');
76
        $this->enrichEventMetadata($actorId);
77
        $identity = false;
78
        $output->writeln(sprintf('<notice>Adding a %s SMS token for %s</notice>', $registrationStatus, $commonName));
79
        if ($this->tokenBootstrapService->hasIdentityWithNameIdAndInstitution($nameId, $institution)) {
80
            $output->writeln(
81
                sprintf(
82
                    '<notice>An identity with name ID "%s" from institution "%s" already exists, using that identity</notice>',
83
                    $nameId->getNameId(),
84
                    $institution->getInstitution()
85
                )
86
            );
87
            $identity = $this->tokenBootstrapService->findOneByNameIdAndInstitution($nameId, $institution);
88
        }
89
        $this->beginTransaction();
90
        $secondFactorId = Uuid::uuid4()->toString();
91
        if (!$identity) {
92
            $output->writeln('<notice>Creating a new identity</notice>');
93
            $identity = $this->createIdentity($institution, $nameId, $commonName, $email, $preferredLocale);
94
        }
95
        try {
96
            switch ($registrationStatus) {
97
                case "unverified":
98
                    $output->writeln('<notice>Creating an unverified SMS token</notice>');
99
                    $this->provePossession($secondFactorId, $identity, $phoneNumber);
100
                    break;
101
                case "verified":
102
                    $output->writeln('<notice>Creating an unverified SMS token</notice>');
103
                    $this->provePossession($secondFactorId, $identity, $phoneNumber);
104
                    $unverifiedSecondFactor = $this->tokenBootstrapService->findUnverifiedToken($identity->id, 'sms');
105
                    if ($mailVerificationRequired) {
106
                        $output->writeln('<notice>Creating a verified SMS token</notice>');
107
                        $this->verifyEmail($identity, $unverifiedSecondFactor);
108
                    }
109
                    break;
110
                case "vetted":
111
                    $output->writeln('<notice>Creating an unverified SMS token</notice>');
112
                    $this->provePossession($secondFactorId, $identity, $phoneNumber);
113
                    /** @var UnverifiedSecondFactor $unverifiedSecondFactor */
114
                    $unverifiedSecondFactor = $this->tokenBootstrapService->findUnverifiedToken($identity->id, 'sms');
115
                    if ($mailVerificationRequired) {
116
                        $output->writeln('<notice>Creating a verified SMS token</notice>');
117
                        $this->verifyEmail($identity, $unverifiedSecondFactor);
118
                    }
119
                    $verifiedSecondFactor = $this->tokenBootstrapService->findVerifiedToken($identity->id, 'sms');
120
                    $output->writeln('<notice>Vetting the verified SMS token</notice>');
121
                    $this->vetSecondFactor(
122
                        'sms',
123
                        $actorId,
124
                        $identity,
125
                        $secondFactorId,
126
                        $verifiedSecondFactor,
127
                        $phoneNumber
128
                    );
129
                    break;
130
            }
131
            $this->finishTransaction();
132
        } catch (Exception $e) {
133
            $output->writeln(
134
                sprintf(
135
                    '<error>An Error occurred when trying to bootstrap the identity: "%s"</error>',
136
                    $e->getMessage()
137
                )
138
            );
139
            $this->rollback();
140
            throw $e;
141
        }
142
        $output->writeln(
143
            sprintf(
144
                '<info>Successfully created identity with UUID %s and %s second factor with UUID %s</info>',
145
                $identity->id,
146
                $registrationStatus,
147
                $secondFactorId
148
            )
149
        );
150
    }
151
152 View Code Duplication
    private function provePossession($secondFactorId, $identity, $phoneNumber)
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...
153
    {
154
        $command = new ProvePhonePossessionCommand();
155
        $command->UUID = (string)Uuid::uuid4();
156
        $command->secondFactorId = $secondFactorId;
157
        $command->identityId = $identity->id;
158
        $command->phoneNumber = $phoneNumber;
159
        $this->process($command);
160
    }
161
162 View Code Duplication
    private function verifyEmail($identity, $unverifiedSecondFactor)
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...
163
    {
164
        $command = new VerifyEmailCommand();
165
        $command->UUID = (string)Uuid::uuid4();
166
        $command->identityId = $identity->id;
167
        $command->verificationNonce = $unverifiedSecondFactor->verificationNonce;
168
        $this->process($command);
169
    }
170
171
    protected function createIdentity(
172
        Institution $institution,
173
        NameId $nameId,
174
        $commonName,
175
        $email,
176
        $preferredLocale
177
    ) {
178
        $identity = new CreateIdentityCommand();
179
        $identity->UUID = (string)Uuid::uuid4();
180
        $identity->id = (string)Uuid::uuid4();
181
        $identity->institution = $institution->getInstitution();
182
        $identity->nameId = $nameId->getNameId();
183
        $identity->commonName = $commonName;
184
        $identity->email = $email;
185
        $identity->preferredLocale = $preferredLocale;
186
        $this->process($identity);
187
188
        return $identity;
189
    }
190
}
191