feature #23887 [Console] Allow commands to provide a default name for compile time registration (chalasr, nicolas-grekas)

This PR was merged into the 3.4 branch.

Discussion
----------

[Console] Allow commands to provide a default name for compile time registration

| Q             | A
| ------------- | ---
| Branch?       | 3.4
| Bug fix?      | no
| New feature?  | yes
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | #23796
| License       | MIT
| Doc PR        | https://github.com/symfony/symfony-docs/issues/8147

Commits
-------

eda7d42955 [Console] Add protected static $defaultName to set the default name of a Command
5d9ae6b56f [Console] Allow commands to provide a default name for compile time registration
This commit is contained in:
Fabien Potencier 2017-08-24 14:10:36 -07:00
commit 67abb80498
32 changed files with 130 additions and 45 deletions

View File

@ -26,6 +26,8 @@ use Twig\Environment;
*/
class DebugCommand extends Command
{
protected static $defaultName = 'debug:twig';
private $twig;
/**
@ -66,7 +68,6 @@ class DebugCommand extends Command
protected function configure()
{
$this
->setName('debug:twig')
->setDefinition(array(
new InputArgument('filter', InputArgument::OPTIONAL, 'Show details for all entries matching this filter'),
new InputOption('format', null, InputOption::VALUE_REQUIRED, 'The output format (text or json)', 'text'),

View File

@ -31,6 +31,8 @@ use Twig\Source;
*/
class LintCommand extends Command
{
protected static $defaultName = 'lint:twig';
private $twig;
/**
@ -71,7 +73,6 @@ class LintCommand extends Command
protected function configure()
{
$this
->setName('lint:twig')
->setDescription('Lints a template and outputs encountered errors')
->addOption('format', null, InputOption::VALUE_REQUIRED, 'The output format', 'txt')
->addArgument('filename', InputArgument::IS_ARRAY)

View File

@ -33,13 +33,14 @@
"symfony/security": "~2.8|~3.0|~4.0",
"symfony/security-acl": "~2.8|~3.0",
"symfony/stopwatch": "~2.8|~3.0|~4.0",
"symfony/console": "~2.8|~3.0|~4.0",
"symfony/console": "~3.4|~4.0",
"symfony/var-dumper": "~2.8.10|~3.1.4|~3.2|~4.0",
"symfony/expression-language": "~2.8|~3.0|~4.0",
"symfony/web-link": "~3.3|~4.0"
},
"conflict": {
"symfony/form": "<3.2.10|~3.3,<3.3.3"
"symfony/form": "<3.2.10|~3.3,<3.3.3",
"symfony/console": "<3.4"
},
"suggest": {
"symfony/finder": "",

View File

@ -28,15 +28,14 @@ use Symfony\Component\HttpKernel\KernelInterface;
*/
class AboutCommand extends ContainerAwareCommand
{
protected static $defaultName = 'about';
/**
* {@inheritdoc}
*/
protected function configure()
{
$this
->setName('about')
->setDescription('Displays information about the current project')
;
$this->setDescription('Displays information about the current project');
}
/**

View File

@ -35,6 +35,8 @@ class AssetsInstallCommand extends ContainerAwareCommand
const METHOD_ABSOLUTE_SYMLINK = 'absolute symlink';
const METHOD_RELATIVE_SYMLINK = 'relative symlink';
protected static $defaultName = 'assets:install';
private $filesystem;
/**
@ -61,7 +63,6 @@ class AssetsInstallCommand extends ContainerAwareCommand
protected function configure()
{
$this
->setName('assets:install')
->setDefinition(array(
new InputArgument('target', InputArgument::OPTIONAL, 'The target directory', 'public'),
))

View File

@ -32,6 +32,8 @@ use Symfony\Component\Finder\Finder;
*/
class CacheClearCommand extends ContainerAwareCommand
{
protected static $defaultName = 'cache:clear';
private $cacheClearer;
private $filesystem;
private $warning;
@ -62,7 +64,6 @@ class CacheClearCommand extends ContainerAwareCommand
protected function configure()
{
$this
->setName('cache:clear')
->setDefinition(array(
new InputOption('no-warmup', '', InputOption::VALUE_NONE, 'Do not warm up the cache'),
new InputOption('no-optional-warmers', '', InputOption::VALUE_NONE, 'Skip optional cache warmers (faster)'),

View File

@ -25,6 +25,8 @@ use Symfony\Component\HttpKernel\CacheClearer\Psr6CacheClearer;
*/
final class CachePoolClearCommand extends ContainerAwareCommand
{
protected static $defaultName = 'cache:pool:clear';
private $poolClearer;
/**
@ -51,7 +53,6 @@ final class CachePoolClearCommand extends ContainerAwareCommand
protected function configure()
{
$this
->setName('cache:pool:clear')
->setDefinition(array(
new InputArgument('pools', InputArgument::IS_ARRAY | InputArgument::REQUIRED, 'A list of cache pools or cache pool clearers'),
))

View File

@ -24,6 +24,8 @@ use Symfony\Component\Console\Style\SymfonyStyle;
*/
final class CachePoolPruneCommand extends Command
{
protected static $defaultName = 'cache:pool:prune';
private $pools;
/**
@ -42,7 +44,6 @@ final class CachePoolPruneCommand extends Command
protected function configure()
{
$this
->setName('cache:pool:prune')
->setDescription('Prune cache pools')
->setHelp(<<<'EOF'
The <info>%command.name%</info> command deletes all expired items from all pruneable pools.

View File

@ -26,6 +26,8 @@ use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerAggregate;
*/
class CacheWarmupCommand extends ContainerAwareCommand
{
protected static $defaultName = 'cache:warmup';
private $cacheWarmer;
/**
@ -52,7 +54,6 @@ class CacheWarmupCommand extends ContainerAwareCommand
protected function configure()
{
$this
->setName('cache:warmup')
->setDefinition(array(
new InputOption('no-optional-warmers', '', InputOption::VALUE_NONE, 'Skip optional cache warmers (faster)'),
))

View File

@ -28,13 +28,14 @@ use Symfony\Component\Yaml\Yaml;
*/
class ConfigDebugCommand extends AbstractConfigCommand
{
protected static $defaultName = 'debug:config';
/**
* {@inheritdoc}
*/
protected function configure()
{
$this
->setName('debug:config')
->setDefinition(array(
new InputArgument('name', InputArgument::OPTIONAL, 'The bundle name or the extension alias'),
new InputArgument('path', InputArgument::OPTIONAL, 'The configuration option path'),

View File

@ -30,13 +30,14 @@ use Symfony\Component\Console\Style\SymfonyStyle;
*/
class ConfigDumpReferenceCommand extends AbstractConfigCommand
{
protected static $defaultName = 'config:dump-reference';
/**
* {@inheritdoc}
*/
protected function configure()
{
$this
->setName('config:dump-reference')
->setDefinition(array(
new InputArgument('name', InputArgument::OPTIONAL, 'The Bundle name or the extension alias'),
new InputArgument('path', InputArgument::OPTIONAL, 'The configuration option path'),

View File

@ -32,6 +32,8 @@ use Symfony\Component\Config\FileLocator;
*/
class ContainerDebugCommand extends ContainerAwareCommand
{
protected static $defaultName = 'debug:container';
/**
* @var ContainerBuilder|null
*/
@ -43,7 +45,6 @@ class ContainerDebugCommand extends ContainerAwareCommand
protected function configure()
{
$this
->setName('debug:container')
->setDefinition(array(
new InputArgument('name', InputArgument::OPTIONAL, 'A service name (foo)'),
new InputOption('show-private', null, InputOption::VALUE_NONE, 'Used to show public *and* private services'),

View File

@ -28,6 +28,7 @@ use Symfony\Component\EventDispatcher\EventDispatcherInterface;
*/
class EventDispatcherDebugCommand extends ContainerAwareCommand
{
protected static $defaultName = 'debug:event-dispatcher';
private $dispatcher;
/**
@ -54,7 +55,6 @@ class EventDispatcherDebugCommand extends ContainerAwareCommand
protected function configure()
{
$this
->setName('debug:event-dispatcher')
->setDefinition(array(
new InputArgument('event', InputArgument::OPTIONAL, 'An event name'),
new InputOption('format', null, InputOption::VALUE_REQUIRED, 'The output format (txt, xml, json, or md)', 'txt'),

View File

@ -32,6 +32,7 @@ use Symfony\Component\Routing\Route;
*/
class RouterDebugCommand extends ContainerAwareCommand
{
protected static $defaultName = 'debug:router';
private $router;
/**
@ -79,7 +80,6 @@ class RouterDebugCommand extends ContainerAwareCommand
protected function configure()
{
$this
->setName('debug:router')
->setDefinition(array(
new InputArgument('name', InputArgument::OPTIONAL, 'A route name'),
new InputOption('show-controllers', null, InputOption::VALUE_NONE, 'Show assigned controllers in overview'),

View File

@ -29,6 +29,8 @@ use Symfony\Component\Routing\Matcher\TraceableUrlMatcher;
*/
class RouterMatchCommand extends ContainerAwareCommand
{
protected static $defaultName = 'router:match';
private $router;
/**
@ -76,7 +78,6 @@ class RouterMatchCommand extends ContainerAwareCommand
protected function configure()
{
$this
->setName('router:match')
->setDefinition(array(
new InputArgument('path_info', InputArgument::REQUIRED, 'A path info'),
new InputOption('method', null, InputOption::VALUE_REQUIRED, 'Sets the HTTP method'),

View File

@ -40,6 +40,8 @@ class TranslationDebugCommand extends ContainerAwareCommand
const MESSAGE_UNUSED = 1;
const MESSAGE_EQUALS_FALLBACK = 2;
protected static $defaultName = 'debug:translation';
private $translator;
private $loader;
private $extractor;
@ -72,7 +74,6 @@ class TranslationDebugCommand extends ContainerAwareCommand
protected function configure()
{
$this
->setName('debug:translation')
->setDefinition(array(
new InputArgument('locale', InputArgument::REQUIRED, 'The locale'),
new InputArgument('bundle', InputArgument::OPTIONAL, 'The bundle name or directory where to load the messages, defaults to app/Resources folder'),

View File

@ -33,6 +33,8 @@ use Symfony\Component\Translation\Writer\TranslationWriterInterface;
*/
class TranslationUpdateCommand extends ContainerAwareCommand
{
protected static $defaultName = 'translation:update';
private $writer;
private $loader;
private $extractor;
@ -68,7 +70,6 @@ class TranslationUpdateCommand extends ContainerAwareCommand
protected function configure()
{
$this
->setName('translation:update')
->setDefinition(array(
new InputArgument('locale', InputArgument::REQUIRED, 'The locale'),
new InputArgument('bundle', InputArgument::OPTIONAL, 'The bundle name or directory where to load the messages, defaults to app/Resources folder'),

View File

@ -25,6 +25,8 @@ use Symfony\Component\Workflow\Marking;
*/
class WorkflowDumpCommand extends ContainerAwareCommand
{
protected static $defaultName = 'workflow:dump';
/**
* {@inheritdoc}
*
@ -41,7 +43,6 @@ class WorkflowDumpCommand extends ContainerAwareCommand
protected function configure()
{
$this
->setName('workflow:dump')
->setDefinition(array(
new InputArgument('name', InputArgument::REQUIRED, 'A workflow name'),
new InputArgument('marking', InputArgument::IS_ARRAY, 'A marking (a list of places)'),

View File

@ -24,6 +24,8 @@ use Symfony\Component\Translation\Command\XliffLintCommand as BaseLintCommand;
*/
class XliffLintCommand extends BaseLintCommand
{
protected static $defaultName = 'lint:xliff';
public function __construct($name = null, $directoryIteratorProvider = null, $isReadableProvider = null)
{
if (func_num_args()) {

View File

@ -23,6 +23,8 @@ use Symfony\Component\Yaml\Command\LintCommand as BaseLintCommand;
*/
class YamlLintCommand extends BaseLintCommand
{
protected static $defaultName = 'lint:yaml';
public function __construct($name = null, $directoryIteratorProvider = null, $isReadableProvider = null)
{
if (func_num_args()) {

View File

@ -27,6 +27,8 @@ use Doctrine\DBAL\Schema\SchemaException;
*/
class InitAclCommand extends ContainerAwareCommand
{
protected static $defaultName = 'init:acl';
private $connection;
private $schema;
@ -70,7 +72,6 @@ class InitAclCommand extends ContainerAwareCommand
protected function configure()
{
$this
->setName('init:acl')
->setDescription('Mounts ACL tables in the database')
->setHelp(<<<'EOF'
The <info>%command.name%</info> command mounts ACL tables in the database.

View File

@ -32,6 +32,8 @@ use Symfony\Component\Security\Acl\Model\MutableAclProviderInterface;
*/
class SetAclCommand extends ContainerAwareCommand
{
protected static $defaultName = 'acl:set';
private $provider;
/**
@ -80,7 +82,6 @@ class SetAclCommand extends ContainerAwareCommand
protected function configure()
{
$this
->setName('acl:set')
->setDescription('Sets ACL for objects')
->setHelp(<<<EOF
The <info>%command.name%</info> command sets ACL.

View File

@ -19,7 +19,6 @@ use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\Question;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\Security\Core\Encoder\BCryptPasswordEncoder;
use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
use Symfony\Component\Security\Core\User\User;
@ -33,6 +32,8 @@ use Symfony\Component\Security\Core\User\User;
*/
class UserPasswordEncoderCommand extends ContainerAwareCommand
{
protected static $defaultName = 'security:encode-password';
private $encoderFactory;
private $userClasses;
@ -54,7 +55,6 @@ class UserPasswordEncoderCommand extends ContainerAwareCommand
protected function configure()
{
$this
->setName('security:encode-password')
->setDescription('Encodes a password.')
->addArgument('password', InputArgument::OPTIONAL, 'The plain password to encode.')
->addArgument('user-class', InputArgument::OPTIONAL, 'The User entity class path associated with the encoder used to encode the password.')

View File

@ -20,7 +20,6 @@ namespace Symfony\Bundle\SecurityBundle\Tests\Functional;
* file that was distributed with this source code.
*/
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\SecurityBundle\Command\InitAclCommand;
use Symfony\Bundle\SecurityBundle\Command\SetAclCommand;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Component\Security\Acl\Domain\ObjectIdentity;
@ -170,7 +169,6 @@ class SetAclCommandTest extends WebTestCase
$kernel->boot();
$application = new Application($kernel);
$application->add(new InitAclCommand($kernel->getContainer()->get('security.acl.dbal.connection'), $kernel->getContainer()->get('security.acl.dbal.schema')));
$initAclCommand = $application->find('init:acl');
$initAclCommandTester = new CommandTester($initAclCommand);

View File

@ -26,7 +26,7 @@
"require-dev": {
"symfony/asset": "~2.8|~3.0|~4.0",
"symfony/browser-kit": "~2.8|~3.0|~4.0",
"symfony/console": "~3.2|~4.0",
"symfony/console": "~3.4|~4.0",
"symfony/css-selector": "~2.8|~3.0|~4.0",
"symfony/dom-crawler": "~2.8|~3.0|~4.0",
"symfony/event-dispatcher": "^3.3.1|~4.0",
@ -47,7 +47,8 @@
},
"conflict": {
"symfony/var-dumper": "<3.3",
"symfony/event-dispatcher": "<3.3.1"
"symfony/event-dispatcher": "<3.3.1",
"symfony/console": "<3.4"
},
"suggest": {
"symfony/security-acl": "For using the ACL functionality of this bundle"

View File

@ -7,6 +7,10 @@ CHANGELOG
* added `CommandLoaderInterface`, `FactoryCommandLoader` and PSR-11
`ContainerCommandLoader` for commands lazy-loading
* added a case-insensitive command name matching fallback
* added static `Command::$defaultName/getDefaultName()`, allowing for
commands to be registered at compile time in the application command loader.
Setting the `$defaultName` property avoids the need for filling the `command`
attribute on the `console.command` tag when using `AddConsoleCommandPass`.
3.3.0
-----

View File

@ -29,6 +29,11 @@ use Symfony\Component\Console\Exception\LogicException;
*/
class Command
{
/**
* @var string|null The default command name
*/
protected static $defaultName;
private $application;
private $name;
private $processTitle;
@ -45,6 +50,17 @@ class Command
private $usages = array();
private $helperSet;
/**
* @return string|null The default command name or null when no default name is set
*/
public static function getDefaultName()
{
$class = get_called_class();
$r = new \ReflectionProperty($class, 'defaultName');
return $class === $r->class ? static::$defaultName : null;
}
/**
* Constructor.
*
@ -56,7 +72,7 @@ class Command
{
$this->definition = new InputDefinition();
if (null !== $name) {
if (null !== $name || null !== $name = static::getDefaultName()) {
$this->setName($name);
}

View File

@ -46,16 +46,21 @@ class AddConsoleCommandPass implements CompilerPassInterface
$definition = $container->getDefinition($id);
$class = $container->getParameterBag()->resolveValue($definition->getClass());
if (!$r = $container->getReflectionClass($class)) {
throw new InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.', $class, $id));
}
if (!$r->isSubclassOf(Command::class)) {
throw new InvalidArgumentException(sprintf('The service "%s" tagged "%s" must be a subclass of "%s".', $id, $this->commandTag, Command::class));
}
$commandId = 'console.command.'.strtolower(str_replace('\\', '_', $class));
if (!isset($tags[0]['command'])) {
if (isset($tags[0]['command'])) {
$commandName = $tags[0]['command'];
} else {
if (!$r = $container->getReflectionClass($class)) {
throw new InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.', $class, $id));
}
if (!$r->isSubclassOf(Command::class)) {
throw new InvalidArgumentException(sprintf('The service "%s" tagged "%s" must be a subclass of "%s".', $id, $this->commandTag, Command::class));
}
$commandName = $class::getDefaultName();
}
if (null === $commandName) {
if (isset($serviceIds[$commandId]) || $container->hasAlias($commandId)) {
$commandId = $commandId.'_'.$id;
}
@ -69,7 +74,6 @@ class AddConsoleCommandPass implements CompilerPassInterface
}
$serviceIds[$commandId] = false;
$commandName = $tags[0]['command'];
unset($tags[0]);
$lazyCommandMap[$commandName] = $id;
$lazyCommandRefs[$id] = new TypedReference($id, $class);

View File

@ -77,6 +77,38 @@ class AddConsoleCommandPassTest extends TestCase
$this->assertSame(array(array('setName', array('my:command')), array('setAliases', array(array('my:alias')))), $command->getMethodCalls());
}
public function testProcessFallsBackToDefaultName()
{
$container = new ContainerBuilder();
$container
->register('with-default-name', NamedCommand::class)
->setPublic(false)
->addTag('console.command')
;
$pass = new AddConsoleCommandPass();
$pass->process($container);
$commandLoader = $container->getDefinition('console.command_loader');
$commandLocator = $container->getDefinition((string) $commandLoader->getArgument(0));
$this->assertSame(ContainerCommandLoader::class, $commandLoader->getClass());
$this->assertSame(array('default' => 'with-default-name'), $commandLoader->getArgument(1));
$this->assertEquals(array(array('with-default-name' => new ServiceClosureArgument(new TypedReference('with-default-name', NamedCommand::class)))), $commandLocator->getArguments());
$this->assertSame(array('console.command.symfony_component_console_tests_dependencyinjection_namedcommand' => false), $container->getParameter('console.command.ids'));
$container = new ContainerBuilder();
$container
->register('with-default-name', NamedCommand::class)
->setPublic(false)
->addTag('console.command', array('command' => 'new-name'))
;
$pass->process($container);
$this->assertSame(array('new-name' => 'with-default-name'), $container->getDefinition('console.command_loader')->getArgument(1));
}
public function visibilityProvider()
{
return array(
@ -96,7 +128,7 @@ class AddConsoleCommandPassTest extends TestCase
$container->addCompilerPass(new AddConsoleCommandPass());
$definition = new Definition('Symfony\Component\Console\Tests\DependencyInjection\MyCommand');
$definition->addTag('console.command', array('command' => 'my:command'));
$definition->addTag('console.command');
$definition->setAbstract(true);
$container->setDefinition('my-command', $definition);
@ -114,7 +146,7 @@ class AddConsoleCommandPassTest extends TestCase
$container->addCompilerPass(new AddConsoleCommandPass());
$definition = new Definition('SplObjectStorage');
$definition->addTag('console.command', array('command' => 'my:command'));
$definition->addTag('console.command');
$container->setDefinition('my-command', $definition);
$container->compile();
@ -146,3 +178,8 @@ class AddConsoleCommandPassTest extends TestCase
class MyCommand extends Command
{
}
class NamedCommand extends Command
{
protected static $defaultName = 'default';
}

View File

@ -26,6 +26,8 @@ use Symfony\Component\Console\Style\SymfonyStyle;
*/
class XliffLintCommand extends Command
{
protected static $defaultName = 'lint:xliff';
private $format;
private $displayCorrectFiles;
private $directoryIteratorProvider;
@ -45,7 +47,6 @@ class XliffLintCommand extends Command
protected function configure()
{
$this
->setName('lint:xliff')
->setDescription('Lints a XLIFF file and outputs encountered errors')
->addArgument('filename', null, 'A file or a directory or STDIN')
->addOption('format', null, InputOption::VALUE_REQUIRED, 'The output format', 'txt')

View File

@ -28,6 +28,8 @@ use Symfony\Component\Yaml\Yaml;
*/
class LintCommand extends Command
{
protected static $defaultName = 'lint:yaml';
private $parser;
private $format;
private $displayCorrectFiles;
@ -48,7 +50,6 @@ class LintCommand extends Command
protected function configure()
{
$this
->setName('lint:yaml')
->setDescription('Lints a file and outputs encountered errors')
->addArgument('filename', null, 'A file or a directory or STDIN')
->addOption('format', null, InputOption::VALUE_REQUIRED, 'The output format', 'txt')

View File

@ -19,7 +19,10 @@
"php": "^5.5.9|>=7.0.8"
},
"require-dev": {
"symfony/console": "~2.8|~3.0|~4.0"
"symfony/console": "~3.4|~4.0"
},
"conflict": {
"symfony/console": "<3.4"
},
"suggest": {
"symfony/console": "For validating YAML files using the lint command"