Completed
Pull Request — master (#91)
by
unknown
08:50
created

GenerateCommand::execute()   F

Complexity

Conditions 18
Paths 310

Size

Total Lines 119
Code Lines 76

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 70
CRAP Score 18.4787

Importance

Changes 0
Metric Value
dl 0
loc 119
ccs 70
cts 79
cp 0.8861
rs 3.6714
c 0
b 0
f 0
cc 18
eloc 76
nc 310
nop 2
crap 18.4787

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 Kaliop\eZMigrationBundle\Command;
4
5
use Kaliop\eZMigrationBundle\API\MigrationGeneratorInterface;
6
use Symfony\Component\Console\Input\InputArgument;
7
use Symfony\Component\Console\Input\InputInterface;
8
use Symfony\Component\Console\Input\InputOption;
9
use Symfony\Component\Console\Output\OutputInterface;
10
use Symfony\Component\HttpFoundation\File\Exception\FileException;
11
use Symfony\Component\Yaml\Yaml;
12
13
class GenerateCommand extends AbstractCommand
14
{
15
    const DIR_CREATE_PERMISSIONS = 0755;
16
17
    private $availableMigrationFormats = array('yml', 'php', 'sql', 'json');
18
    private $availableModes = array('create', 'update');
19
    private $thisBundle = 'EzMigrationBundle';
20
21
    /**
22
     * Configure the console command
23
     */
24
    protected function configure()
25
    {
26 20
        $this->setName('kaliop:migration:generate')
27
            ->setDescription('Generate a blank migration definition file.')
28 20
            ->addOption('format', null, InputOption::VALUE_REQUIRED, 'The format of migration file to generate (yml, php, sql, json)', 'yml')
29 20
            ->addOption('type', null, InputOption::VALUE_REQUIRED, 'The type of migration to generate (role, content_type, generic, db, php)', '')
30 20
            ->addOption('dbserver', null, InputOption::VALUE_REQUIRED, 'The type of the database server the sql migration is for, for type=db (mysql, postgresql, ...)', 'mysql')
31 20
            ->addOption('role', null, InputOption::VALUE_REQUIRED, 'Deprecated: The role identifier (or id) that you would like to update, for type=role', null)
32 20
            ->addOption('identifier', null, InputOption::VALUE_REQUIRED, 'The identifier that you would like to update', null)
33 20
            ->addOption('mode', null, InputOption::VALUE_REQUIRED, 'The mode of the migration (create, update)', 'create')
34 20
            ->addArgument('bundle', InputArgument::REQUIRED, 'The bundle to generate the migration definition file in. eg.: AcmeMigrationBundle')
35 20
            ->addArgument('name', InputArgument::OPTIONAL, 'The migration name (will be prefixed with current date)', null)
36 20
            ->setHelp(<<<EOT
37
The <info>kaliop:migration:generate</info> command generates a skeleton migration definition file:
38
39
    <info>./ezpublish/console kaliop:migration:generate bundlename</info>
40
41
You can optionally specify the file type to generate with <info>--format</info>:
42
43
    <info>./ezpublish/console kaliop:migration:generate --format=yml bundlename migrationname</info>
44
45
For SQL type migration you can optionally specify the database server type the migration is for with <info>--dbserver</info>:
46
47
    <info>./ezpublish/console kaliop:migration:generate --format=sql bundlename migrationname</info>
48
49
For role type migration you will receive a yaml file with the current role definition. You must define ALL the policies you wish for the role. Any not defined will be removed.
50
51
    <info>./ezpublish/console kaliop:migration:generate --role=Anonymous bundlename migrationname
52
53
For freeform php migrations, you will receive a php class definition
54
55
    <info>./ezpublish/console kaliop:migration:generate --format=php bundlename classname</info>
56
57
EOT
58 20
            );
59 20
    }
60
61
    /**
62
     * Run the command and display the results.
63
     *
64
     * @param InputInterface $input
65
     * @param OutputInterface $output
66
     * @return null|int null or 0 if everything went fine, or an error code
67
     * @throws \InvalidArgumentException When an unsupported file type is selected
68
     */
69 1
    public function execute(InputInterface $input, OutputInterface $output)
70
    {
71 1
        $bundleName = $input->getArgument('bundle');
72 1
        $name = $input->getArgument('name');
73 1
        $fileType = $input->getOption('format');
74 1
        $migrationType = $input->getOption('type');
75 1
        $role = $input->getOption('role');
76 1
        $identifier = $input->getOption('identifier');
77
        $mode = $input->getOption('mode');
78 1
        $dbServer = $input->getOption('dbserver');
79
80
        if ($role != '') {
81
            $output->writeln('<error>The "role" option is deprecated since version 3.2 and will be removed in 4.0. Use "identifier" instead.</error>');
82 1
            $migrationType = 'role';
83 1
            $identifier = $role;
84
        }
85 1
86 1
        if ($bundleName == $this->thisBundle) {
87 1
            throw new \InvalidArgumentException("It is not allowed to create migrations in bundle '$bundleName'");
88 1
        }
89
90
        $activeBundles = array();
91
        foreach ($this->getApplication()->getKernel()->getBundles() as $bundle) {
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...
92 1
            $activeBundles[] = $bundle->getName();
93 1
        }
94
        asort($activeBundles);
95
        if (!in_array($bundleName, $activeBundles)) {
96 1
            throw new \InvalidArgumentException("Bundle '$bundleName' does not exist or it is not enabled. Try with one of:\n" . implode(', ', $activeBundles));
97 1
        }
98 1
99 1
        $bundle = $this->getApplication()->getKernel()->getBundle($bundleName);
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...
100 1
        $migrationDirectory = $bundle->getPath() . '/' . $this->getContainer()->getParameter('kaliop_bundle_migration.version_directory');
101 1
102 1
        // be kind to lazy users
103 1
        if ($migrationType == '') {
104 1
            if ($fileType == 'sql') {
105
                $migrationType = 'db';
106 1
            } elseif ($fileType == 'php') {
107
                $migrationType = 'php';
108 1
            } else {
109
                $migrationType = 'generic';
110
            }
111
        }
112 1
113
        if (!in_array($fileType, $this->availableMigrationFormats)) {
114
            throw new \InvalidArgumentException('Unsupported migration file format ' . $fileType);
115
        }
116 1
117 1
        if (!in_array($mode, $this->availableModes)) {
118 1
            throw new \InvalidArgumentException('Unsupported migration mode ' . $mode);
119
        }
120 1
121
        if (!is_dir($migrationDirectory)) {
122 1
            $output->writeln(sprintf(
123 1
                "Migrations directory <info>%s</info> does not exist. I will create it now....",
124 1
                $migrationDirectory
125
            ));
126 1
127 1
            if (mkdir($migrationDirectory, self::DIR_CREATE_PERMISSIONS, true)) {
128
                $output->writeln(sprintf(
129
                    "Migrations directory <info>%s</info> has been created",
130
                    $migrationDirectory
131
                ));
132
            } else {
133 1
                throw new FileException(sprintf(
134
                    "Failed to create migrations directory %s.",
135
                    $migrationDirectory
136 1
                ));
137 1
            }
138 1
        }
139
140 1
        $parameters = array(
141
            'dbserver' => $dbServer,
142
            'identifier' => $identifier,
143 1
            'mode' => $mode
144
        );
145 1
146 1
        $date = date('YmdHis');
147 1
148 1
        switch ($fileType) {
149 1
            case 'sql':
150
                /// @todo this logic should come from the DefinitionParser, really
151 1
                if ($name != '') {
152
                    $name = '_' . ltrim($name, '_');
153 1
                }
154 1
                $fileName = $date . '_' . $dbServer . $name . '.sql';
155 1
                break;
156 1
157
            case 'php':
158 1
                /// @todo this logic should come from the DefinitionParser, really
159 1
                $className = ltrim($name, '_');
160
                if ($className == '') {
161
                    $className = 'Migration';
162 1
                }
163 1
                // Make sure that php class names are unique, not only migration definition file names
164
                $existingMigrations = count(glob($migrationDirectory . '/*_' . $className . '*.php'));
165 1
                if ($existingMigrations) {
166 1
                    $className = $className . sprintf('%03d', $existingMigrations + 1);
167 1
                }
168
                $parameters = array_merge($parameters, array(
169 1
                    'namespace' => $bundle->getNamespace(),
170 1
                    'class_name' => $className
171 1
                ));
172 1
                $fileName = $date . '_' . $className . '.php';
173 1
                break;
174 1
175
            default:
176 1
                if ($name == '') {
177
                    $name = 'placeholder';
178 1
                }
179
                $fileName = $date . '_' . $name . '.' . $fileType;
180 1
        }
181 1
182
        $path = $migrationDirectory . '/' . $fileName;
183
184
        $this->generateMigrationFile($path, $fileType, $migrationType, $parameters);
185
186
        $output->writeln(sprintf("Generated new migration file: <info>%s</info>", $path));
187
    }
188
189
    /**
190
     * Generates a migration definition file.
191
     *
192
     * @param string $path filename to file to generate (full path)
193 1
     * @param string $fileType The type of migration file to generate
194
     * @param string $migrationType The type of migration to generate
195 1
     * @param array $parameters passed on to twig
196 1
     * @return string The path to the migration file
197 1
     * @throws \Exception
198
     */
199
    protected function generateMigrationFile($path, $fileType, $migrationType, array $parameters = array())
200
    {
201 1
        switch ($migrationType) {
202 1
            case 'db':
203 1
            case 'generic':
204 1
            case 'php':
205
                // Generate migration file by template
206
                $template = $migrationType . 'Migration.' . $fileType . '.twig';
207 1
                $templatePath = $this->getApplication()->getKernel()->getBundle($this->thisBundle)->getPath() . '/Resources/views/MigrationTemplate/';
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...
208 1
                if (!is_file($templatePath . $template)) {
209
                    throw new \Exception("The combination of migration type '$migrationType' is not supported with format '$fileType'");
210
                }
211
212
                $code = $this->getContainer()->get('twig')->render($this->thisBundle . ':MigrationTemplate:' . $template, $parameters);
213
                break;
214
            default:
215
                // Generate migration file by executor
216 1
                $migrationService = $this->getMigrationService();
217
                $executor = $migrationService->getExecutor($migrationType);
218
                if (!$executor instanceof MigrationGeneratorInterface) {
219 1
                    throw new \Exception("The executor '$migrationType' can not generate a migration");
220 1
                }
221 1
                $data = $executor->generateMigration($parameters['identifier'], $parameters['mode']);
222
223
                switch ($fileType) {
224 1
                    case 'yml':
225
                        $code = Yaml::dump($data, 5);
226
                        break;
227 1
                    case 'json':
228
                        $code = json_encode($data, JSON_PRETTY_PRINT);
229
                        break;
230 1
                    default:
231
                        throw new \Exception("The combination of migration type '$migrationType' is not supported with format '$fileType'");
232 1
                }
233
        }
234 1
235
        file_put_contents($path, $code);
236 1
    }
237
}
238