Completed
Pull Request — master (#91)
by
unknown
06:57
created

GenerateCommand::generateRoleTemplate()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 42
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 42
ccs 22
cts 22
cp 1
rs 8.8571
c 0
b 0
f 0
cc 3
eloc 22
nc 3
nop 1
crap 3
1
<?php
2
3
namespace Kaliop\eZMigrationBundle\Command;
4
5
use Kaliop\eZMigrationBundle\API\ExecutorGenerateInterface;
6
use Symfony\Component\Console\Input\InputArgument;
7
use Symfony\Component\Console\Input\InputInterface;
8
use Symfony\Component\Console\Input\InputOption;
9
use Symfony\Component\Console\Output\OutputInterface;
10
use Symfony\Component\HttpFoundation\File\Exception\FileException;
11
use Symfony\Component\Yaml\Yaml;
12
13
class GenerateCommand extends AbstractCommand
14
{
15
    const ADMIN_USER_ID = 14;
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
            ->addArgument('bundle', InputArgument::REQUIRED, 'The bundle to generate the migration definition file in. eg.: AcmeMigrationBundle')
36 20
            ->addArgument('name', InputArgument::OPTIONAL, 'The migration name (will be prefixed with current date)', null)
37
            ->setHelp(<<<EOT
38
The <info>kaliop:migration:generate</info> command generates a skeleton migration definition file:
39
40
    <info>./ezpublish/console kaliop:migration:generate bundlename</info>
41
42
You can optionally specify the file type to generate with <info>--format</info>:
43
44
    <info>./ezpublish/console kaliop:migration:generate --format=yml bundlename migrationname</info>
45
46
For SQL type migration you can optionally specify the database server type the migration is for with <info>--dbserver</info>:
47
48
    <info>./ezpublish/console kaliop:migration:generate --format=sql bundlename migrationname</info>
49
50
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.
51
52
    <info>./ezpublish/console kaliop:migration:generate --role=Anonymous bundlename migrationname
53
54
For freeform php migrations, you will receive a php class definition
55
56
    <info>./ezpublish/console kaliop:migration:generate --format=php bundlename classname</info>
57
58 20
EOT
59 20
            );
60
    }
61
62
    /**
63
     * Run the command and display the results.
64
     *
65
     * @param InputInterface $input
66
     * @param OutputInterface $output
67
     * @return null|int null or 0 if everything went fine, or an error code
68
     * @throws \InvalidArgumentException When an unsupported file type is selected
69 1
     */
70
    public function execute(InputInterface $input, OutputInterface $output)
71 1
    {
72 1
        $bundleName = $input->getArgument('bundle');
73 1
        $name = $input->getArgument('name');
74 1
        $fileType = $input->getOption('format');
75 1
        $migrationType = $input->getOption('type');
76 1
        $role = $input->getOption('role');
77
        $identifier = $input->getOption('identifier');
78 1
        $mode = $input->getOption('mode');
79
        $dbServer = $input->getOption('dbserver');
80
81
        if ($role != '') {
82 1
            $output->writeln('<error>The "role" option is deprecated since version 3.2 and will be removed in 4.0. Use "identifier" instead.</error>');
83 1
            $migrationType = 'role';
84
            $identifier = $role;
85 1
        }
86 1
87 1
        if ($bundleName == $this->thisBundle) {
88 1
            throw new \InvalidArgumentException("It is not allowed to create migrations in bundle '$bundleName'");
89
        }
90
91
        $activeBundles = array();
92 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...
93 1
        {
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
        );
147 1
148 1
        $date = date('YmdHis');
149 1
150
        switch ($fileType) {
151 1
            case 'sql':
152
                /// @todo this logic should come from the DefinitionParser, really
153 1
                if ($name != '') {
154 1
                    $name = '_' . ltrim($name, '_');
155 1
                }
156 1
                $fileName = $date . '_' . $dbServer . $name . '.sql';
157
                break;
158 1
159 1
            case 'php':
160
                /// @todo this logic should come from the DefinitionParser, really
161
                $className = ltrim($name, '_');
162 1
                if ($className == '') {
163 1
                    $className = 'Migration';
164
                }
165 1
                // Make sure that php class names are unique, not only migration definition file names
166 1
                $existingMigrations = count(glob($migrationDirectory.'/*_' . $className .'*.php'));
167 1
                if ($existingMigrations) {
168
                    $className = $className . sprintf('%03d', $existingMigrations + 1);
169 1
                }
170 1
                $parameters = array_merge($parameters, array(
171 1
                    'namespace' => $bundle->getNamespace(),
172 1
                    'class_name' => $className
173 1
                ));
174 1
                $fileName = $date . '_' . $className . '.php';
175
                break;
176 1
177
            default:
178 1
                if ($name == '') {
179
                    $name = 'placeholder';
180 1
                }
181 1
                $fileName = $date . '_' . $name . '.' . $fileType;
182
        }
183
184
        $path = $migrationDirectory . '/' . $fileName;
185
186
        $this->generateMigrationFile($path, $fileType, $migrationType, $parameters);
187
188
        $output->writeln(sprintf("Generated new migration file: <info>%s</info>", $path));
189
    }
190
191
    /**
192
     * Generates a migration definition file.
193 1
     *
194
     * @param string $path filename to file to generate (full path)
195 1
     * @param string $fileType The type of migration file to generate
196 1
     * @param string $migrationType The type of migration to generate
197 1
     * @param array $parameters passed on to twig
198
     * @return string The path to the migration file
199
     * @throws \Exception
200
     */
201 1
    protected function generateMigrationFile($path, $fileType, $migrationType, array $parameters = array())
202 1
    {
203 1
        switch ($migrationType) {
204 1
            case 'db':
205
            case 'generic':
206
            case 'php':
207 1
                // Generate migration file by template
208 1
                $template = $migrationType . 'Migration.' . $fileType . '.twig';
209
                $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...
210
                if (!is_file($templatePath . $template)) {
211
                    throw new \Exception("The combination of migration type '$migrationType' is not supported with format '$fileType'");
212
                }
213
214
                $code = $this->getContainer()->get('twig')->render($this->thisBundle . ':MigrationTemplate:'.$template, $parameters);
215
                break;
216 1
            default:
217
                // Generate migration file by executor
218
                $migrationService = $this->getMigrationService();
219 1
                $executor = $migrationService->getExecutor($migrationType);
220 1
                if (!$executor instanceof ExecutorGenerateInterface) {
221 1
                    throw new \Exception("The executor '$migrationType' can not generate a migration");
222
                }
223
                $data = $executor->generateMigration($parameters['identifier'], $parameters['mode']);
224 1
225
                switch ($fileType) {
226
                    case 'yml':
227 1
                        $code = Yaml::dump($data, 5);
228
                        break;
229
                    case 'json':
230 1
                        $code = json_encode($data);
231
                        break;
232 1
                    default:
233
                        throw new \Exception("The combination of migration type '$migrationType' is not supported with format '$fileType'");
234 1
                }
235
        }
236 1
237
        file_put_contents($path, $code);
238
    }
239
}
240