GenerateAdminCommand::updateKernel()   A
last analyzed

Complexity

Conditions 3
Paths 5

Size

Total Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 29
rs 9.456
c 0
b 0
f 0
cc 3
nc 5
nop 3
1
<?php
2
3
namespace Admingenerator\GeneratorBundle\Command;
4
5
use Admingenerator\GeneratorBundle\Routing\Manipulator\RoutingManipulator;
6
use Admingenerator\GeneratorBundle\Generator\BundleGenerator;
7
use Sensio\Bundle\GeneratorBundle\Manipulator\KernelManipulator;
8
use Sensio\Bundle\GeneratorBundle\Model\Bundle;
9
use Sensio\Bundle\GeneratorBundle\Command\GeneratorCommand;
10
use Symfony\Component\Console\Input\InputInterface;
11
use Symfony\Component\Console\Input\InputOption;
12
use Symfony\Component\Console\Output\OutputInterface;
13
use Sensio\Bundle\GeneratorBundle\Command\Validators;
14
use Symfony\Component\Console\Question\ChoiceQuestion;
15
use Symfony\Component\Console\Question\ConfirmationQuestion;
16
use Symfony\Component\Console\Question\Question;
17
use Symfony\Component\HttpKernel\KernelInterface;
18
19
class GenerateAdminCommand extends GeneratorCommand
20
{
21
    protected function configure()
22
    {
23
        $this
24
            ->setName('admin:generate-admin')
25
            ->setDescription('Generate new admin pages given a model')
26
            ->setDefinition(array(
27
                new InputOption('namespace', '', InputOption::VALUE_REQUIRED, 'The namespace of the bundle to use'),
28
                new InputOption('dir', '', InputOption::VALUE_REQUIRED, 'The directory where the bundle is', 'src/'),
29
                new InputOption('bundle-name', '', InputOption::VALUE_REQUIRED, 'The bundle name'),
30
                new InputOption('generator', '', InputOption::VALUE_REQUIRED, 'The generator service (propel, doctrine, doctrine_odm)', 'doctrine'),
31
                new InputOption('model-name', '', InputOption::VALUE_REQUIRED, 'Base model name for admin module, without namespace.', 'YourModel'),
32
                new InputOption('prefix', '', InputOption::VALUE_REQUIRED, 'The generator prefix ([prefix]-generator.yml)'),
33
34
            ))
35
            ->setHelp(<<<EOT
36
The <info>admin:generate-admin</info> command helps you generates new admin pages for a given model.
37
This command creates the bundle and register it if it doesn't exists.
38
39
By default, the command interacts with the developer to tweak the generation.
40
Any passed option will be used as a default value for the interaction.
41
42
If you want to disable any user interaction, use <comment>--no-interaction</comment> but don't forget to pass all needed options.
43
44
Note that the bundle namespace must end with "Bundle".
45
EOT
46
            )
47
        ;
48
    }
49
    protected function interact(InputInterface $input, OutputInterface $output)
50
    {
51
        $questionHelper = $this->getQuestionHelper();
52
        $questionHelper->writeSection($output, 'Welcome to the Symfony2Admingenerator');
53
54
        /*
55
         * Namespace option
56
         */
57
        $askForBundleName = true;
58
        $namespace = $input->getOption('namespace');
59
        $output->writeln(array(
60
            '',
61
            'Precise the full bundle namespace where you want to generate files (including vendor name if any)',
62
            ''
63
        ));
64
65
        $question = new Question($questionHelper->getQuestion(
66
            'Fully qualified bundle name',
67
            $namespace
68
        ), $namespace);
69
        $question->setValidator(function ($inputNamespace) {
70
            return Validators::validateBundleNamespace($inputNamespace, false);
71
        });
72
        $namespace = $questionHelper->ask($input, $output, $question);
73
74
        if (strpos($namespace, '\\') === false) {
75
            // this is a bundle name (FooBundle) not a namespace (Acme\FooBundle)
76
            // so this is the bundle name (and it is also the namespace)
77
            $input->setOption('bundle-name', $namespace);
78
            $askForBundleName = false;
79
        }
80
        $input->setOption('namespace', $namespace);
81
82
        /*
83
         * bundle-name option
84
         */
85
        if ($askForBundleName) {
86
            $bundle = $input->getOption('bundle-name');
87
            // no bundle yet? Get a default from the namespace
88
            if (!$bundle) {
89
                $bundle = strtr($namespace, array('\\Bundle\\' => '', '\\' => ''));
90
            }
91
92
            $output->writeln(array(
93
                '',
94
                'Please specify the Bundle name.',
95
                'Based on the namespace, we suggest <comment>'.$bundle.'</comment>.',
96
                '',
97
            ));
98
            $question = new Question($questionHelper->getQuestion(
99
                'Bundle name',
100
                $bundle
101
            ), $bundle);
102
            $question->setValidator(function($bundleName){
103
                return Validators::validateBundleName($bundleName);
104
            });
105
            $bundle = $questionHelper->ask($input, $output, $question);
106
            $input->setOption('bundle-name', $bundle);
107
        }
108
109
        /*
110
         * dir option
111
         */
112
        // defaults to src/ in the option
113
        $dir = $input->getOption('dir');
114
        $output->writeln(array(
115
            '',
116
            'Bundles are usually generated into the <info>src/</info> directory. Unless you\'re',
117
            'doing something custom, hit enter to keep this default!',
118
            '',
119
        ));
120
121
        $question = new Question($questionHelper->getQuestion(
122
            'Target Directory',
123
            $dir
124
        ), $dir);
125
        $dir = $questionHelper->ask($input, $output, $question);
126
        $input->setOption('dir', $dir);
127
128
129
        /*
130
         * Generator option
131
         */
132
        $generator = $input->getOption('generator');
133
        $output->writeln(array(
134
            '',
135
            'What database manager are you using?',
136
            ''
137
        ));
138
139
        $question = new Question($questionHelper->getQuestion(
140
            'Generator (doctrine, doctrine_odm, propel)',
141
            $generator
142
        ), $generator);
143
        $question->setValidator(function($generator){
144
            if (!in_array($generator, array('doctrine', 'doctrine_odm', 'propel'))) {
145
                throw new \InvalidArgumentException('Use a valid generator.');
146
            }
147
148
            return $generator;
149
        });
150
        $question->setAutocompleterValues(array('doctrine', 'doctrine_odm', 'propel'));
0 ignored issues
show
Documentation introduced by
array('doctrine', 'doctrine_odm', 'propel') is of type array<integer,string,{"0..."string","2":"string"}>, but the function expects a object<Symfony\Component...Question\iterable>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
151
        $generator = $questionHelper->ask($input, $output, $question);
152
        $input->setOption('generator', $generator);
153
154
155
        /*
156
         * Model name option
157
         */
158
        $modelName = $input->getOption('model-name');
159
        $output->writeln(array(
160
            '',
161
            'What is the model name you want to generate files for?',
162
            ''
163
        ));
164
        $question = new Question($questionHelper->getQuestion(
165
            'Model name',
166
            $modelName
167
        ), $modelName);
168
        $question->setValidator(function ($modelName) {
169
            if (empty($modelName) || preg_match('#[^a-zA-Z0-9]#', $modelName)) {
170
                throw new \InvalidArgumentException('Model name should not contain any special characters nor spaces.');
171
            }
172
173
            return $modelName;
174
        });
175
        $modelName = $questionHelper->ask($input, $output, $question);
176
        $input->setOption('model-name', $modelName);
177
178
        /*
179
         * Prefix option
180
         */
181
        $prefix = $input->getOption('prefix');
182
        $output->writeln(array(
183
            '',
184
            'Please precise a prefix to use for YAML generator file',
185
            ''
186
        ));
187
        if (!$prefix) {
188
            $prefix = preg_replace('/[0-9]/', '', $modelName);
189
        }
190
        $question = new Question($questionHelper->getQuestion(
191
            'Prefix of yaml',
192
            $prefix
193
        ), $prefix);
194
        $question->setValidator(function ($prefix) {
195
            if (!preg_match('/([a-z]+)/i', $prefix)) {
196
                throw new \RuntimeException('Prefix have to be a simple word');
197
            }
198
            return $prefix;
199
        });
200
        $prefix = $questionHelper->ask($input, $output, $question);
201
        $input->setOption('prefix', $prefix);
202
    }
203
204
    /**
205
     * @param InputInterface $input
206
     * @param OutputInterface $output
207
     * @return int|null|void
208
     */
209
    protected function execute(InputInterface $input, OutputInterface $output)
210
    {
211
        $questionHelper = $this->getQuestionHelper();
212
213
        $bundle = $this->createBundleObject($input);
214
        $questionHelper->writeSection($output, 'Bundle generation');
215
216
        $generator = $this->createGenerator();
217
        $generator->setGenerator($input->getOption('generator'));
218
        $generator->setPrefix($input->getOption('prefix'));
219
        $generator->generate(
220
            $bundle,
221
            $input->getOption('model-name')
222
        );
223
224
        $output->writeln('Generating the bundle code: <info>OK</info>');
225
226
        $errors = array();
227
        $runner = $questionHelper->getRunner($output, $errors);
228
229
        // check that the namespace is already autoloaded
230
        $runner($this->checkAutoloader($output, $bundle));
231
232
        // register the bundle in the Kernel class
233
        $runner($this->updateKernel($output, $this->getContainer()->get('kernel'), $bundle));
234
235
        // routing
236
        $runner($this->updateRouting($input, $output, $bundle, $input->getOption('prefix')));
237
238
        $questionHelper->writeGeneratorSummary($output, $errors);
239
    }
240
241
    protected function createGenerator()
242
    {
243
        return new BundleGenerator($this->getContainer()->get('filesystem'), __DIR__.'/../Resources/skeleton/bundle');
244
    }
245
246
    /**
247
     * @param OutputInterface $output
248
     * @param Bundle $bundle
249
     * @return array
250
     */
251
    protected function checkAutoloader(OutputInterface $output, Bundle $bundle)
252
    {
253
        $output->write('> Checking that the bundle is autoloaded: ');
254
        if (!class_exists($bundle->getBundleClassName())) {
255
            return array(
256
                '- Edit the <comment>composer.json</comment> file and register the bundle',
257
                '  namespace in the "autoload" section.',
258
                '',
259
            );
260
        }
261
262
        return array();
263
    }
264
265
    protected function updateKernel(OutputInterface $output, KernelInterface $kernel, Bundle $bundle)
266
    {
267
        $kernelManipulator = new KernelManipulator($kernel);
268
269
        $output->write(sprintf(
270
            '> Enabling the bundle inside <info>%s</info>: ',
271
            $this->makePathRelative($kernelManipulator->getFilename())
272
        ));
273
274
        try {
275
            $ret = $kernelManipulator->addBundle($bundle->getBundleClassName());
276
277
            if (!$ret) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $ret of type boolean|null is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
278
                $reflected = new \ReflectionObject($kernel);
279
280
                return array(
281
                    sprintf('- Edit <comment>%s</comment>', $reflected->getFilename()),
282
                    '  and add the following bundle in the <comment>AppKernel::registerBundles()</comment> method:',
283
                    '',
284
                    sprintf('    <comment>new %s(),</comment>', $bundle->getBundleClassName()),
285
                    '',
286
                );
287
            }
288
        } catch (\RuntimeException $e) {
289
            // Bundle already registered, this is not an error
290
        }
291
292
        return array();
293
    }
294
295
    /**
296
     * @param InputInterface $input
297
     * @param OutputInterface $output
298
     * @param Bundle $bundle
299
     * @param $prefix
300
     * @return array|void
301
     */
302
    protected function updateRouting(InputInterface $input, OutputInterface $output, Bundle $bundle, $prefix)
303
    {
304
        $questionHelper = $this->getQuestionHelper();
305
        $question = new ChoiceQuestion(
306
            'Which routing file would you like to update?',
307
            array(
308
                'base' => '::routing.yml',
309
                'bundle' => sprintf('%s:Resources:%s', $bundle->getName(), $bundle->getRoutingConfigurationFilename()),
310
                'none' => 'Do not update any file.'
311
            ),
312
            'base'
313
        );
314
315
        $routingFile = $questionHelper->ask($input, $output, $question);
316
317
        if ('none' == $routingFile) {
318
            return array();
319
        }
320
321
        if ('base' == $routingFile) {
322
            $targetRoutingPath = $this->getContainer()->getParameter('kernel.root_dir').'/config/routing.yml';
323
        } else {
324
            $targetRoutingPath = sprintf('%s/Resources/config/%s', $bundle->getTargetDirectory(), $bundle->getRoutingConfigurationFilename());
325
        }
326
327
        $output->write(sprintf(
328
            '> Importing the bundle\'s routes from the <info>%s</info> file: ',
329
            $this->makePathRelative($targetRoutingPath)
330
        ));
331
        $routing = new RoutingManipulator($targetRoutingPath);
332
        $routing->setYamlPrefix($prefix);
333
334
        try {
335
            $ret = $routing->addResource($bundle->getName(), 'admingenerator');
336
            if (!$ret) {
337
                $help = sprintf("        <comment>resource: \"@%s/Controller/%s/\"</comment>\n        <comment>type:     admingenerator</comment>\n", $bundle->getName(), ucfirst($prefix));
338
                $help .= "        <comment>prefix:   /</comment>\n";
339
340
                return array(
341
                    '- Import the bundle\'s routing resource in the app main routing file:',
342
                    '',
343
                    sprintf('    <comment>%s:</comment>', $bundle->getName()),
344
                    $help,
345
                    '',
346
                );
347
            }
348
        } catch (\RuntimeException $e) {
349
            return array(
350
                sprintf('Bundle <comment>%s</comment> is already imported.', $bundle->getName()),
351
                '',
352
            );
353
        }
354
355
        return array();
356
    }
357
358
    /**
359
     * Creates the Bundle object based on the user's (non-interactive) input.
360
     *
361
     * @param InputInterface $input
362
     *
363
     * @return Bundle
364
     */
365
    protected function createBundleObject(InputInterface $input)
366
    {
367
        foreach (array('namespace', 'dir') as $option) {
368
            if (null === $input->getOption($option)) {
369
                throw new \RuntimeException(sprintf('The "%s" option must be provided.', $option));
370
            }
371
        }
372
373
        $namespace = Validators::validateBundleNamespace($input->getOption('namespace'), false);
374
        if (!$bundleName = $input->getOption('bundle-name')) {
375
            $bundleName = strtr($namespace, array('\\' => ''));
376
        }
377
        $bundleName = Validators::validateBundleName($bundleName);
378
        $dir = $input->getOption('dir');
379
380
        if (!$this->getContainer()->get('filesystem')->isAbsolutePath($dir)) {
381
            $dir = getcwd().'/'.$dir;
382
        }
383
        // add trailing / if necessary
384
        $dir = '/' === substr($dir, -1, 1) ? $dir : $dir.'/';
385
386
        return new Bundle(
387
            $namespace,
388
            $bundleName,
389
            $dir,
390
            'yml',
391
            false // unused
392
        );
393
    }
394
}
395