Completed
Push — feature/bootstrap-commands ( 9583fe...bf04fe )
by Michiel
02:13
created

AbstractBootstrapCommand::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 9.568
c 0
b 0
f 0
cc 1
nc 1
nop 9

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

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 Broadway\EventHandling\EventBusInterface;
22
use Rhumsaa\Uuid\Uuid;
23
use Surfnet\Stepup\Configuration\Value\Institution;
24
use Surfnet\StepupMiddleware\ApiBundle\Configuration\Repository\InstitutionConfigurationOptionsRepository;
25
use Surfnet\StepupMiddleware\ApiBundle\Identity\Repository\IdentityRepository;
26
use Surfnet\StepupMiddleware\ApiBundle\Identity\Repository\UnverifiedSecondFactorRepository;
27
use Surfnet\StepupMiddleware\ApiBundle\Identity\Repository\VerifiedSecondFactorRepository;
28
use Surfnet\StepupMiddleware\CommandHandlingBundle\Command\Command as MiddlewareCommand;
29
use Surfnet\StepupMiddleware\CommandHandlingBundle\Command\Metadata;
30
use Surfnet\StepupMiddleware\CommandHandlingBundle\EventSourcing\MetadataEnricher;
31
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\VetSecondFactorCommand;
32
use Surfnet\StepupMiddleware\CommandHandlingBundle\Pipeline\Pipeline;
33
use Surfnet\StepupMiddleware\MiddlewareBundle\Service\DBALConnectionHelper;
34
use Symfony\Component\Console\Command\Command;
35
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
36
37
abstract class AbstractBootstrapCommand extends Command
38
{
39
    /** @var Pipeline  */
40
    private $pipeline;
41
    /** @var EventBusInterface  */
42
    private $eventBus;
43
    /** @var DBALConnectionHelper  */
44
    private $connection;
45
    /** @var IdentityRepository  */
46
    protected $identityRepository;
47
    /** @var UnverifiedSecondFactorRepository  */
48
    protected $unverifiedSecondFactorRepository;
49
    /** @var VerifiedSecondFactorRepository */
50
    protected $verifiedSecondFactorRepository;
51
    /** @var InstitutionConfigurationOptionsRepository */
52
    private $institutionConfigurationRepository;
53
    /** @var TokenStorageInterface */
54
    protected $tokenStorage;
55
    /** @var MetadataEnricher */
56
    private $enricher;
57
58
    public function __construct(
59
        Pipeline $pipeline,
60
        EventBusInterface $eventBus,
61
        DBALConnectionHelper $connection,
62
        MetadataEnricher $enricher,
63
        IdentityRepository $identityRepository,
64
        UnverifiedSecondFactorRepository $unverifiedSecondFactorRepository,
65
        VerifiedSecondFactorRepository $verifiedSecondFactorRepository,
66
        InstitutionConfigurationOptionsRepository $institutionConfigurationOptionsRepository,
67
        TokenStorageInterface $tokenStorage
68
    ) {
69
        $this->pipeline = $pipeline;
70
        $this->eventBus = $eventBus;
71
        $this->connection = $connection;
72
        $this->enricher = $enricher;
73
        $this->identityRepository = $identityRepository;
74
        $this->unverifiedSecondFactorRepository = $unverifiedSecondFactorRepository;
75
        $this->verifiedSecondFactorRepository = $verifiedSecondFactorRepository;
76
        $this->institutionConfigurationRepository = $institutionConfigurationOptionsRepository;
77
        $this->tokenStorage = $tokenStorage;
78
        parent::__construct();
79
    }
80
81
    protected function beginTransaction()
82
    {
83
        $this->connection->beginTransaction();
84
    }
85
86
    protected function finishTransaction()
87
    {
88
        $this->eventBus->flush();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Broadway\EventHandling\EventBusInterface as the method flush() does only exist in the following implementations of said interface: Surfnet\StepupMiddleware...ndling\BufferedEventBus.

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...
89
        $this->connection->commit();
90
    }
91
92
    protected function rollback()
93
    {
94
        $this->connection->rollBack();
95
    }
96
97
    protected function process(MiddlewareCommand $command)
98
    {
99
        $this->pipeline->process($command);
100
    }
101
102
    protected function requiresMailVerification($institution)
103
    {
104
        $configuration = $this->institutionConfigurationRepository->findConfigurationOptionsFor(new Institution($institution));
105
        if ($configuration) {
106
            return $configuration->verifyEmailOption->isEnabled();
107
        }
108
        return true;
109
    }
110
111
    protected function vetSecondFactor($tokenType, $actorId, $identity, $secondFactorId, $verifiedSecondFactor, $phoneNumber)
112
    {
113
        $command = new VetSecondFactorCommand();
114
        $command->UUID = (string) Uuid::uuid4();
115
        $command->authorityId = $actorId;
116
        $command->identityId = $identity->id;
117
        $command->secondFactorId = $secondFactorId;
118
        $command->registrationCode = $verifiedSecondFactor->registrationCode;
119
        $command->secondFactorType = $tokenType;
120
        $command->secondFactorIdentifier = $phoneNumber;
121
        $command->documentNumber = '123987';
122
        $command->identityVerified = true;
123
        $this->pipeline->process($command);
124
    }
125
126
    protected function enrichEventMetadata($actorId)
127
    {
128
        $actor = $this->identityRepository->findOneBy(['id' => $actorId]);
129
        $metadata = new Metadata();
130
        $metadata->actorId = $actor->id;
131
        $metadata->actorInstitution = $actor->institution;
132
        $this->enricher->setMetadata($metadata);
133
    }
134
}
135