Completed
Pull Request — master (#30)
by Anton
17:34
created

ModelCommand::generate()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 57
Code Lines 27

Duplication

Lines 30
Ratio 52.63 %

Code Coverage

Tests 24
CRAP Score 3.004

Importance

Changes 0
Metric Value
dl 30
loc 57
ccs 24
cts 26
cp 0.9231
rs 9.6818
c 0
b 0
f 0
cc 3
eloc 27
nc 4
nop 2
crap 3.004

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
 * @copyright Bluz PHP Team
4
 * @link https://github.com/bluzphp/bluzman
5
 */
6
7
namespace Bluzman\Command\Generate;
8
9
use Bluz\Proxy\Db;
10
use Bluz\Validator\Validator as v;
11
use Bluzman\Input\InputArgument;
12
use Bluzman\Input\InputException;
13
use Bluzman\Generator;
14
use Symfony\Component\Console\Input\InputInterface;
15
use Symfony\Component\Console\Output\OutputInterface;
16
use Symfony\Component\Console\Question\ConfirmationQuestion;
17
18
/**
19
 * ModelCommand
20
 *
21
 * @package  Bluzman\Command\Generate
22
 */
23
class ModelCommand extends AbstractGenerateCommand
24
{
25
    /**
26
     * Command configuration
27
     */
28 14
    protected function configure()
29
    {
30
        $this
31
            // the name of the command (the part after "bin/bluzman")
32 14
            ->setName('generate:model')
33
            // the short description shown while running "php bin/bluzman list"
34 14
            ->setDescription('Generate a new model')
35
            // the full command description shown when running the command with
36
            // the "--help" option
37 14
            ->setHelp('This command allows you to generate models files')
38
        ;
39
40 14
        $this->addModelArgument();
41
42 14
        $table = new InputArgument('table', InputArgument::REQUIRED, 'Table name is required');
43 14
        $table->setValidator(
44 14
            v::create()->string()->alphaNumeric('_')->noWhitespace()
45
        );
46
47 14
        $this->getDefinition()->addArgument($table);
48 14
    }
49
50
    /**
51
     * @param InputInterface $input
52
     * @param OutputInterface $output
53
     * @return void
54
     */
55 2
    protected function execute(InputInterface $input, OutputInterface $output)
56
    {
57
        try {
58 2
            $this->write("Running <info>generate:model</info> command");
59
60 2
            $model = $input->getArgument('model');
61 2
            $this->getDefinition()->getArgument('model')->validate($model);
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\Input\InputArgument as the method validate() does only exist in the following sub-classes of Symfony\Component\Console\Input\InputArgument: Bluzman\Input\InputArgument. 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...
62
63 1
            $table = $input->getArgument('table');
64 1
            $this->getDefinition()->getArgument('table')->validate($table);
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\Input\InputArgument as the method validate() does only exist in the following sub-classes of Symfony\Component\Console\Input\InputArgument: Bluzman\Input\InputArgument. 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...
65
66
            // generate directories and files
67 1
            $this->generate($input, $output);
68
69
            // verify it
70 1
            $this->verify($input, $output);
71
72 1
            $this->write("Model <info>{$model}</info> has been successfully created.");
73 1
        } catch (InputException $e) {
74 1
            $this->error("ERROR: {$e->getMessage()}");
75
        }
76 2
    }
77
78
    /**
79
     * @param InputInterface $input
80
     * @param OutputInterface $output
81
     * @return void
82
     * @throws InputException
83
     */
84 1
    protected function generate(InputInterface $input, OutputInterface $output)
0 ignored issues
show
Unused Code introduced by
The parameter $output is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
85
    {
86 1
        $modelName = ucfirst($input->getArgument('model'));
87 1
        $tableName = $input->getArgument('table');
88
89
        /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
62% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
90
        if ($this->getApplication()->isModelExists($modelName)) {
91
            $helper = $this->getHelperSet()->get("question");
92
            $question = new ConfirmationQuestion(
93
                "\n<question>Model $modelName would be overwritten. y/N?</question>:\n> ",
94
                false
95
            );
96
97
            if (!$helper->ask($input, $output, $question)) {
98
                return;
99
            }
100
        }
101
        */
102
103
        // generate table
104 1
        $tableFile = $this->getApplication()->getModelPath($modelName) . DS . 'Table.php';
105
106 1 View Code Duplication
        if (file_exists($tableFile)) {
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...
107
            $this->comment("Table file <info>$modelName/Table.php</info> already exists");
108
        } else {
109 1
            $template = $this->getTemplate('TableTemplate');
110 1
            $template->setFilePath($tableFile);
111 1
            $template->setTemplateData([
112 1
                'model' => $modelName,
113 1
                'table' => $tableName,
114 1
                'primaryKey' => $this->getPrimaryKey($tableName)
115
            ]);
116
117 1
            $generator = new Generator\Generator($template);
118 1
            $generator->make();
119
        }
120
121
        // generate row
122 1
        $rowFile = $this->getApplication()->getModelPath($modelName) . DS . 'Row.php';
123
124 1 View Code Duplication
        if (file_exists($rowFile)) {
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...
125
            $this->comment("Row file <info>$modelName/Row.php</info> already exists");
126
        } else {
127 1
            $template = $this->getTemplate('RowTemplate');
128 1
            $template->setFilePath($rowFile);
129 1
            $template->setTemplateData(
130
                [
131 1
                    'model' => $modelName,
132 1
                    'table' => $tableName,
133 1
                    'columns' => $this->getColumns($tableName)
134
                ]
135
            );
136
137 1
            $generator = new Generator\Generator($template);
138 1
            $generator->make();
139
        }
140 1
    }
141
142
    /**
143
     * @param InputInterface $input
144
     * @param OutputInterface $output
145
     * @return void
146
     * @throws \Bluzman\Generator\GeneratorException
147
     */
148 1 View Code Duplication
    public function verify(InputInterface $input, OutputInterface $output)
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...
149
    {
150 1
        $modelPath = $this->getApplication()->getModelPath($input->getArgument('model'));
151
152
        $paths = [
153 1
            $modelPath . DS . 'Table.php',
154 1
            $modelPath . DS . 'Row.php'
155
        ];
156
157 1
        foreach ($paths as $path) {
158 1
            if (!$this->getFs()->exists($path)) {
159
                throw new Generator\GeneratorException("File `$path` is not exists");
160
            }
161
        }
162 1
    }
163
164
    /**
165
     * @todo move it to DB class
166
     * @return array
167
     */
168
    protected function getPrimaryKey($table)
169
    {
170
        $connect = Db::getOption('connect');
171
172
        return Db::fetchColumn(
173
            '
174
            SELECT COLUMN_NAME
175
            FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
176
            WHERE TABLE_SCHEMA = ?
177
              AND TABLE_NAME = ?
178
             AND CONSTRAINT_NAME = ?
179
            ',
180
            [$connect['name'], $table, 'PRIMARY']
181
        );
182
    }
183
184
    /**
185
     * @todo move it to DB class
186
     * @return array
187
     */
188
    protected function getColumns($table)
189
    {
190
        $connect = Db::getOption('connect');
191
192
        return Db::fetchAll(
193
            '
194
            SELECT 
195
              COLUMN_NAME as name,
196
              COLUMN_TYPE as type
197
            FROM INFORMATION_SCHEMA.COLUMNS
198
            WHERE TABLE_SCHEMA = ?
199
              AND TABLE_NAME = ?
200
            ',
201
            [$connect['name'], $table]
202
        );
203
    }
204
}
205