Completed
Push — master ( 2e4bb9...57d19c )
by Gaetano
07:25
created

GenerateCommand::migrationContextFromParameters()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 13
c 0
b 0
f 0
ccs 0
cts 0
cp 0
rs 9.5222
cc 5
nc 4
nop 1
crap 30
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 $availableTypes = array('role', 'content', 'content_type', 'content_type_group', 'object_state_group', 'section', 'generic', 'db', 'php');
21
    private $thisBundle = 'EzMigrationBundle';
22
23
    /**
24
     * Configure the console command
25
     */
26 76
    protected function configure()
27
    {
28 76
        $this->setName('kaliop:migration:generate')
29 76
            ->setDescription('Generate a blank migration definition file.')
30 76
            ->addOption('format', null, InputOption::VALUE_REQUIRED, 'The format of migration file to generate (' . implode(', ', $this->availableMigrationFormats) . ')', 'yml')
31 76
            ->addOption('type', null, InputOption::VALUE_REQUIRED, 'The type of migration to generate (' . implode(', ', $this->availableTypes) . ')', '')
32 76
            ->addOption('mode', null, InputOption::VALUE_REQUIRED, 'The mode of the migration (' . implode(', ', $this->availableModes) . ')', 'create')
33 76
            ->addOption('match-type', null, InputOption::VALUE_REQUIRED, 'The type of identifier used to find the entity to generate the migration for', null)
34 76
            ->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)
35 76
            ->addOption('match-except', null, InputOption::VALUE_NONE, 'Used to match all entities except the ones satisfying the match-value condition', null)
36 76
            ->addOption('lang', 'l', InputOption::VALUE_REQUIRED, 'The language of the migration (eng-GB, ger-DE, ...). If null, the default language of the current siteaccess is used')
37 76
            ->addOption('dbserver', null, InputOption::VALUE_REQUIRED, 'The type of the database server the sql migration is for, when type=db (mysql, postgresql, ...)', 'mysql')
38 76
            ->addOption('role', null, InputOption::VALUE_REQUIRED, 'Deprecated: The role identifier (or id) that you would like to update, for type=role', null)
39 76
            ->addOption('admin-login', 'a', InputOption::VALUE_REQUIRED, "Login of admin account used whenever elevated privileges are needed (user id 14 used by default)")
40 76
            ->addArgument('bundle', InputArgument::REQUIRED, 'The bundle to generate the migration definition file in. eg.: AcmeMigrationBundle')
41 76
            ->addArgument('name', InputArgument::OPTIONAL, 'The migration name (will be prefixed with current date)', null)
42 76
            ->setHelp(<<<EOT
43
The <info>kaliop:migration:generate</info> command generates a skeleton migration definition file:
44
45
    <info>php ezpublish/console kaliop:migration:generate bundleName</info>
46
47
You can optionally specify the file type to generate with <info>--format</info>, as well a name for the migration:
48
49
    <info>php ezpublish/console kaliop:migration:generate --format=json bundleName migrationName</info>
50
51
For SQL type migration you can optionally specify the database server type the migration is for with <info>--dbserver</info>:
52
53
    <info>php ezpublish/console kaliop:migration:generate --format=sql bundleName</info>
54
55
For role/content/content_type migrations you need to specify the entity that you want to generate the migration for:
56
57
    <info>php ezpublish/console kaliop:migration:generate --type=content --match-type=content_id --match-value=10,14 bundleName</info>
58
59
For role type migration you will receive a yaml file with the current role definition. You must define ALL the policies
60
you wish for the role. Any not defined will be removed. Example for updating an existing role:
61
62
    <info>php ezpublish/console kaliop:migration:generate --type=role --mode=update --match-type=identifier --match-value=Anonymous bundleName</info>
63
64
For freeform php migrations, you will receive a php class definition
65
66
    <info>php ezpublish/console kaliop:migration:generate --format=php bundlename classname</info>
67
68
Note that you can pass in a custom directory path instead of a bundle name, but, if you do, you will have to use the <info>--path</info>
69
option when you run the <info>migrate</info> command.
70
EOT
71 76
            );
72
    }
73
74
    /**
75
     * Run the command and display the results.
76
     *
77
     * @param InputInterface $input
78
     * @param OutputInterface $output
79
     * @return null|int null or 0 if everything went fine, or an error code
80
     * @throws \InvalidArgumentException When an unsupported file type is selected
81 31
     */
82
    public function execute(InputInterface $input, OutputInterface $output)
