CrudGenCommand   A
last analyzed

Complexity

Total Complexity 17

Size/Duplication

Total Lines 169
Duplicated Lines 11.24 %

Coupling/Cohesion

Components 1
Dependencies 14

Importance

Changes 6
Bugs 1 Features 2
Metric Value
wmc 17
c 6
b 1
f 2
lcom 1
cbo 14
dl 19
loc 169
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
B configure() 0 41 1
B execute() 0 53 5
A createGenerator() 0 7 1
A getRepositoryGenerator() 0 12 2
A getFormGenerator() 0 9 2
A getGenerator() 0 9 2
A getSkeletonDirs() 19 19 4

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace Kpicaza\GenBundle\Command;
4
5
use Kpicaza\GenBundle\Generator\GenCrudGenerator;
6
use Kpicaza\GenBundle\Generator\GenFormGenerator;
7
use Kpicaza\GenBundle\Generator\GenRepositoryGenerator;
8
use Sensio\Bundle\GeneratorBundle\Command\GenerateDoctrineCrudCommand;
9
use Sensio\Bundle\GeneratorBundle\Command\Validators;
10
use Symfony\Component\Console\Input\InputArgument;
11
use Symfony\Component\Console\Input\InputInterface;
12
use Symfony\Component\Console\Input\InputOption;
13
use Symfony\Component\Console\Output\OutputInterface;
14
use Symfony\Component\Console\Question\ConfirmationQuestion;
15
use Symfony\Component\HttpKernel\Bundle\BundleInterface;
16
17
class CrudGenCommand extends GenerateDoctrineCrudCommand
18
{
19
    protected $generator;
20
    protected $formGenerator;
21
    protected $repositoryGenerator;
22
23
    /**
24
     * @see Command
25
     */
26
    protected function configure()
27
    {
28
        $this
29
            ->setName('gen:generate:rest')
30
            ->setAliases(array('doctrine:generate:rest'))
31
            ->setDescription('Generates a REST based on a Doctrine entity')
32
            ->setDefinition(array(
33
                new InputArgument('entity', InputArgument::OPTIONAL, 'The entity class name to initialize (shortcut notation)'),
34
                new InputOption('entity', '', InputOption::VALUE_REQUIRED, 'The entity class name to initialize (shortcut notation)'),
35
                new InputOption('route-prefix', '', InputOption::VALUE_REQUIRED, 'The route prefix to API', '/api'),
36
                new InputOption('with-write', '', InputOption::VALUE_NONE, 'Whether or not to generate create, new and delete actions'),
37
                new InputOption('format', '', InputOption::VALUE_REQUIRED, 'The format used for configuration files (php, xml, yml, or annotation)', 'annotation'),
38
                new InputOption('overwrite', '', InputOption::VALUE_NONE, 'Overwrite any existing controller or form class when generating the CRUD contents'),
39
            ))
40
            ->setHelp(<<<EOT
41
The <info>%command.name%</info> command generates a REST based on a Doctrine entity.
42
43
The default command only generates the list and show actions.
44
45
<info>php %command.full_name% --entity=AcmeBlogBundle:Post --route-prefix=post_admin</info>
46
47
Using the --with-write option allows to generate the new, edit and delete actions.
48
49
<info>php %command.full_name% doctrine:generate:rest --entity=AcmeBlogBundle:Post --route-prefix=post_admin --with-write</info>
50
51
Every generated file is based on a template. There are default templates but they can be overridden by placing custom templates in one of the following locations, by order of priority:
52
53
<info>BUNDLE_PATH/Resources/SensioGeneratorBundle/skeleton/crud
54
APP_PATH/Resources/SensioGeneratorBundle/skeleton/crud</info>
55
56
And
57
58
<info>__bundle_path__/Resources/SensioGeneratorBundle/skeleton/form
59
__project_root__/app/Resources/SensioGeneratorBundle/skeleton/form</info>
60
61
You can check https://github.com/sensio/SensioGeneratorBundle/tree/master/Resources/skeleton
62
in order to know the file structure of the skeleton
63
EOT
64
            )
65
        ;
66
    }
67
68
    /**
69
     * @see Command
70
     */
71
    protected function execute(InputInterface $input, OutputInterface $output)
72
    {
73
        $questionHelper = $this->getQuestionHelper();
74
75
        if ($input->isInteractive()) {
76
            $question = new ConfirmationQuestion($questionHelper->getQuestion('Do you confirm generation', 'yes', '?'), true);
77
            if (!$questionHelper->ask($input, $output, $question)) {
78
                $output->writeln('<error>Command aborted</error>');
79
80
                return 1;
81
            }
82
        }
83
84
        $entity = Validators::validateEntityName($input->getOption('entity'));
85
        list($bundle, $entity) = $this->parseShortcutNotation($entity);
86
87
        $format = Validators::validateFormat($input->getOption('format'));
88
        $prefix = $this->getRoutePrefix($input, $entity);
89
        $withWrite = $input->getOption('with-write');
90
        $forceOverwrite = $input->getOption('overwrite');
91
92
        $questionHelper->writeSection($output, 'REST generation');
93
94
        try {
95
            $entityClass = $this->getContainer()->get('doctrine')->getAliasNamespace($bundle).'\\'.$entity;
96
            $metadata = $this->getEntityMetadata($entityClass);
97
        } catch (\Exception $e) {
98
            throw new \RuntimeException(sprintf('Entity "%s" does not exist in the "%s" bundle. Create it with the "doctrine:generate:entity" command and then execute this command again.', $entity, $bundle));
99
        }
100
101
        $bundle = $this->getContainer()->get('kernel')->getBundle($bundle);
102
103
        $repositoryGenerator = $this->getRepositoryGenerator($bundle);
104
        $repositoryGenerator->generate($bundle, $entity, $metadata[0], $format, $forceOverwrite);
105
106
        $output->writeln('Generating the Repository pattern code: <info>OK</info>');
107
108
        $generator = $this->getGenerator($bundle);
109
        $generator->generate($bundle, $entity, $metadata[0], $format, $prefix, $withWrite, $forceOverwrite);
110
111
        $output->writeln('Generating the REST code: <info>OK</info>');
112
113
        $errors = array();
114
        $questionHelper->getRunner($output, $errors);
0 ignored issues
show
Unused Code introduced by
The call to the method Sensio\Bundle\GeneratorB...tionHelper::getRunner() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
115
116
        // form
117
        if ($withWrite) {
118
            $this->generateForm($bundle, $entity, $metadata, $forceOverwrite);
119
            $output->writeln('Generating the Form code: <info>OK</info>');
120
        }
121
122
        $questionHelper->writeGeneratorSummary($output, $errors);
123
    }
124
125
    protected function createGenerator($bundle = null)
126
    {
127
        return new GenCrudGenerator(
128
            $this->getContainer()->get('filesystem'),
129
            $this->getContainer()->getParameter('kernel.root_dir')
130
        );
131
    }
132
133
    protected function getRepositoryGenerator($bundle = null)
134
    {
135
        if (null === $this->repositoryGenerator) {
136
            $this->repositoryGenerator = new GenRepositoryGenerator(
137
                $this->getContainer()->get('filesystem'),
138
                $this->getContainer()->getParameter('kernel.root_dir')
139
            );
140
            $this->repositoryGenerator->setSkeletonDirs($this->getSkeletonDirs($bundle));
141
        }
142
143
        return $this->repositoryGenerator;
144
    }
145
146
    protected function getFormGenerator($bundle = null)
147
    {
148
        if (null === $this->formGenerator) {
149
            $this->formGenerator = new GenFormGenerator($this->getContainer()->get('filesystem'));
150
            $this->formGenerator->setSkeletonDirs($this->getSkeletonDirs($bundle));
151
        }
152
153
        return $this->formGenerator;
154
    }
155
156
    protected function getGenerator(BundleInterface $bundle = null)
157
    {
158
        if (null === $this->generator) {
159
            $this->generator = $this->createGenerator();
160
            $this->generator->setSkeletonDirs($this->getSkeletonDirs($bundle));
161
        }
162
163
        return $this->generator;
164
    }
165
166 View Code Duplication
    protected function getSkeletonDirs(BundleInterface $bundle = null)
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...
167
    {
168
        $skeletonDirs = parent::getSkeletonDirs($bundle);
169
170
        if (isset($bundle) && is_dir($dir = $bundle->getPath().'/Resources/skeleton')) {
171
            $skeletonDirs[] = $dir;
172
        }
173
174
        if (is_dir($dir = $this->getContainer()->get('kernel')->getRootdir().'/Resources/skeleton')) {
175
            $skeletonDirs[] = $dir;
176
        }
177
178
        $kernel = $this->getApplication()->getKernel();
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...
179
180
        $skeletonDirs[] = $kernel->locateResource('@KpicazaGenBundle/Resources/skeleton');
181
        $skeletonDirs[] = $kernel->locateResource('@KpicazaGenBundle/Resources');
182
183
        return array_reverse($skeletonDirs);
184
    }
185
}
186