GenerateImageEntityCommand   A
last analyzed

Complexity

Total Complexity 22

Size/Duplication

Total Lines 268
Duplicated Lines 4.1 %

Coupling/Cohesion

Components 1
Dependencies 11

Importance

Changes 0
Metric Value
wmc 22
lcom 1
cbo 11
dl 11
loc 268
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 1
A configure() 0 56 4
D interact() 0 98 9
B execute() 11 35 4
A createGenerator() 0 7 1
B createYesNoQuestion() 0 33 3

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\Generator\ImageEntityGenerator;
14
use IrishDan\ResponsiveImageBundle\ImageEntityNameResolver;
15
use Sensio\Bundle\GeneratorBundle\Command\GeneratorCommand;
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\Console\Style\SymfonyStyle;
22
23
24
/**
25
 * Class CreateImageEntityCommand
26
 *
27
 * @package IrishDan\ResponsiveImageBundle\Command
28
 */
29
class GenerateImageEntityCommand extends GeneratorCommand
30
{
31
    protected $entityNameResolver;
32
    protected $responsiveImageEntity;
33
    protected $bundle;
34
    protected $entityName;
35
    protected $doctrine;
36
    protected $classExists;
37
    protected $needsOverWritePermission = false;
38
    protected $overwrite = false;
39
40
    public function __construct(ImageEntityNameResolver $entityNameResolver, $doctrine)
41
    {
42
        $this->entityNameResolver    = $entityNameResolver;
43
        $this->doctrine              = $doctrine;
44
        $this->responsiveImageEntity = $entityNameResolver->getClassName();
45
        $this->classExists           = $entityNameResolver->classExists();
46
47
        parent::__construct();
48
    }
49
50
    protected function configure()
51
    {
52
        // Limit generation to One entity for now!
53
        // We are checking two things:
54
        // If entity class name is set
55
        // If the class exists
56
57
        // @TODO: Would be good to ask for additional fields.
58
59
        $this
60
            ->setName('responsive_image:generate:entity')
61
            ->setDescription('Creates the Responsive Image entity, ' . $this->responsiveImageEntity);
62
63
        // If the Classname is not set we need to ask for it
64
        if (empty($this->responsiveImageEntity)) {
65
            $this
66
                ->setDefinition(
67
                    [
68
                        new InputOption('bundle', '', InputOption::VALUE_REQUIRED, 'The bundle for this entity'),
69
                        new InputOption('entity_name', '', InputOption::VALUE_REQUIRED, 'The name of the entity'),
70
                    ]
71
                );
72
        }
73
        // The classname is set and and the entity already exists
74
        elseif ($this->classExists) {
75
            $this->needsOverWritePermission = true;
76
77
            // Needs to have the entityName and bundle properties set
78
            // @TODO:Is there a nicer way to do this?
79
            $em        = $this->doctrine->getManager();
80
            $metadata  = $em->getClassMetadata($this->responsiveImageEntity);
81
            $namespace = $metadata->namespace;
82
83
            // This is bit hacky but it'll do for now.
84
            // Lets get rid of the '\Entity'.
85
            if (strpos($namespace, '\\Entity') > 0) {
86
                $namespace = substr($namespace, 0, -7);
87
            }
88
89
            $namespaceParts   = explode('\\', $namespace);
90
            $this->bundle     = array_pop($namespaceParts);
91
            $entityNameParts  = explode('\\', $this->responsiveImageEntity);
92
            $this->entityName = array_pop($entityNameParts);
93
94
            $this
95
                ->setDefinition(
96
                    [
97
                        new InputOption(
98
                            'overwrite', '', InputOption::VALUE_NONE, 'Overwrite the existing image entity'
99
                        ),
100
                    ]
101
                );
102
        }
103
        // The classname is set but the entity does not exist.
104
        // We don't need any options for this, simple generate based on the defined classname
105
    }
106
107
    /**
108
     * @param InputInterface  $input
109
     * @param OutputInterface $output
110
     */
111
    protected function interact(InputInterface $input, OutputInterface $output)
112
    {
113
        $questionHelper = $this->getQuestionHelper();
114
        $questionHelper->writeSection($output, 'Welcome to the Image entity generator');
115
116
        $message = [
117
            'This Currently only supports one Image entity',
118
            '',
119
        ];
120
121
        // If entity already exists,
122
        // get overwrite permission
123
        if ($this->needsOverWritePermission) {
124
            $message[] = sprintf('It looks like the image entity exists as %s', $this->responsiveImageEntity);
125
            $message[] = '';
126
            $message[] = sprintf(
127
                'Therefore this generator will overwrite that class, %s',
128
                $this->responsiveImageEntity
129
            );
130
131
            $output->writeln($message);
132
133
            // Ask whether overwrite is allowed
134
            $question  = $this->createYesNoQuestion($questionHelper, $this->responsiveImageEntity);
135
            $overwrite = $questionHelper->ask($input, $output, $question);
136
137
            if ($overwrite !== 'y') {
138
                throw new \RuntimeException(
139
                    'Aborting, overwrite permission is needed.'
140
                );
141
            }
142
            else {
143
                $this->overwrite = true;
144
            }
145
        }
146
        // If class name is not set,
147
        // Ask the bundle and the entity name questions
148
        elseif (empty($this->responsiveImageEntity)) {
149
            $question = new Question(
150
                $questionHelper->getQuestion('The bundle name', $input->getOption('bundle')),
151
                $input->getOption('bundle')
152
            );
153
154
            $question->setValidator(['Sensio\Bundle\GeneratorBundle\Command\Validators', 'validateBundleName']);
155
            $question->setNormalizer(
156
                function ($value) {
157
                    return $value ? trim($value) : '';
158
                }
159
            );
160
            $question->setMaxAttempts(2);
161
162
            $bundle = $questionHelper->ask($input, $output, $question);
163
            $input->setOption('bundle', $bundle);
164
165
            // Get the Bundle to generate it in
166
            $output->writeln(
167
                [
168
                    '',
169
                    'Now, give the name of the new entity class (eg <comment>Image</comment>)',
170
                ]
171
            );
172
173
            // Get the new class name and validate it.
174
            $question = new Question(
175
                $questionHelper->getQuestion('The entity name', $input->getOption('entity_name')),
176
                $input->getOption('entity_name')
177
            );
178
            $question->setValidator(
179
                function ($answer) {
180
                    // Should only contain letters.
181
                    $valid = preg_match('/^[a-zA-Z]+$/', $answer);
182
                    if (!$valid) {
183
                        throw new \RuntimeException(
184
                            'The class name should only contain letters'
185
                        );
186
                    }
187
188
                    return $answer;
189
                }
190
            );
191
            $question->setNormalizer(
192
                function ($value) {
193
                    return $value ? trim($value) : '';
194
                }
195
            );
196
197
            $notificationName = $questionHelper->ask($input, $output, $question);
198
            $input->setOption('entity_name', $notificationName);
199
        }
200
        // Should be all ready to generate
201
202
        // At the end we need the bundle and the entity
203
        if (empty($this->entityName) || empty($this->bundle)) {
204
            throw new \RuntimeException(
205
                'Required options have not been set'
206
            );
207
        }
208
    }
209
210
    /**
211
     * @param InputInterface  $input
212
     * @param OutputInterface $output
213
     *
214
     * @return int
215
     */
216
    protected function execute(InputInterface $input, OutputInterface $output)
217
    {
218
        $questionHelper = $this->getQuestionHelper();
219
220 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...
221
            $question = new ConfirmationQuestion(
222
                $questionHelper->getQuestion('Do you confirm generation', 'yes', '?'),
223
                true
224
            );
225
            if (!$questionHelper->ask($input, $output, $question)) {
226
                $output->writeln('<error>Command aborted</error>');
227
228
                return 1;
229
            }
230
        }
231
232
        $style = new SymfonyStyle($input, $output);
233
234
        $bundle = $this->bundle;
235
        $name   = $this->entityName;
236
237
        $style->text('Generating New doctrine entity class ' . $name . ' generated in ' . $bundle);
238
239
        try {
240
            $bundle = $this->getContainer()->get('kernel')->getBundle($bundle);
241
        } catch (\Exception $e) {
242
            $output->writeln(sprintf('<bg=red>Bundle "%s" does not exist.</>', $bundle));
243
        }
244
245
        $generator = $this->getGenerator($bundle);
246
        $generator->generate($bundle, $name);
247
248
        $output->writeln(sprintf('Generated the <info>%s</info> entity in <info>%s</info>', $name, $bundle->getName()));
249
        $questionHelper->writeGeneratorSummary($output, []);
250
    }
251
252
    /**
253
     * @return ImageEntityGenerator
254
     */
255
    protected function createGenerator()
256
    {
257
        return new ImageEntityGenerator(
258
            $this->getContainer()->get('filesystem'),
259
            $this->overwrite
260
        );
261
    }
262
263
    protected function createYesNoQuestion($questionHelper, $entity)
264
    {
265
        $question = new Question(
266
            $questionHelper->getQuestion(
267
                'Overwrite the existing image entity ' . $entity . '? <comment>[yes]</comment>',
268
                'overwrite'
269
            ), 'yes'
270
        );
271
        $question->setNormalizer(
272
            function ($value) {
273
                return $value[0] == 'y' ? 'y' : 'n';
274
            }
275
        );
276
        $question->setValidator(
277
            function ($answer) {
278
                // Should only contain letters.
279
                $allowed = [
280
                    'y',
281
                    'n',
282
                ];
283
                $valid   = in_array($answer, $allowed);
284
                if (!$valid) {
285
                    throw new \RuntimeException(
286
                        'Only allowed values are ' . implode(', ', $allowed)
287
                    );
288
                }
289
290
                return $answer;
291
            }
292
        );
293
294
        return $question;
295
    }
296
}