GenerateImageEntityCrudCommand   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 218
Duplicated Lines 5.05 %

Coupling/Cohesion

Components 2
Dependencies 10

Importance

Changes 0
Metric Value
wmc 12
lcom 2
cbo 10
dl 11
loc 218
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
B __construct() 0 33 3
B configure() 0 26 1
B execute() 11 45 4
B interact() 0 77 2
A getSkeletonDirs() 0 14 2

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
 * This file is part of the IrishDan\ResponsiveImageBundle package.
4
 *
5
 * (c) Daniel Byrne <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE file that was distributed with this source
8
 * code.
9
 */
10
11
namespace IrishDan\ResponsiveImageBundle\Command;
12
13
use IrishDan\ResponsiveImageBundle\ImageEntityClassLocator;
14
use Sensio\Bundle\GeneratorBundle\Command\GenerateDoctrineCrudCommand;
15
use Sensio\Bundle\GeneratorBundle\Command\Validators;
16
use Symfony\Component\Console\Input\InputInterface;
17
use Symfony\Component\Console\Input\InputOption;
18
use Symfony\Component\Console\Output\OutputInterface;
19
use Symfony\Component\Console\Question\ConfirmationQuestion;
20
use Symfony\Component\Console\Question\Question;
21
use Symfony\Component\HttpKernel\Bundle\BundleInterface;
22
23
24
/**
25
 * Class CreateImageEntityCommand
26
 *
27
 * @package IrishDan\ResponsiveImageBundle\Command
28
 */
