Completed
Pull Request — master (#93)
by
unknown
23:15
created

GenerateCommand::generateMigrationFile()   D

Complexity

Conditions 9
Paths 13

Size

Total Lines 41
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 9

Importance

Changes 0
Metric Value
dl 0
loc 41
ccs 18
cts 18
cp 1
rs 4.909
c 0
b 0
f 0
cc 9
eloc 29
nc 13
nop 4
crap 9
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');
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 (yml, php, sql, json)', 'yml')
30 20
            ->addOption('type', null, InputOption::VALUE_REQUIRED, 'The type of migration to generate (role, content_type, generic, db, php)', '')
31 20
            ->addOption('dbserver', null, InputOption::VALUE_REQUIRED, 'The type of the database server the sql migration is for, for type=db (mysql, postgresql, ...)', 'mysql')
32 20
            ->addOption('role', null, InputOption::VALUE_REQUIRED, 'Deprecated: The role identifier (or id) that you would like to update, for type=role', null)
33 20
            ->addOption('match_type', null, InputOption::VALUE_REQUIRED, 'The match type that you would like to update', null)
34 20
            ->addOption('match_value', null, InputOption::VALUE_REQUIRED, 'The match value that you would like to update', null)
35 20
            ->addOption('mode', null, InputOption::VALUE_REQUIRED, 'The mode of the migration (create, update)', 'create')
36 20
            ->addOption('lang', null, InputOption::VALUE_REQUIRED, 'The language of the migration (eng-GB, ger-DE)', 'eng-GB')
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>./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>./ezpublish/console kaliop:migration:generate --format=yml 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>./ezpublish/console kaliop:migration:generate --format=sql bundlename migrationname</info>
51
52
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.
53
54
    <info>./ezpublish/console kaliop:migration:generate --role=Anonymous bundlename migrationname
55
56
For freeform php migrations, you will receive a php class definition
57
58 20
    <info>./ezpublish/console kaliop:migration:generate --format=php bundlename classname</info>
59 20
60
EOT
61
            );
62
    }
63
64
    /**
65
     * Run the command and display the results.
66
     *
67
     * @param InputInterface $input
68
     * @param OutputInterface $output
69 1
     * @return null|int null or 0 if everything went fine, or an error code
70
     * @throws \InvalidArgumentException When an unsupported file type is selected
71 1
     */
72 1
    public function execute(InputInterface $input, OutputInterface $output)
73 1
    {
74 1
        $bundleName = $input->getArgument('bundle');
75 1
        $name = $input->getArgument('name');
76 1
        $fileType = $input->getOption('format');
77
        $migrationType = $input->getOption('type');
78 1
        $role = $input->getOption('role');
79
        $matchType = $input->getOption('match_type');
80
        $matchValue = $input->getOption('match_value');
81
        $mode = $input->getOption('mode');
82 1
        $dbServer = $input->getOption('dbserver');
83 1
84
        if ($role != '') {
85 1
            $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>');
86 1
            $migrationType = 'role';
87 1
            $matchType = 'identifier';
88 1
            $matchValue = $role;
89
        }
90
91
        if ($bundleName == $this->thisBundle) {
92 1
            throw new \InvalidArgumentException("It is not allowed to create migrations in bundle '$bundleName'");
93 1
        }
94
95
        $activeBundles = array();
96 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...
97 1
            $activeBundles[] = $bundle->getName();
98 1
        }
99 1
        asort($activeBundles);
100 1
        if (!in_array($bundleName, $activeBundles)) {
101 1
            throw new \InvalidArgumentException("Bundle '$bundleName' does not exist or it is not enabled. Try with one of:\n" . implode(', ', $activeBundles));
102 1
        }
103 1
104 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...
105
        $migrationDirectory = $bundle->getPath() . '/' . $this->getContainer()->getParameter('kaliop_bundle_migration.version_directory');
106 1
107
        // be kind to lazy users
108 1
        if ($migrationType == '') {
109
            if ($fileType == 'sql') {
110
                $migrationType = 'db';
111
            } elseif ($fileType == 'php') {
112 1
                $migrationType = 'php';
113
            } else {
114
                $migrationType = 'generic';
115
            }
116 1
        }
117 1
118 1
        if (!in_array($fileType, $this->availableMigrationFormats)) {
119
            throw new \InvalidArgumentException('Unsupported migration file format ' . $fileType);
120 1
        }
121
122 1
        if (!in_array($mode, $this->availableModes)) {
123 1
            throw new \InvalidArgumentException('Unsupported migration mode ' . $mode);
124 1
        }
