Completed
Push — master ( a06a95...a1d542 )
by dan
15s
created

GenerateImageEntityCrudCommand   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 217
Duplicated Lines 5.07 %

Coupling/Cohesion

Components 2
Dependencies 10

Importance

Changes 0
Metric Value
wmc 12
lcom 2
cbo 10
dl 11
loc 217
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 48 4
B interact() 0 78 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);
0 ignored issues
show
Bug introduced by
The property metadata does not seem to exist. Did you mean metaData?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
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;
0 ignored issues
show
Bug introduced by
The property metadata does not seem to exist. Did you mean metaData?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
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
    protected function execute(InputInterface $input, OutputInterface $output)
104
    {
105
        $questionHelper = $this->getQuestionHelper();
106
107 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...
108
            $question = new ConfirmationQuestion(
109
                $questionHelper->getQuestion('Do you confirm generation', 'yes', '?'),
110
                true
111
            );
112
            if (!$questionHelper->ask($input, $output, $question)) {
113
                $output->writeln('<error>Command aborted</error>');
114
115
                return 1;
116
            }
117
        }
118
119
        $entity = Validators::validateEntityName($this->entityShortNotation);
120
        $bundle = $this->bundle;
121
122
        $format = Validators::validateFormat($input->getOption('format'));
123
        $prefix = $this->getRoutePrefix($input, $entity);
124
125
        $questionHelper->writeSection($output, 'CRUD generation');
126
        $bundle = $this->getContainer()->get('kernel')->getBundle($bundle);
127
128
        $generator = $this->getGenerator($bundle);
129
130
        // $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...
131
        // $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...
132
        // @TODO: Perhaps Don't force overwrite
133
        $generator->generate($bundle, $this->entityName, $this->metadata[0], $format, $prefix, true, true);
0 ignored issues
show
Bug introduced by
The property metadata does not seem to exist. Did you mean metaData?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
134
135
        $output->writeln('Generating the CRUD code: <info>OK</info>');
136
137
        $errors = [];
138
        $runner = $questionHelper->getRunner($output, $errors);
139
140
        // routing
141
        $output->write('Updating the routing: ');
142
        if ('annotation' != $format) {
143
            $runner($this->updateRouting($questionHelper, $input, $output, $bundle, $format, $entity, $prefix));
144
        }
145
        else {
146
            $runner($this->updateAnnotationRouting($bundle, $entity, $prefix));
147
        }
148
149
        $questionHelper->writeGeneratorSummary($output, $errors);
150
    }
151
152
    protected function interact(InputInterface $input, OutputInterface $output)
153
    {
154
        $questionHelper = $this->getQuestionHelper();
155
        $questionHelper->writeSection($output, 'Welcome to the Doctrine2 CRUD generator');
156
157
        // namespace
158
        $output->writeln(
159
            [
160
                '',
161
                'This command helps you generate CRUD controllers and templates.',
162
                '',
163
                'First, give the name of the existing entity for which you want to generate a CRUD',
164
                '(use the shortcut notation like <comment>AcmeBlogBundle:Post</comment>)',
165
                '',
166
            ]
167
        );
168
169
        // list($bundle, $entity) = $this->parseShortcutNotation($entity);
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% 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...
170
        $entity = $this->entityName;
171
        $bundle = $this->bundle;
172
        try {
173
            $entityClass = $this->getContainer()->get('doctrine')->getAliasNamespace($bundle) . '\\' . $entity;
174
            $metadata    = $this->getEntityMetadata($entityClass);
0 ignored issues
show
Unused Code introduced by
$metadata is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
175
        } catch (\Exception $e) {
176
            throw new \RuntimeException(
177
                sprintf(
178
                    '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).',
179
                    $entity,
180
                    $bundle
181
                )
182
            );
183
        }
184
185
        // format
186
        $format = $input->getOption('format');
187
        $output->writeln(
188
            [
189
                '',
190
                'Determine the format to use for the generated CRUD.',
191
                '',
192
            ]
193
        );
194
        $question = new Question(
195
            $questionHelper->getQuestion('Configuration format (yml, xml, php, or annotation)', $format), $format
196
        );
197
        $question->setValidator(['Sensio\Bundle\GeneratorBundle\Command\Validators', 'validateFormat']);
198
        $format = $questionHelper->ask($input, $output, $question);
199
        $input->setOption('format', $format);
200
201
        // route prefix
202
        $prefix = $this->getRoutePrefix($input, $entity);
203
        $output->writeln(
204
            [
205
                '',
206
                'Determine the routes prefix (all the routes will be "mounted" under this',
207
                'prefix: /prefix/, /prefix/new, ...).',
208
                '',
209
            ]
210
        );
211
        $prefix = $questionHelper->ask(
212
            $input,
213
            $output,
214
            new Question($questionHelper->getQuestion('Routes prefix', '/' . $prefix), '/' . $prefix)
215
        );
216
        $input->setOption('route-prefix', $prefix);
217
218
        // summary
219
        $output->writeln(
220
            [
221
                '',
222
                $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...
223
                '',
224
                sprintf('You are going to generate a CRUD controller for "<info>%s:%s</info>"', $bundle, $entity),
225
                sprintf('using the "<info>%s</info>" format.', $format),
226
                '',
227
            ]
228
        );
229
    }
230
231
    protected function getSkeletonDirs(BundleInterface $bundle = null)
232
    {
233
        $skeletonDirs = [];
234
235
        if (is_dir(
236
            $dir = $this->getContainer()->get('kernel')->getRootdir() . '/Resources/ResponsiveImageBundle/skeleton'
237
        )) {
238
            $skeletonDirs[] = $dir;
239
        }
240
241
        $skeletonDirs[] = __DIR__ . '/../Resources/skeleton';
242
243
        return $skeletonDirs;
244
    }
245
}