Completed
Push — master ( c4a8e5...b804d1 )
by Gaetano
06:51
created

GenerateCommand   B

Complexity

Total Complexity 36

Size/Duplication

Total Lines 277
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 92%

Importance

Changes 0
Metric Value
wmc 36
lcom 1
cbo 7
dl 0
loc 277
ccs 115
cts 125
cp 0.92
rs 8.8
c 0
b 0
f 0

4 Methods

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