125
126 1
        if (!is_dir($migrationDirectory)) {
127 1
            $output->writeln(sprintf(
128
                "Migrations directory <info>%s</info> does not exist. I will create it now....",
129
                $migrationDirectory
130
            ));
131
132
            if (mkdir($migrationDirectory, self::DIR_CREATE_PERMISSIONS, true)) {
133 1
                $output->writeln(sprintf(
134
                    "Migrations directory <info>%s</info> has been created",
135
                    $migrationDirectory
136 1
                ));
137 1
            } else {
138 1
                throw new FileException(sprintf(
139
                    "Failed to create migrations directory %s.",
140 1
                    $migrationDirectory
141
                ));
142
            }
143 1
        }
144
145 1
        $parameters = array(
146 1
            'dbserver' => $dbServer,
147 1
            'matchType' => $matchType,
148 1
            'matchValue' => $matchValue,
149 1
            'mode' => $mode,
150
            'lang' => $input->getOption('lang')
151 1
        );
152
153 1
        $date = date('YmdHis');
154 1
155 1
        switch ($fileType) {
156 1
            case 'sql':
157
                /// @todo this logic should come from the DefinitionParser, really
158 1
                if ($name != '') {
159 1
                    $name = '_' . ltrim($name, '_');
160
                }
161
                $fileName = $date . '_' . $dbServer . $name . '.sql';
162 1
                break;
163 1
164
            case 'php':
165 1
                /// @todo this logic should come from the DefinitionParser, really
166 1
                $className = ltrim($name, '_');
167 1
                if ($className == '') {
168
                    $className = 'Migration';
169 1
                }
170 1
                // Make sure that php class names are unique, not only migration definition file names
171 1
                $existingMigrations = count(glob($migrationDirectory . '/*_' . $className . '*.php'));
172 1
                if ($existingMigrations) {
173 1
                    $className = $className . sprintf('%03d', $existingMigrations + 1);
174 1
                }
175
                $parameters = array_merge($parameters, array(
176 1
                    'namespace' => $bundle->getNamespace(),
177
                    'class_name' => $className
178 1
                ));
179
                $fileName = $date . '_' . $className . '.php';
180 1
                break;
181 1
182
            default:
183
                if ($name == '') {
184
                    $name = 'placeholder';
185
                }
186
                $fileName = $date . '_' . $name . '.' . $fileType;
187
        }
188
189
        $path = $migrationDirectory . '/' . $fileName;
190
191
        $this->generateMigrationFile($path, $fileType, $migrationType, $parameters);
192
193 1
        $output->writeln(sprintf("Generated new migration file: <info>%s</info>", $path));
194
    }
195 1
196 1
    /**
197 1
     * Generates a migration definition file.
198
     *
199
     * @param string $path filename to file to generate (full path)
200
     * @param string $fileType The type of migration file to generate
201 1
     * @param string $migrationType The type of migration to generate
202 1
     * @param array $parameters passed on to twig
203 1
     * @return string The path to the migration file
204 1
     * @throws \Exception
205
     */
206
    protected function generateMigrationFile($path, $fileType, $migrationType, array $parameters = array())
207 1
    {
208 1
        switch ($migrationType) {
209
            case 'db':
210
            case 'generic':
211
            case 'php':
212
                // Generate migration file by template
213
                $template = $migrationType . 'Migration.' . $fileType . '.twig';
214
                $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...
215
                if (!is_file($templatePath . $template)) {
216 1
                    throw new \Exception("The combination of migration type '$migrationType' is not supported with format '$fileType'");
217
                }
218
219 1
                $code = $this->getContainer()->get('twig')->render($this->thisBundle . ':MigrationTemplate:' . $template, $parameters);
220 1
                break;
221 1
            default:
222
                // Generate migration file by executor
223
                $migrationService = $this->getMigrationService();
224 1
                $executor = $migrationService->getExecutor($migrationType);
225
                if (!$executor instanceof MigrationGeneratorInterface) {
226
                    throw new \Exception("The executor '$migrationType' can not generate a migration");
227 1
                }
228
                if ($executor instanceof RepositoryExecutor) {
229
                    $executor->setLanguageCode($parameters['lang']);
230 1
                }
231
                $data = $executor->generateMigration($parameters['matchType'], $parameters['matchValue'], $parameters['mode']);
232 1
233
                switch ($fileType) {
234 1
                    case 'yml':
235
                        $code = Yaml::dump($data, 5);
236 1
                        break;
237
                    case 'json':
238
                        $code = json_encode($data, JSON_PRETTY_PRINT);
239 1
                        break;
240
                    default:
241 1
                        throw new \Exception("The combination of migration type '$migrationType' is not supported with format '$fileType'");
242 1
                }
243
        }
244 1
245 1
        file_put_contents($path, $code);
246 1
    }
247
}
248