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

GenerateCommand::execute()   F

Complexity

Conditions 17
Paths 294

Size

Total Lines 114
Code Lines 72

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 68
CRAP Score 17.4616

Importance

Changes 0
Metric Value
dl 0
loc 114
c 0
b 0
f 0
ccs 68
cts 77
cp 0.8831
rs 3.6909
cc 17
eloc 72
nc 294
nop 2
crap 17.4616

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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