29
class GenerateImageEntityCrudCommand extends GenerateDoctrineCrudCommand
30
{
31
    protected $responsiveImageEntity;
32
    protected $imageEntityShorthand;
33
    protected $entityName;
34
    protected $bundle;
35
    protected $doctrine;
36
    protected $entityShortNotation;
37
    protected $metadata;
38
39
    public function __construct(ImageEntityClassLocator $entityClassFinder, $doctrine)
40
    {
41
        parent::__construct();
42
43
        $this->responsiveImageEntity = $entityClassFinder->getClassName();
44
        $this->doctrine              = $doctrine;
45
        $em                          = $this->doctrine->getManager();
46
47
        try {
48
            $this->metadata = $em->getClassMetadata($this->responsiveImageEntity);
49
        } catch (\Exception $e) {
50
            throw new \RuntimeException(
51
                sprintf(
52
                    'Entity "%s" does not exist. Create it with the "doctrine:generate:entity" command and then execute this command again.',
53
                    $this->responsiveImageEntity
54
                )
55
            );
56
        }
57
58
        $namespace = $this->metadata->namespace;
59
60
        // This is bit hacky but it'll do for now.
61
        // Lets get rid of the '\Entity'.
62
        if (strpos($namespace, '\\Entity') > 0) {
63
            $namespace = substr($namespace, 0, -7);
64
        }
65
66
        $namespaceParts            = explode('\\', $namespace);
67
        $this->bundle              = array_pop($namespaceParts);
68
        $entityNameParts           = explode('\\', $this->responsiveImageEntity);
69
        $this->entityName          = array_pop($entityNameParts);
70
        $this->entityShortNotation = $this->bundle . ':' . $this->entityName;
71
    }
72
73
    protected function configure()
74
    {
75
        // This limits CRUD generation to the single entity defined in configuration
76
77
        $this
78
            ->setName('responsive_image:generate:crud')
79
            ->setDescription('Generates the CRUD for responsive image entity')
80
            ->setDefinition(
81
                [
82
                    new InputOption('route-prefix', '', InputOption::VALUE_REQUIRED, 'The route prefix'),
83
                    new InputOption(
84
                        'format',
85
                        '',
86
                        InputOption::VALUE_REQUIRED,
87
                        'The format used for configuration files (php, xml, yml, or annotation)',
88
                        'annotation'
89
                    ),
90
                    new InputOption(
91
                        'overwrite',
92
                        '',
93
                        InputOption::VALUE_NONE,
94
                        'Overwrite any existing controller or form class when generating the CRUD contents'
95
                    ),
96
                ]
97
            );
98
    }
99
100
    /**
101
     * @see Command
102
     *
103
     * @param InputInterface  $input
104
     * @param OutputInterface $output
105
     *
106
     * @return int|null
107
     */
108
    protected function execute(InputInterface $input, OutputInterface $output)
109
    {
110
        $questionHelper = $this->getQuestionHelper();
111
112 View Code Duplication
        if ($input->isInteractive()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
113
            $question = new ConfirmationQuestion($questionHelper->getQuestion('Do you confirm generation', 'yes', '?'), true);
114
            if (!$questionHelper->ask($input, $output, $question)) {
115
                $output->writeln('<error>Command aborted</error>');
116
117
                return 1;
118
            }
119
        }
120
121
        $entity = Validators::validateEntityName($this->entityShortNotation);
122
        $bundle = $this->bundle;
123
124
        $format = Validators::validateFormat($input->getOption('format'));
125
        $prefix = $this->getRoutePrefix($input, $entity);
126
127
        $questionHelper->writeSection($output, 'CRUD generation');
128
        $bundle = $this->getContainer()->get('kernel')->getBundle($bundle);
129
130
        $generator = $this->getGenerator($bundle);
131
132
        // $withWrite = true;
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
133
        // $forceOverwrite = true;
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
134
        // @TODO: Perhaps Don't force overwrite
135
        $generator->generate($bundle, $this->entityName, $this->metadata[0], $format, $prefix, true, true);
136
137
        $output->writeln('Generating the CRUD code: <info>OK</info>');
138
139
        $errors = [];
140
        $runner = $questionHelper->getRunner($output, $errors);
141
142
        // routing
143
        $output->write('Updating the routing: ');
144
        if ('annotation' != $format) {
145
            $runner($this->updateRouting($questionHelper, $input, $output, $bundle, $format, $entity, $prefix));
146
        }
147
        else {
148
            $runner($this->updateAnnotationRouting($bundle, $entity, $prefix));
149
        }
150
151
        $questionHelper->writeGeneratorSummary($output, $errors);
152
    }
153
154
    protected function interact(InputInterface $input, OutputInterface $output)
155
    {
156
        $questionHelper = $this->getQuestionHelper();
157
        $questionHelper->writeSection($output, 'Welcome to the Doctrine2 CRUD generator');
158
159
        // namespace
160
        $output->writeln(
161
            [
162
                '',
163
                'This command helps you generate CRUD controllers and templates.',
164
                '',
165
                'First, give the name of the existing entity for which you want to generate a CRUD',
166
                '(use the shortcut notation like <comment>AcmeBlogBundle:Post</comment>)',
167
                '',
168
            ]
169
        );
170
171
        $entity = $this->entityName;
172
        $bundle = $this->bundle;
173
        try {
174
            $entityClass = $this->getContainer()->get('doctrine')->getAliasNamespace($bundle) . '\\' . $entity;
175
            $this->getEntityMetadata($entityClass);
176
        } catch (\Exception $e) {
177
            throw new \RuntimeException(
178
                sprintf(
179
                    'Entity "%s" does not exist in the "%s" bundle. You may have mistyped the bundle name or maybe the entity doesn\'t exist yet (create it first with the "doctrine:generate:entity" command).',
180
                    $entity,
181
                    $bundle
182
                )
183
            );
184
        }
185
186
        // format
187
        $format = $input->getOption('format');
188
        $output->writeln(
189
            [
190
                '',
191
                'Determine the format to use for the generated CRUD.',
192
                '',
193
            ]
194
        );
195
        $question = new Question(
196
            $questionHelper->getQuestion('Configuration format (yml, xml, php, or annotation)', $format), $format
197
        );
198
        $question->setValidator(['Sensio\Bundle\GeneratorBundle\Command\Validators', 'validateFormat']);
199
        $format = $questionHelper->ask($input, $output, $question);
200
        $input->setOption('format', $format);
201
202
        // route prefix
203
        $prefix = $this->getRoutePrefix($input, $entity);
204
        $output->writeln(
205
            [
206
                '',
207
                'Determine the routes prefix (all the routes will be "mounted" under this',
208
                'prefix: /prefix/, /prefix/new, ...).',
209
                '',
210
            ]
211
        );
212
        $prefix = $questionHelper->ask(
213
            $input,
214
            $output,
215
            new Question($questionHelper->getQuestion('Routes prefix', '/' . $prefix), '/' . $prefix)
216
        );
217
        $input->setOption('route-prefix', $prefix);
218
219
        // summary
220
        $output->writeln(
221
            [
222
                '',
223
                $this->getHelper('formatter')->formatBlock('Summary before generation', 'bg=blue;fg=white', true),
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Console\Helper\HelperInterface as the method formatBlock() does only exist in the following implementations of said interface: Symfony\Component\Console\Helper\FormatterHelper.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
224
                '',
225
                sprintf('You are going to generate a CRUD controller for "<info>%s:%s</info>"', $bundle, $entity),
226
                sprintf('using the "<info>%s</info>" format.', $format),
227
                '',
228
            ]
229
        );
230
    }
231
232
    protected function getSkeletonDirs(BundleInterface $bundle = null)
233
    {
234
        $skeletonDirs = [];
235
236
        if (is_dir(
237
            $dir = $this->getContainer()->get('kernel')->getRootdir() . '/Resources/ResponsiveImageBundle/skeleton'
238
        )) {
239
            $skeletonDirs[] = $dir;
240
        }
241
242
        $skeletonDirs[] = __DIR__ . '/../Resources/skeleton';
243
244
        return $skeletonDirs;
245
    }
246
}