AddConsoleCommandPass.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Console\DependencyInjection;
  11. use Symfony\Component\Console\Command\Command;
  12. use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
  13. use Symfony\Component\DependencyInjection\ContainerBuilder;
  14. use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
  15. /**
  16. * Registers console commands.
  17. *
  18. * @author Grégoire Pineau <lyrixx@lyrixx.info>
  19. */
  20. class AddConsoleCommandPass implements CompilerPassInterface
  21. {
  22. public function process(ContainerBuilder $container)
  23. {
  24. $commandServices = $container->findTaggedServiceIds('console.command', true);
  25. $serviceIds = array();
  26. foreach ($commandServices as $id => $tags) {
  27. $definition = $container->getDefinition($id);
  28. $class = $container->getParameterBag()->resolveValue($definition->getClass());
  29. if (!$r = $container->getReflectionClass($class)) {
  30. throw new InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.', $class, $id));
  31. }
  32. if (!$r->isSubclassOf(Command::class)) {
  33. throw new InvalidArgumentException(sprintf('The service "%s" tagged "console.command" must be a subclass of "%s".', $id, Command::class));
  34. }
  35. $commandId = 'console.command.'.strtolower(str_replace('\\', '_', $class));
  36. if ($container->hasAlias($commandId) || isset($serviceIds[$commandId])) {
  37. $commandId = $commandId.'_'.$id;
  38. }
  39. if (!$definition->isPublic()) {
  40. $container->setAlias($commandId, $id);
  41. $id = $commandId;
  42. }
  43. $serviceIds[$commandId] = $id;
  44. }
  45. $container->setParameter('console.command.ids', $serviceIds);
  46. }
  47. }