Completed
Pull Request — develop (#170)
by A.
06:41 queued 03:00
created

MigrateInstitutionConfigurationsCommand   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 84
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 5

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 8
lcom 0
cbo 5
dl 0
loc 84
rs 10
c 2
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A configure() 0 8 1
C execute() 0 72 7
1
<?php
2
3
/**
4
 * Copyright 2017 SURFnet B.V.
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 Sensio\Bundle\GeneratorBundle\Command\Helper\QuestionHelper;
23
use Symfony\Component\Console\Command\Command;
24
use Symfony\Component\Console\Input\InputInterface;
25
use Symfony\Component\Console\Output\OutputInterface;
26
use Symfony\Component\Console\Question\ConfirmationQuestion;
27
use Symfony\Component\DependencyInjection\Container;
28
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
29
30
final class MigrateInstitutionConfigurationsCommand extends Command
31
{
32
    protected function configure()
33
    {
34
        $this->setName('stepup:migrate:institution-configuration');
35
        $this->setDescription(
36
            'Migrates institution configurations to work with UUIDv5 identifiers'
37
            . 'based on institutions with normalized casing'
38
        );
39
    }
40
41
    public function execute(InputInterface $input, OutputInterface $output)
42
    {
43
        /** @var QuestionHelper $questionHelper */
44
        $questionHelper = $this->getHelper('question');
45
46
        $output->writeln([
47
            '<error>WARNING: you are about to migrate institution configurations'
48
            . ' to work with identifiers based on insitutions with normalized casing.</error>',
49
            '<error>This command is intended to be run only once.</error>',
50
            ''
51
        ]);
52
53
        $confirmationQuestion = new ConfirmationQuestion(
54
            'Are you sure you want to run the institution configuration migrations? [y/N]',
55
            false
56
        );
57
        $confirmed = $questionHelper->ask($input, $output, $confirmationQuestion);
58
59
        if (!$confirmed) {
60
            $output->writeln('<info>Exiting without running migrations.</info>');
61
            return;
62
        }
63
64
        /** @var Container $container */
65
        $container = $this->getApplication()->getKernel()->getContainer();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Symfony\Component\Console\Application as the method getKernel() does only exist in the following sub-classes of Symfony\Component\Console\Application: Symfony\Bundle\FrameworkBundle\Console\Application. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends 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 sub-classes 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 parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
66
67
        $tokenStorage     = $container->get('security.token_storage');
68
        $connectionHelper = $container->get('surfnet_stepup_middleware_middleware.dbal_connection_helper');
69
        $provider         = $container->get('surfnet_stepup_middleware_middleware.institution_configuration_provider');
70
        $pipeline         = $container->get('pipeline');
71
        $eventBus         = $container->get('surfnet_stepup_middleware_command_handling.event_bus.buffered');
72
73
        // The InstitutionConfiguration commands require ROLE_MANAGEMENT
74
        // Note that the new events will not have any actor metadata associated with them
75
        $tokenStorage->setToken(new AnonymousToken('console', 'console', ['ROLE_MANAGEMENT']));
0 ignored issues
show
Documentation introduced by
array('ROLE_MANAGEMENT') is of type array<integer,string,{"0":"string"}>, but the function expects a array<integer,object<Sym...re\Role\RoleInterface>>.

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...
76
77
        $connectionHelper->beginTransaction();
78
79
        try {
80
            $state = $provider->loadData();
81
82
            foreach ($state->inferRemovalCommands() as $removalCommand) {
83
                $pipeline->process($removalCommand);
84
            }
85
            $eventBus->flush();
86
87
            foreach ($state->inferCreateCommands() as $createCommand) {
88
                $pipeline->process($createCommand);
89
            }
90
            $eventBus->flush();
91
92
            foreach ($state->inferReconfigureCommands() as $reconfigureCommand) {
93
                $pipeline->process($reconfigureCommand);
94
            }
95
            $eventBus->flush();
96
97
            foreach ($state->inferAddRaLocationCommands() as $addRaLocationCommand) {
98
                $pipeline->process($addRaLocationCommand);
99
            }
100
            $eventBus->flush();
101
102
            $connectionHelper->commit();
103
            $output->writeln('<info>Successfully migrated institution configurations.</info>');
104
        } catch (Exception $exception) {
105
            $output->writeln(
106
                sprintf('<error>Could not migrate institution configurations: %s</error>', $exception->getMessage())
107
            );
108
            $connectionHelper->rollBack();
109
110
            throw $exception;
111
        }
112
    }
113
}
114