Completed
Push — master ( b4efa6...174a17 )
by Gaetano
09:08
created

GenerateCommand::execute()   F

Complexity

Conditions 20
Paths 849

Size

Total Lines 131
Code Lines 84

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 72
CRAP Score 20.7262

Importance

Changes 0
Metric Value
dl 0
loc 131
ccs 72
cts 82
cp 0.878
rs 2.3199
c 0
b 0
f 0
cc 20
eloc 84
nc 849
nop 2
crap 20.7262

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