83 31
    {
84 31
        $bundleName = $input->getArgument('bundle');
85 31
        $name = $input->getArgument('name');
86 31
        $fileType = $input->getOption('format');
87 31
        $migrationType = $input->getOption('type');
88 31
        $role = $input->getOption('role');
89 31
        $matchType = $input->getOption('match-type');
90 31
        $matchValue = $input->getOption('match-value');
91 31
        $matchExcept = $input->getOption('match-except');
92 31
        $mode = $input->getOption('mode');
93
        $dbServer = $input->getOption('dbserver');
94 31
95
        if ($role != '') {
96
            $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>');
97
            $migrationType = 'role';
98
            $matchType = 'identifier';
99
            $matchValue = $role;
100
            if ($mode == '') {
101
                $mode = 'update';
102
            }
103
        }
104 31
105
        if ($bundleName == $this->thisBundle) {
106
            throw new \InvalidArgumentException("It is not allowed to create migrations in bundle '$bundleName'");
107
        }
108
109 31
        // be kind to lazy users
110 6
        if ($migrationType == '') {
111 2
            if ($fileType == 'sql') {
112 4
                $migrationType = 'db';
113 2
            } elseif ($fileType == 'php') {
114
                $migrationType = 'php';
115 2
            } else {
116
                $migrationType = 'generic';
117
            }
118
        }
119 31
120
        if (!in_array($fileType, $this->availableMigrationFormats)) {
121
            throw new \InvalidArgumentException('Unsupported migration file format ' . $fileType);
122
        }
123 31
124
        if (!in_array($mode, $this->availableModes)) {
125
            throw new \InvalidArgumentException('Unsupported migration mode ' . $mode);
126
        }
127 31
128
        $migrationDirectory = $this->getMigrationDirectory($bundleName);
0 ignored issues
show
Bug introduced by
It seems like $bundleName defined by $input->getArgument('bundle') on line 84 can also be of type array<integer,string>; however, Kaliop\eZMigrationBundle...getMigrationDirectory() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
129 31
130 1
        if (!is_dir($migrationDirectory)) {
131 1
            $output->writeln(sprintf(
132 1
                "Migrations directory <info>%s</info> does not exist. I will create it now....",
133
                $migrationDirectory
134
            ));
135 1
136 1
            if (mkdir($migrationDirectory, self::DIR_CREATE_PERMISSIONS, true)) {
137 1
                $output->writeln(sprintf(
138 1
                    "Migrations directory <info>%s</info> has been created",
139
                    $migrationDirectory
140
                ));
141
            } else {
142
                throw new FileException(sprintf(
143
                    "Failed to create migrations directory %s.",
144
                    $migrationDirectory
145
                ));
146
            }
147
        }
148
149 31
        // allow to generate migrations for many entities
150 2
        if (strpos($matchValue, ',') !== false ) {
151
            $matchValue = explode(',', $matchValue);
152
        }
153
154 31
        $parameters = array(
155 31
            'dbserver' => $dbServer,
156 31
            'matchType' => $matchType,
157 31
            'matchValue' => $matchValue,
158 31
            'matchExcept' => $matchExcept,
159 31
            'mode' => $mode,
160
            'lang' => $input->getOption('lang'),
161
            'adminLogin' => $input->getOption('admin-login')
162 31
        );
163
164
        $date = date('YmdHis');
165 31
166
        switch ($fileType) {
167 2
            case 'sql':
168 1
                /// @todo this logic should come from the DefinitionParser, really
169
                if ($name != '') {
170 2
                    $name = '_' . ltrim($name, '_');
171 2
                }
172
                $fileName = $date . '_' . $dbServer . $name . '.sql';
173 29
                break;
174
175 2
            case 'php':
176 2
                /// @todo this logic should come from the DefinitionParser, really
177 1
                $className = ltrim($name, '_');
178
                if ($className == '') {
179
                    $className = 'Migration';
180 2
                }
181 2
                // Make sure that php class names are unique, not only migration definition file names
182
                $existingMigrations = count(glob($migrationDirectory . '/*_' . $className . '*.php'));
183
                if ($existingMigrations) {
184 2
                    $className = $className . sprintf('%03d', $existingMigrations + 1);
185 2
                }
186
                $parameters = array_merge($parameters, array(
187 2
                    'class_name' => $className
188 2
                ));
189
                $fileName = $date . '_' . $className . '.php';
190
                break;
191 27
192 1
            default:
193
                if ($name == '') {
194 27
                    $name = 'placeholder';
195
                }
196
                $fileName = $date . '_' . $name . '.' . $fileType;
197 31
        }
198
199 31
        $path = $migrationDirectory . '/' . $fileName;
200
201 6
        $warning = $this->generateMigrationFile($path, $fileType, $migrationType, $parameters);
202
203 6
        $output->writeln(sprintf("Generated new migration file: <info>%s</info>", $path));
204
205
        if ($warning != '') {
206 6
            $output->writeln("<comment>$warning</comment>");
207
        }
208
    }
