Completed
Pull Request — master (#93)
by
unknown
07:04
created

GenerateCommand   A

Complexity

Total Complexity 28

Size/Duplication

Total Lines 230
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 7

Test Coverage

Coverage 91.3%

Importance

Changes 0
Metric Value
wmc 28
lcom 2
cbo 7
dl 0
loc 230
ccs 105
cts 115
cp 0.913
rs 10
c 0
b 0
f 0

3 Methods

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