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

execute()   C

Complexity

Conditions 9
Paths 120

Size

Total Lines 99

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 99
rs 6.3329
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\ApiBundle\Identity\Entity\VerifiedSecondFactor;
27
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\CreateIdentityCommand;
28
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\ProvePhonePossessionCommand;
29
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\VerifyEmailCommand;
30
use Symfony\Component\Console\Input\InputArgument;
31
use Symfony\Component\Console\Input\InputInterface;
32
use Symfony\Component\Console\Output\OutputInterface;
33
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
34
35
/**
36
 * @SuppressWarnings(PHPMD.ExcessiveClassLength)
37
 */
38
final class BootstrapIdentityWithSmsSecondFactorCommand extends AbstractBootstrapCommand
39
{
40 View Code Duplication
    protected function configure()
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...
41
    {
42
        $this
43
            ->setDescription('Creates an identity with a SMS second factor')
44
            ->addArgument('name-id', InputArgument::REQUIRED, 'The NameID of the identity to create')
45
            ->addArgument('institution', InputArgument::REQUIRED, 'The institution of the identity to create')
46
            ->addArgument('common-name', InputArgument::REQUIRED, 'The Common Name of the identity to create')
47
            ->addArgument('email', InputArgument::REQUIRED, 'The e-mail address of the identity to create')
48
            ->addArgument('preferred-locale', InputArgument::REQUIRED, 'The preferred locale of the identity to create')
49
            ->addArgument(
50
                'phone-number',
51
                InputArgument::REQUIRED,
52
                'The phone number of the user should be formatted like "+31 (0) 612345678"'
53
            )
54
            ->addArgument(
55
                'registration-status',
56
                InputArgument::REQUIRED,
57
                'Valid arguments: unverified, verified, vetted'
58
            );
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
        $identity = false;
76
        $output->writeln(sprintf('<notice>Adding a %s SMS token for %s</notice>', $registrationStatus, $commonName));
77
78
        if ($this->identityRepository->hasIdentityWithNameIdAndInstitution($nameId, $institution)) {
79
            $output->writeln(
80
                sprintf(
81
                    '<notice>An identity with name ID "%s" from institution "%s" already exists, using that identity</notice>',
82
                    $nameId->getNameId(),
83
                    $institution->getInstitution()
84
                )
85
            );
86
            $identity = $this->identityRepository->findOneByNameIdAndInstitution($nameId, $institution);
87
        }
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
96
        try {
97
            switch ($registrationStatus) {
98
                case "unverified":
99
                    $output->writeln('<notice>Creating an unverified SMS token</notice>');
100
                    $this->provePossession($secondFactorId, $identity, $phoneNumber);
101
                    break;
102
                case "verified":
103
                    $output->writeln('<notice>Creating an unverified SMS token</notice>');
104
                    $this->provePossession($secondFactorId, $identity, $phoneNumber);
105
                    /** @var UnverifiedSecondFactor $unverifiedSecondFactor */
106
                    $unverifiedSecondFactor = $this->unverifiedSecondFactorRepository->findOneBy(
107
                        ['identityId' => $identity->id, 'type' => 'sms']
108
                    );
109
                    if ($mailVerificationRequired) {
110
                        $output->writeln('<notice>Creating a verified SMS token</notice>');
111
                        $this->verifyEmail($identity, $unverifiedSecondFactor);
112
                    }
113
                    break;
114
                case "vetted":
115
                    $output->writeln('<notice>Creating an unverified SMS token</notice>');
116
                    $this->provePossession($secondFactorId, $identity, $phoneNumber);
117
                    /** @var UnverifiedSecondFactor $unverifiedSecondFactor */
118
                    $unverifiedSecondFactor = $this->unverifiedSecondFactorRepository->findOneBy(
119
                        ['identityId' => $identity->id, 'type' => 'sms']
120
                    );
121
                    if ($mailVerificationRequired) {
122
                        $output->writeln('<notice>Creating a verified SMS token</notice>');
123
                        $this->verifyEmail($identity, $unverifiedSecondFactor);
124
                    }
125
                    /** @var VerifiedSecondFactor $verifiedSecondFactor */
126
                    $verifiedSecondFactor = $this->verifiedSecondFactorRepository->findOneBy(
127
                        ['identityId' => $identity->id, 'type' => 'sms']
128
                    );
129
                    $output->writeln('<notice>Vetting the verified SMS token</notice>');
130
                    $this->vetSecondFactor(
131
                        'sms',
132
                        'db9b8bdf-720c-44ba-a4c4-154953e45f14',
133
                        $identity,
134
                        $secondFactorId,
135
                        $verifiedSecondFactor,
136
                        $phoneNumber
137
                    );
138
                    break;
139
            }
140
            $this->finishTransaction();
141
        } catch (Exception $e) {
142
            $output->writeln(
143
                sprintf(
144
                    '<error>An Error occurred when trying to bootstrap the identity: "%s"</error>',
145
                    $e->getMessage()
146
                )
147
            );
148
            $this->rollback();
149
            throw $e;
150
        }
151
        $output->writeln(
152
            sprintf(
153
                '<info>Successfully created identity with UUID %s and %s second factor with UUID %s</info>',
154
                $identity->id,
155
                $registrationStatus,
156
                $secondFactorId
157
            )
158
        );
159
    }
160
161 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...
162
    {
163
        $command = new ProvePhonePossessionCommand();
164
        $command->UUID = (string)Uuid::uuid4();
165
        $command->secondFactorId = $secondFactorId;
166
        $command->identityId = $identity->id;
167
        $command->phoneNumber = $phoneNumber;
168
        $this->process($command);
169
    }
170
171 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...
172
    {
173
        $command = new VerifyEmailCommand();
174
        $command->UUID = (string)Uuid::uuid4();
175
        $command->identityId = $identity->id;
176
        $command->verificationNonce = $unverifiedSecondFactor->verificationNonce;
177
        $this->process($command);
178
    }
179
180
    protected function createIdentity(
181
        Institution $institution,
182
        NameId $nameId,
183
        $commonName,
184
        $email,
185
        $preferredLocale
186
    ) {
187
        $identity = new CreateIdentityCommand();
188
        $identity->UUID = (string)Uuid::uuid4();
189
        $identity->id = (string)Uuid::uuid4();
190
        $identity->institution = $institution->getInstitution();
191
        $identity->nameId = $nameId->getNameId();
192
        $identity->commonName = $commonName;
193
        $identity->email = $email;
194
        $identity->preferredLocale = $preferredLocale;
195
        $this->process($identity);
196
197
        return $identity;
198
    }
199
}
200