209
210
    /**
211
     * Generates a migration definition file.
212
     * @todo allow non-filesystem storage
213
     *
214
     * @param string $path filename to file to generate (full path)
215
     * @param string $fileType The type of migration file to generate
216
     * @param string $migrationType The type of migration to generate
217
     * @param array $parameters passed on to twig
218 31
     * @return string A warning message in case file generation was OK but there was something weird
219
     * @throws \Exception
220 31
     */
221
    protected function generateMigrationFile($path, $fileType, $migrationType, array $parameters = array())
222
    {
223 31
        $warning = '';
224 29
225 27
        switch ($migrationType) {
226
            case 'db':
227 6
            case 'generic':
228 6
            case 'php':
229 6
                // Generate migration file by template
230
                $template = $migrationType . 'Migration.' . $fileType . '.twig';
231
                $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...
232
                if (!is_file($templatePath . $template)) {
233 6
                    throw new \Exception("The combination of migration type '$migrationType' is not supported with format '$fileType'");
234 6
                }
235
236
                $code = $this->getContainer()->get('twig')->render($this->thisBundle . ':MigrationTemplate:' . $template, $parameters);
237
                break;
238 25
239
            default:
240
                // Generate migration file by executor
241
                $executors = $this->getGeneratingExecutors();
242
                if (!in_array($migrationType, $executors)) {
243
                    throw new \Exception("It is not possible to generate a migration of type '$migrationType': executor not found or not a generator");
244
                }
245
                $executor = $this->getMigrationService()->getExecutor($migrationType);
246
247
                $context = $this->migrationContextFromParameters($parameters);
248
249
                $matchCondition = array($parameters['matchType'] => $parameters['matchValue']);
250
                if ($parameters['matchExcept']) {
251
                    $matchCondition = array(MatcherInterface::MATCH_NOT => $matchCondition);
252
                }
253
                $data = $executor->generateMigration($matchCondition, $parameters['mode'], $context);
254
255
                if (!is_array($data) || !count($data)) {
256
                    $warning = 'Note: the generated migration is empty';
257
                }
258
259 View Code Duplication
                switch ($fileType) {
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...
260
                    case 'yml':
261
                        $code = Yaml::dump($data, 5);
262
                        break;
263
                    case 'json':
264
                        $code = json_encode($data, JSON_PRETTY_PRINT);
265
                        break;
266
                    default:
267
                        throw new \Exception("The combination of migration type '$migrationType' is not supported with format '$fileType'");
268
                }
269
        }
270
271 6
        file_put_contents($path, $code);
272
273 6
        return $warning;
274
    }
275
276
    /**
277
     * @param string $bundleName a bundle name or filesystem path to a directory
278
     * @return string
279
     */
280 31
    protected function getMigrationDirectory($bundleName)
281
    {
282
        // Allow direct usage of a directory path instead of a bundle name
283 31
        if (strpos($bundleName, '/') !== false && is_dir($bundleName)) {
284
            return rtrim($bundleName, '/');
285
        }
286
287 31
        $activeBundles = array();
288 31
        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...
289 31
            $activeBundles[] = $bundle->getName();
290
        }
291 31
        asort($activeBundles);
292 31
        if (!in_array($bundleName, $activeBundles)) {
293
            throw new \InvalidArgumentException("Bundle '$bundleName' does not exist or it is not enabled. Try with one of:\n" . implode(', ', $activeBundles));
294
        }
295
296 31
        $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...
297 31
        $migrationDirectory = $bundle->getPath() . '/' . $this->getContainer()->get('ez_migration_bundle.helper.config.resolver')->getParameter('kaliop_bundle_migration.version_directory');
298
299 31
        return $migrationDirectory;
300
    }
301
302
    /// @todo move somewhere else. Maybe to the MigrationService itself ?
303 25 View Code Duplication
    protected function getGeneratingExecutors()
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...
304
    {
305 25
        $migrationService = $this->getMigrationService();
306
        $executors = $migrationService->listExecutors();
307
        foreach($executors as $key => $name) {
308
            $executor = $migrationService->getExecutor($name);
309
            if (!$executor instanceof MigrationGeneratorInterface) {
310
                unset($executors[$key]);
311
            }
312
        }
313
        return $executors;
314
    }
315
316
    /**
317
     * @see MigrationService::migrationContextFromParameters
318
     * @param array $parameters
319
     * @return array
320
     */
321
    protected function migrationContextFromParameters(array $parameters)
322
    {
323
        $context = array();
324
325
        if (isset($parameters['lang']) && $parameters['lang'] != '') {
326
            $context['defaultLanguageCode'] = $parameters['lang'];
327
        }
328
        if (isset($parameters['adminLogin']) && $parameters['adminLogin'] != '') {
329
            $context['adminUserLogin'] = $parameters['adminLogin'];
330
        }
331
332
        return $context;
333
    }
334
}
335