This repository has been archived by the owner on Jan 6, 2020. It is now read-only.
/
GenerateBundleCommand.php
421 lines (371 loc) · 16.2 KB
/
GenerateBundleCommand.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\GeneratorBundle\Command;
use Sensio\Bundle\GeneratorBundle\Manipulator\ConfigurationManipulator;
use Sensio\Bundle\GeneratorBundle\Model\Bundle;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\Question;
use Symfony\Component\Console\Question\ConfirmationQuestion;
use Symfony\Component\HttpKernel\KernelInterface;
use Sensio\Bundle\GeneratorBundle\Generator\BundleGenerator;
use Sensio\Bundle\GeneratorBundle\Manipulator\KernelManipulator;
use Sensio\Bundle\GeneratorBundle\Manipulator\RoutingManipulator;
use Sensio\Bundle\GeneratorBundle\Command\Helper\QuestionHelper;
/**
* Generates bundles.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class GenerateBundleCommand extends GeneratorCommand
{
/**
* @see Command
*/
protected function configure()
{
$this
->setDefinition(array(
new InputOption('namespace', '', InputOption::VALUE_REQUIRED, 'The namespace of the bundle to create'),
new InputOption('dir', '', InputOption::VALUE_REQUIRED, 'The directory where to create the bundle', 'src/'),
new InputOption('bundle-name', '', InputOption::VALUE_REQUIRED, 'The optional bundle name'),
new InputOption('format', '', InputOption::VALUE_REQUIRED, 'Use the format for configuration files (php, xml, yml, or annotation)'),
new InputOption('shared', '', InputOption::VALUE_NONE, 'Are you planning on sharing this bundle across multiple applications?'),
))
->setDescription('Generates a bundle')
->setHelp(<<<EOT
The <info>generate:bundle</info> command helps you generates new bundles.
By default, the command interacts with the developer to tweak the generation.
Any passed option will be used as a default value for the interaction
(<comment>--namespace</comment> is the only one needed if you follow the
conventions):
<info>php app/console generate:bundle --namespace=Acme/BlogBundle</info>
Note that you can use <comment>/</comment> instead of <comment>\\ </comment>for the namespace delimiter to avoid any
problems.
If you want to disable any user interaction, use <comment>--no-interaction</comment> but don't forget to pass all needed options:
<info>php app/console generate:bundle --namespace=Acme/BlogBundle --dir=src [--bundle-name=...] --no-interaction</info>
Note that the bundle namespace must end with "Bundle".
EOT
)
->setName('generate:bundle')
;
}
/**
* @see Command
*
* @throws \InvalidArgumentException When namespace doesn't end with Bundle
* @throws \RuntimeException When bundle can't be executed
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$questionHelper = $this->getQuestionHelper();
$bundle = $this->createBundleObject($input);
$questionHelper->writeSection($output, 'Bundle generation');
/** @var BundleGenerator $generator */
$generator = $this->getGenerator();
$output->writeln(sprintf(
'> Generating a sample bundle skeleton into <info>%s</info> <comment>OK!</comment>',
$this->makePathRelative($bundle->getTargetDirectory())
));
$generator->generateBundle($bundle);
$errors = array();
$runner = $questionHelper->getRunner($output, $errors);
// check that the namespace is already autoloaded
$runner($this->checkAutoloader($output, $bundle));
// register the bundle in the Kernel class
$runner($this->updateKernel($output, $this->getContainer()->get('kernel'), $bundle));
// routing importing
$runner($this->updateRouting($output, $bundle));
if (!$bundle->shouldGenerateDependencyInjectionDirectory()) {
// we need to import their services.yml manually!
$runner($this->updateConfiguration($output, $bundle));
}
$questionHelper->writeGeneratorSummary($output, $errors);
}
protected function interact(InputInterface $input, OutputInterface $output)
{
$questionHelper = $this->getQuestionHelper();
$questionHelper->writeSection($output, 'Welcome to the Symfony bundle generator!');
/*
* shared option
*/
$shared = $input->getOption('shared');
// ask, but use $shared as the default
$question = new ConfirmationQuestion($questionHelper->getQuestion(
'Are you planning on sharing this bundle across multiple applications?',
$shared ? 'yes' : 'no'
), $shared);
$shared = $questionHelper->ask($input, $output, $question);
$input->setOption('shared', $shared);
/*
* namespace option
*/
$namespace = $input->getOption('namespace');
$output->writeln(array(
'',
'Your application code must be written in <comment>bundles</comment>. This command helps',
'you generate them easily.',
'',
));
$askForBundleName = true;
if ($shared) {
// a shared bundle, so it should probably have a vendor namespace
$output->writeln(array(
'Each bundle is hosted under a namespace (like <comment>Acme/BlogBundle</comment>).',
'The namespace should begin with a "vendor" name like your company name, your',
'project name, or your client name, followed by one or more optional category',
'sub-namespaces, and it should end with the bundle name itself',
'(which must have <comment>Bundle</comment> as a suffix).',
'',
'See http://symfony.com/doc/current/cookbook/bundles/best_practices.html#bundle-name for more',
'details on bundle naming conventions.',
'',
'Use <comment>/</comment> instead of <comment>\\ </comment> for the namespace delimiter to avoid any problem.',
'',
));
$question = new Question($questionHelper->getQuestion(
'Bundle namespace',
$namespace
), $namespace);
$question->setValidator(function ($answer) {
return Validators::validateBundleNamespace($answer, true);
});
$namespace = $questionHelper->ask($input, $output, $question);
} else {
// a simple application bundle
$output->writeln(array(
'Give your bundle a descriptive name, like <comment>BlogBundle</comment>.',
));
$question = new Question($questionHelper->getQuestion(
'Bundle name',
$namespace
), $namespace);
$question->setValidator(function ($inputNamespace) {
return Validators::validateBundleNamespace($inputNamespace, false);
});
$namespace = $questionHelper->ask($input, $output, $question);
if (strpos($namespace, '\\') === false) {
// this is a bundle name (FooBundle) not a namespace (Acme\FooBundle)
// so this is the bundle name (and it is also the namespace)
$input->setOption('bundle-name', $namespace);
$askForBundleName = false;
}
}
$input->setOption('namespace', $namespace);
/*
* bundle-name option
*/
if ($askForBundleName) {
$bundle = $input->getOption('bundle-name');
// no bundle yet? Get a default from the namespace
if (!$bundle) {
$bundle = strtr($namespace, array('\\Bundle\\' => '', '\\' => ''));
}
$output->writeln(array(
'',
'In your code, a bundle is often referenced by its name. It can be the',
'concatenation of all namespace parts but it\'s really up to you to come',
'up with a unique name (a good practice is to start with the vendor name).',
'Based on the namespace, we suggest <comment>' . $bundle . '</comment>.',
'',
));
$question = new Question($questionHelper->getQuestion(
'Bundle name',
$bundle
), $bundle);
$question->setValidator(
array('Sensio\Bundle\GeneratorBundle\Command\Validators', 'validateBundleName')
);
$bundle = $questionHelper->ask($input, $output, $question);
$input->setOption('bundle-name', $bundle);
}
/*
* dir option
*/
// defaults to src/ in the option
$dir = $input->getOption('dir');
$output->writeln(array(
'',
'Bundles are usually generated into the <info>src/</info> directory. Unless you\'re',
'doing something custom, hit enter to keep this default!',
'',
));
$question = new Question($questionHelper->getQuestion(
'Target Directory',
$dir
), $dir);
$dir = $questionHelper->ask($input, $output, $question);
$input->setOption('dir', $dir);
/*
* format option
*/
$format = $input->getOption('format');
if (!$format) {
$format = $shared ? 'xml' : 'annotation';
}
$output->writeln(array(
'',
'What format do you want to use for your generated configuration?',
'',
));
$question = new Question($questionHelper->getQuestion(
'Configuration format (annotation, yml, xml, php)',
$format
), $format);
$question->setValidator(function ($format) {
return Validators::validateFormat($format);
});
$question->setAutocompleterValues(array('annotation', 'yml', 'xml', 'php'));
$format = $questionHelper->ask($input, $output, $question);
$input->setOption('format', $format);
}
protected function checkAutoloader(OutputInterface $output, Bundle $bundle)
{
$output->write('> Checking that the bundle is autoloaded: ');
if (!class_exists($bundle->getBundleClassName())) {
return array(
'- Edit the <comment>composer.json</comment> file and register the bundle',
' namespace in the "autoload" section:',
'',
);
}
}
protected function updateKernel(OutputInterface $output, KernelInterface $kernel, Bundle $bundle)
{
$kernelManipulator = new KernelManipulator($kernel);
$output->write(sprintf(
'> Enabling the bundle inside <info>%s</info>: ',
$this->makePathRelative($kernelManipulator->getFilename())
));
try {
$ret = $kernelManipulator->addBundle($bundle->getBundleClassName());
if (!$ret) {
$reflected = new \ReflectionObject($kernel);
return array(
sprintf('- Edit <comment>%s</comment>', $reflected->getFilename()),
' and add the following bundle in the <comment>AppKernel::registerBundles()</comment> method:',
'',
sprintf(' <comment>new %s(),</comment>', $bundle->getBundleClassName()),
'',
);
}
} catch (\RuntimeException $e) {
return array(
sprintf('Bundle <comment>%s</comment> is already defined in <comment>AppKernel::registerBundles()</comment>.', $bundle->getBundleClassName()),
'',
);
}
}
protected function updateRouting(OutputInterface $output, Bundle $bundle)
{
$targetRoutingPath = $this->getContainer()->getParameter('kernel.root_dir').'/config/routing.yml';
$output->write(sprintf(
'> Importing the bundle\'s routes from the <info>%s</info> file: ',
$this->makePathRelative($targetRoutingPath)
));
$routing = new RoutingManipulator($targetRoutingPath);
try {
$ret = $routing->addResource($bundle->getName(), $bundle->getConfigurationFormat());
if (!$ret) {
if ('annotation' === $bundle->getConfigurationFormat()) {
$help = sprintf(" <comment>resource: \"@%s/Controller/\"</comment>\n <comment>type: annotation</comment>\n", $bundle->getName());
} else {
$help = sprintf(" <comment>resource: \"@%s/Resources/config/routing.%s\"</comment>\n", $bundle->getName(), $bundle->getConfigurationFormat());
}
$help .= " <comment>prefix: /</comment>\n";
return array(
'- Import the bundle\'s routing resource in the app\'s main routing file:',
'',
sprintf(' <comment>%s:</comment>', $bundle->getName()),
$help,
'',
);
}
} catch (\RuntimeException $e) {
return array(
sprintf('Bundle <comment>%s</comment> is already imported.', $bundle->getName()),
'',
);
}
}
protected function updateConfiguration(OutputInterface $output, Bundle $bundle)
{
$targetConfigurationPath = $this->getContainer()->getParameter('kernel.root_dir').'/config/config.yml';
$output->write(sprintf(
'> Importing the bundle\'s %s from the <info>%s</info> file: ',
$bundle->getServicesConfigurationFilename(),
$this->makePathRelative($targetConfigurationPath)
));
$manipulator = new ConfigurationManipulator($targetConfigurationPath);
try {
$manipulator->addResource($bundle);
} catch (\RuntimeException $e) {
return array(
'- Import the bundle\'s %s resource in the app\'s main configuration file:',
'',
$manipulator->getImportCode($bundle),
'',
);
}
}
/**
* Creates the Bundle object based on the user's (non-interactive) input
*
* @param InputInterface $input
* @return Bundle
*/
protected function createBundleObject(InputInterface $input)
{
foreach (array('namespace', 'dir') as $option) {
if (null === $input->getOption($option)) {
throw new \RuntimeException(sprintf('The "%s" option must be provided.', $option));
}
}
$shared = $input->getOption('shared');
$namespace = Validators::validateBundleNamespace($input->getOption('namespace'), $shared);
if (!$bundleName = $input->getOption('bundle-name')) {
$bundleName = strtr($namespace, array('\\' => ''));
}
$bundleName = Validators::validateBundleName($bundleName);
$dir = $input->getOption('dir');
if (null === $input->getOption('format')) {
$input->setOption('format', 'annotation');
}
$format = Validators::validateFormat($input->getOption('format'));
if (!$this->getContainer()->get('filesystem')->isAbsolutePath($dir)) {
$dir = getcwd().'/'.$dir;
}
// add trailing / if necessary
$dir = '/' === substr($dir, -1, 1) ? $dir : $dir.'/';
return new Bundle(
$namespace,
$bundleName,
$dir,
$format,
$shared
);
}
/**
* Tries to make a path relative to the project, which prints nicer
*
* @param string $absolutePath
* @return string
*/
protected function makePathRelative($absolutePath)
{
$projectRootDir = dirname($this->getContainer()->getParameter('kernel.root_dir'));
return str_replace($projectRootDir.'/', '', $absolutePath);
}
protected function createGenerator()
{
return new BundleGenerator($this->getContainer()->get('filesystem'));
}
}