InitCommand::initialize()   F
last analyzed

Complexity

Conditions 15
Paths 4098

Size

Total Lines 83
Code Lines 42

Duplication

Lines 6
Ratio 7.23 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 6
loc 83
rs 2
cc 15
eloc 42
nc 4098
nop 2

How to fix   Long Method    Complexity   

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
namespace Openl10n\Cli\Command;
4
5
use GuzzleHttp\Exception\ClientException;
6
use Openl10n\Cli\ServiceContainer\Exception\ConfigurationLoadingException;
7
use Openl10n\Sdk\Model\Project;
8
use Symfony\Component\Console\Input\InputArgument;
9
use Symfony\Component\Console\Input\InputInterface;
10
use Symfony\Component\Console\Output\OutputInterface;
11
use Symfony\Component\Yaml\Yaml;
12
13
class InitCommand extends AbstractCommand
14
{
15
    protected $configuration = array();
16
17
    /**
18
     * {@inheritdoc}
19
     */
20
    protected function configure()
21
    {
22
        $this
23
            ->setName('init')
24
            ->setDescription('Create the configuration file and initialize the project')
25
            ->setDefinition(array(
26
                new InputArgument('url', InputArgument::OPTIONAL, 'URL of the openl10n instance (eg. http://user:[email protected])'),
27
                new InputArgument('project', InputArgument::OPTIONAL, 'Slug of the project'),
28
                new InputArgument('pattern', InputArgument::OPTIONAL|InputArgument::IS_ARRAY, 'Pattern of the translation files'),
29
            ))
30
        ;
31
    }
32
33
    /**
34
     * {@inheritdoc}
35
     */
36
    protected function initialize(InputInterface $input, OutputInterface $output)
37
    {
38
        //
39
        // First try to read the configuration file if exists
40
        //
41
        $this->getApplication()->ignoreMissingConfiguration();
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 ignoreMissingConfiguration() does only exist in the following sub-classes of Symfony\Component\Console\Application: Openl10n\Cli\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...
42
        $configurationLoader = $this->get('configuration.loader');
43
44
        try {
45
            // Init configuration by manually read configuration file (if already exists)
46
            $this->configuration = $configurationLoader->loadConfiguration();
47
        } catch (ConfigurationLoadingException $e) {
48
            $this->configuration = [
49
                'server'  => [],
50
                'project' => null,
51
                'files'   => [],
52
            ];
53
        }
54
55
        //
56
        // Then add config from input
57
        //
58
        $server = [
59
            'scheme' => null,
60
            'user' => null,
61
            'pass' => null,
62
            'port' => null,
63
            'host' => null
64
        ];
65
66
        if (null !== $url = $input->getArgument('url')) {
67
            $urlParts = parse_url($url);
68
69
            if (false === $urlParts) {
70
                throw new InvalidArgumentException("$url is not a valid URL");
71
            }
72
73
            $server = array_merge($server, $urlParts);
74
        }
75
76
        if (null !== $hostname = $server['host']) {
77
            $this->configuration['server']['hostname'] = $hostname;
78
        }
79
80
        if (null !== $scheme = $server['scheme']) {
81
            $this->configuration['server']['use_ssl'] = 'https' === $scheme;
82
        }
83
84
        if (isset($this->configuration['server']['use_ssl']) && false === $this->configuration['server']['use_ssl']) {
85
            unset($this->configuration['server']['use_ssl']);
86
        }
87
88 View Code Duplication
        if (null !== $port = $server['port']) {
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...
89
            $this->configuration['server']['port'] = $port;
90
        }
91
92
        if (null !== $username = $server['user']) {
93
            $this->configuration['server']['username'] = $username;
94
        }
95
96 View Code Duplication
        if (null !== $password = $server['pass']) {
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...
97
            $this->configuration['server']['password'] = $password;
98
        }
99
100
        if (null !== $projectSlug = $input->getArgument('project')) {
101
            $this->configuration['project'] = $projectSlug;
102
        }
103
104
        if (array() !== $patterns = $input->getArgument('pattern')) {
105
            $this->configuration['files'] = $patterns;
106
        }
107
108
        // If no file are already set, try to find possible ones
109
        if (empty($this->configuration['files'])) {
110
            $inDir = $this->get('configuration.loader')->getRootDirectory();
111
            $this->configuration['files'] = $this->get('file.pattern_guess')->suggestPatterns($inDir);
112
        }
113
114
        // If no pattern found, add example of file pattern
115
        if (empty($this->configuration['files'])) {
116
            $this->configuration['files'][] = 'path/to/translations.<locale>.yml';
117
        }
118
    }
119
120
    /**
121
     * {@inheritdoc}
122
     */
123
    protected function interact(InputInterface $input, OutputInterface $output)
124
    {
125
        $dialog = $this->getHelperSet()->get('dialog');
126
127
        // Server
128 View Code Duplication
        if (!isset($this->configuration['server']['hostname'])) {
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...
129
            $this->configuration['server']['hostname'] = $dialog->ask($output, '<info>Hostname</info> [<comment>openl10n.dev</comment>]: ', 'openl10n.dev');
130
        }
131
132 View Code Duplication
        if (!isset($this->configuration['server']['use_ssl'])) {
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...
133
            $this->configuration['server']['use_ssl'] = $dialog->askConfirmation($output, '<info>Enable ssl</info> [<comment>no</comment>]? ', false);
134
        }
135
136
        if (false === $this->configuration['server']['use_ssl']) {
137
            unset($this->configuration['server']['use_ssl']);
138
        }
139
140
        if (!isset($this->configuration['server']['username'])) {
141
            $currentUser = get_current_user();
142
            $this->configuration['server']['username'] = $dialog->ask($output, "<info>Username</info> [<comment>$currentUser</comment>]: ", $currentUser);
143
        }
144
145
        if (!isset($this->configuration['server']['password'])) {
146
            $currentUser = get_current_user();
0 ignored issues
show
Unused Code introduced by
$currentUser is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
147
            $this->configuration['server']['password'] = $dialog->askHiddenResponseAndValidate(
148
                $output,
149
                '<info>Password</info> []: ',
150
                function ($answer) {
151
                    if ('' === trim($answer)) {
152
                        throw new \RuntimeException('The password can not be empty.');
153
                    }
154
155
                    return $answer;
156
                },
157
                false,
158
                false
159
            );
160
        }
161
162
        // Project
163
        if (!isset($this->configuration['project'])) {
164
            $project = strtolower(basename(realpath($this->get('configuration.loader')->getRootDirectory())));
165
            $this->configuration['project'] = $dialog->ask($output, "<info>Project's slug</info> [<comment>$project</comment>]: ", $project);
166
        }
167
    }
168
169
    /**
170
     * {@inheritdoc}
171
     */
172
    protected function execute(InputInterface $input, OutputInterface $output)
173
    {
174
        $dialog = $this->getHelperSet()->get('dialog');
175
        $configurationLoader = $this->get('configuration.loader');
176
177
        // Dump configuration
178
        $content = $this->get('configuration.dumper')->dumpConfiguration($this->configuration);
179
180
        if ($input->isInteractive()) {
181
            $output->writeln(['', $content]);
182
        }
183
184
        if (!$dialog->askConfirmation($output, '<info>Do you confirm generation</info> [<comment>yes</comment>]? ')) {
185
            return 1;
186
        }
187
188
        file_put_contents($configurationLoader->getConfigurationFilepath(), $content);
189
190
        // Destroy current container to force recreate it with configured service
191
        $this->getApplication()->destroyContainer();
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 destroyContainer() does only exist in the following sub-classes of Symfony\Component\Console\Application: Openl10n\Cli\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...
192
193
        $projectApi = $this->get('api')->getEntryPoint('project');
194
195
        try {
196
            $projectSlug = $this->configuration['project'];
197
            $project = $projectApi->get($projectSlug);
0 ignored issues
show
Unused Code introduced by
$project is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
198
199
            return;
200
        } catch (ClientException $e) {
201
            if ('404' !== $e->getResponse()->getStatusCode()) {
202
                throw $e;
203
            }
204
        }
205
206
        $output->writeln('');
207
        if ($dialog->askConfirmation($output, '<info>Would you like to create the project</info> [<comment>yes</comment>]? ')) {
208
            $project = new Project($projectSlug);
209
210
            $defaultName = ucfirst($project->getSlug());
211
            $name = $dialog->ask($output, "<info>Project's name</info> [<comment>$defaultName</comment>]: ", $defaultName);
212
            $project->setName($name);
213
214
            $defaultLocale = $dialog->ask($output, "<info>Default locale</info> [<comment>en</comment>]: ", 'en');
215
            $project->setDefaultLocale($defaultLocale);
216
217
            try {
218
                $projectApi->create($project);
219
            } catch (\Exception $e) {
220
                $output->writeln(sprintf('<error>%s</error>', $e->getMessage()));
221
222
                return 1;
223
            }
224
        }
225
    }
226
}
227