Test Failed
Push — master ( 359bf7...72eda2 )
by Emmanuel
02:11
created

ConfigGenerateCommand::configure()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 60
Code Lines 56

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 60
rs 9.5555
c 0
b 0
f 0
ccs 0
cts 59
cp 0
cc 1
eloc 56
nc 1
nop 0
crap 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
 * neuralyzer : Data Anonymization Library and CLI Tool
4
 *
5
 * PHP Version 7.1
6
 *
7
 * @author Emmanuel Dyan
8
 * @author Rémi Sauvat
9
 * @copyright 2018 Emmanuel Dyan
10
 *
11
 * @package edyan/neuralyzer
12
 *
13
 * @license GNU General Public License v2.0
14
 *
15
 * @link https://github.com/edyan/neuralyzer
16
 */
17
18
namespace Edyan\Neuralyzer\Console\Commands;
19
20
use Symfony\Component\Console\Command\Command;
21
use Symfony\Component\Console\Input\InputInterface;
22
use Symfony\Component\Console\Input\InputOption;
23
use Symfony\Component\Console\Output\OutputInterface;
24
use Symfony\Component\Console\Question\Question;
25
26
/**
27
 * Command to generate a config file from a DB
28
 */
29
class ConfigGenerateCommand extends Command
30
{
31
    /**
32
     * Set the command shortcut to be used in configuration
33
     *
34
     * @var string
35
     */
36
    protected $command = 'config:generate';
37
38
39
    /**
40
     * Configure the command
41
     *
42
     * @return void
43
     */
44
    protected function configure()
45
    {
46
        // First command : Test the DB Connexion
47
        $this->setName($this->command)
48
            ->setDescription(
49
                'Generate configuration for the Anonymizer'
50
            )->setHelp(
51
                'This command will connect to a DB and extract a list of tables / fields to a yaml file' . PHP_EOL .
52
                "Usage: neuralyzer <info>{$this->command} -u app -p app -f neuralyzer.yml</info>"
53
            )->addOption(
54
                'driver',
55
                'D',
56
                InputOption::VALUE_REQUIRED,
57
                'Driver (check Doctrine documentation to have the list)',
58
                'pdo_mysql'
59
            )->addOption(
60
                'host',
61
                'H',
62
                InputOption::VALUE_REQUIRED,
63
                'Host',
64
                '127.0.0.1'
65
            )->addOption(
66
                'db',
67
                'd',
68
                InputOption::VALUE_REQUIRED,
69
                'Database Name'
70
            )->addOption(
71
                'user',
72
                'u',
73
                InputOption::VALUE_REQUIRED,
74
                'User Name',
75
                get_current_user()
76
            )->addOption(
77
                'password',
78
                'p',
79
                InputOption::VALUE_REQUIRED,
80
                "Password (or it'll be prompted)"
81
            )->addOption(
82
                'file',
83
                'f',
84
                InputOption::VALUE_REQUIRED,
85
                'File',
86
                'neuralyzer.yml'
87
            )->addOption(
88
                'protect',
89
                null,
90
                InputOption::VALUE_NONE,
91
                'Protect IDs and other fields'
92
            )->addOption(
93
                'ignore-table',
94
                null,
95
                InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY,
96
                'Table to ignore. Can be repeated'
97
            )->addOption(
98
                'ignore-field',
99
                null,
100
                InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY,
101
                'Field to ignore. Regexp in the form "table.field". Can be repeated'
102
            );
103
    }
104
105
    /**
106
     * Execute the command
107
     *
108
     * @param InputInterface  $input
109
     * @param OutputInterface $output
110
     *
111
     * @return void
112
     */
113
    protected function execute(InputInterface $input, OutputInterface $output)
114
    {
115
        // Throw an exception immediately if we dont have the required DB parameter
116
        if (empty($input->getOption('db'))) {
117
            throw new \InvalidArgumentException('Database name is required (--db)');
118
        }
119
120
        $password = $input->getOption('password');
121
        if (is_null($password)) {
122
            $question = new Question('Password: ');
123
            $question->setHidden(true)->setHiddenFallback(false);
124
125
            $password = $this->getHelper('question')->ask($input, $output, $question);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Console\Helper\HelperInterface as the method ask() does only exist in the following implementations of said interface: Symfony\Component\Console\Helper\QuestionHelper, Symfony\Component\Consol...r\SymfonyQuestionHelper.

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...
126
        }
127
128
        $ignoreFields = $input->getOption('ignore-field');
129
130
        // Now work on the DB
131
        $db = new \Edyan\Neuralyzer\Anonymizer\DB([
132
            'driver' => $input->getOption('driver'),
133
            'host' => $input->getOption('host'),
134
            'dbname' => $input->getOption('db'),
135
            'user' => $input->getOption('user'),
136
            'password' => $password,
137
        ]);
138
139
        $writer = new \Edyan\Neuralyzer\Configuration\Writer;
140
        $writer->protectCols($input->getOption('protect'));
141
142
        // Override the protection if fields are defined
143
        if (!empty($ignoreFields)) {
144
            $writer->protectCols(true);
145
            $writer->setProtectedCols($ignoreFields);
146
        }
147
148
        $writer->setIgnoredTables($input->getOption('ignore-table'));
149
        $data = $writer->generateConfFromDB($db, new \Edyan\Neuralyzer\Guesser);
150
        $writer->save($data, $input->getOption('file'));
151
152
        $output->writeln('<comment>Configuration written to ' . $input->getOption('file') . '</comment>');
153
    }
154
}
155