First Commit

This commit is contained in:
Esteban
2026-07-03 16:27:34 +02:00
commit 7a7440daab
8955 changed files with 1117958 additions and 0 deletions
@@ -0,0 +1,193 @@
<?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 Symfony\Component\Console\DependencyInjection;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Command\LazyCommand;
use Symfony\Component\Console\CommandLoader\ContainerCommandLoader;
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\TypedReference;
/**
* Registers console commands.
*
* @author Grégoire Pineau <lyrixx@lyrixx.info>
*/
class AddConsoleCommandPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container): void
{
$commandServices = [];
$lazyCommandMap = [];
$lazyCommandRefs = [];
$serviceIds = [];
foreach ($container->findTaggedServiceIds('console.command', true) as $id => $tags) {
foreach ($tags as $tag) {
$commandServices[$id][$tag['method'] ?? '__invoke'][] = $tag;
}
}
foreach ($commandServices as $id => $commands) {
$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));
}
foreach ($commands as $tags) {
$this->registerCommand($container, $r, $id, $class, $tags, $definition, $serviceIds, $lazyCommandMap, $lazyCommandRefs);
}
}
$container
->register('console.command_loader', ContainerCommandLoader::class)
->setPublic(true)
->addTag('container.no_preload')
->setArguments([ServiceLocatorTagPass::register($container, $lazyCommandRefs), $lazyCommandMap]);
$container->setParameter('console.command.ids', $serviceIds);
}
private function registerCommand(ContainerBuilder $container, \ReflectionClass $reflection, string $id, string $class, array $tags, Definition $definition, array &$serviceIds, array &$lazyCommandMap, array &$lazyCommandRefs): void
{
if (!$reflection->isSubclassOf(Command::class)) {
$method = $tags[0]['method'] ?? '__invoke';
if (!$reflection->hasMethod($method)) {
throw new InvalidArgumentException(\sprintf('The service "%s" tagged "%s" must either be a subclass of "%s" or have an "%s()" method.', $id, 'console.command', Command::class, $method));
}
$reflection = $reflection->getMethod($method);
if (!$reflection->isPublic() || $reflection->isStatic()) {
throw new InvalidArgumentException(\sprintf('The method "%s::%s()" must be public and non-static to be used as a console command.', $class, $method));
}
if ('__invoke' === $method) {
$callableRef = new Reference($id);
$id .= '.command';
} else {
$callableRef = [new Reference($id), $method];
$id .= '.'.$method.'.command';
}
$class = Command::class;
$closureDefinition = new Definition(\Closure::class)
->setFactory([\Closure::class, 'fromCallable'])
->setArguments([$callableRef]);
$definition = $container->register($id, $class)
->addMethodCall('setCode', [$closureDefinition]);
} elseif (isset($tags[0]['method'])) {
throw new InvalidArgumentException(\sprintf('The service "%s" tagged "console.command" cannot define a method command when it is a subclass of "%s".', $id, Command::class));
}
$definition->addTag('container.no_preload');
$attribute = $this->getCommandAttribute($reflection);
$defaultName = $attribute?->name;
$aliases = str_replace('%', '%%', $tags[0]['command'] ?? $defaultName ?? '');
$aliases = explode('|', $aliases);
$commandName = array_shift($aliases);
if ($isHidden = '' === $commandName) {
$commandName = array_shift($aliases);
}
if (null === $commandName) {
if ($definition->isPrivate() || $definition->hasTag('container.private')) {
$commandId = 'console.command.public_alias.'.$id;
$container->setAlias($commandId, $id)->setPublic(true);
$id = $commandId;
}
$serviceIds[] = $id;
return;
}
$description = $tags[0]['description'] ?? null;
$help = $tags[0]['help'] ?? null;
$usages = $tags[0]['usages'] ?? null;
unset($tags[0]);
$lazyCommandMap[$commandName] = $id;
$lazyCommandRefs[$id] = new TypedReference($id, $class);
foreach ($aliases as $alias) {
$lazyCommandMap[$alias] = $id;
}
foreach ($tags as $tag) {
if (isset($tag['command'])) {
$aliases[] = $tag['command'];
$lazyCommandMap[$tag['command']] = $id;
}
$description ??= $tag['description'] ?? null;
$help ??= $tag['help'] ?? null;
$usages ??= $tag['usages'] ?? null;
}
$definition->addMethodCall('setName', [$commandName]);
if ($aliases) {
$definition->addMethodCall('setAliases', [$aliases]);
}
if ($isHidden) {
$definition->addMethodCall('setHidden', [true]);
}
if ($help ??= $attribute?->help) {
$definition->addMethodCall('setHelp', [str_replace('%', '%%', $help)]);
}
if ($usages ??= $attribute?->usages) {
foreach ($usages as $usage) {
$definition->addMethodCall('addUsage', [$usage]);
}
}
if ($description ??= $attribute?->description) {
$escapedDescription = str_replace('%', '%%', $description);
$definition->addMethodCall('setDescription', [$escapedDescription]);
$container->register('.'.$id.'.lazy', LazyCommand::class)
->setArguments([$commandName, $aliases, $escapedDescription, $isHidden, new ServiceClosureArgument($lazyCommandRefs[$id])]);
$lazyCommandRefs[$id] = new Reference('.'.$id.'.lazy');
}
}
private function getCommandAttribute(\ReflectionClass|\ReflectionMethod $reflection): ?AsCommand
{
/** @var AsCommand|null $attribute */
if ($attribute = ($reflection->getAttributes(AsCommand::class)[0] ?? null)?->newInstance()) {
return $attribute;
}
if ($reflection instanceof \ReflectionMethod && '__invoke' === $reflection->getName()) {
return ($reflection->getDeclaringClass()->getAttributes(AsCommand::class)[0] ?? null)?->newInstance();
}
return null;
}
}
@@ -0,0 +1,69 @@
<?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 Symfony\Component\Console\DependencyInjection;
use Symfony\Component\Console\ArgumentResolver\ValueResolver\TraceableValueResolver;
use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
use Symfony\Component\DependencyInjection\Argument\ServiceLocatorArgument;
use Symfony\Component\DependencyInjection\Argument\TaggedIteratorArgument;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Compiler\PriorityTaggedServiceTrait;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
/**
* Gathers and configures the console argument value resolvers.
*
* @author Robin Chalas <robin.chalas@gmail.com>
*/
class ConsoleArgumentValueResolverPass implements CompilerPassInterface
{
use PriorityTaggedServiceTrait;
public function process(ContainerBuilder $container): void
{
if (!$container->hasDefinition('console.argument_resolver')) {
return;
}
$definitions = $container->getDefinitions();
$namedResolvers = $this->findAndSortTaggedServices(new TaggedIteratorArgument('console.targeted_value_resolver', 'name', needsIndexes: true), $container);
$resolvers = $this->findAndSortTaggedServices(new TaggedIteratorArgument('console.argument_value_resolver', 'name', needsIndexes: true), $container);
foreach ($resolvers as $name => $resolver) {
if ($definitions[(string) $resolver]->hasTag('console.targeted_value_resolver')) {
unset($resolvers[$name]);
} else {
$namedResolvers[$name] ??= clone $resolver;
}
}
if ($container->getParameter('kernel.debug') && $container->has('debug.stopwatch')) {
foreach ($resolvers as $name => $resolver) {
$resolvers[$name] = new Reference('.debug.console.value_resolver.'.$resolver);
$container->register('.debug.console.value_resolver.'.$resolver, TraceableValueResolver::class)
->setArguments([$resolver, new Reference('debug.stopwatch')]);
}
foreach ($namedResolvers as $name => $resolver) {
$namedResolvers[$name] = new Reference('.debug.console.value_resolver.'.$resolver);
$container->register('.debug.console.value_resolver.'.$resolver, TraceableValueResolver::class)
->setArguments([$resolver, new Reference('debug.stopwatch')]);
}
}
$container
->getDefinition('console.argument_resolver')
->replaceArgument(0, new IteratorArgument(array_values($resolvers)))
->setArgument(1, new ServiceLocatorArgument($namedResolvers))
;
}
}
@@ -0,0 +1,190 @@
<?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 Symfony\Component\Console\DependencyInjection;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\RawInputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\DependencyInjection\Attribute\AutowireCallable;
use Symfony\Component\DependencyInjection\Attribute\Target;
use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\TypedReference;
use Symfony\Component\VarExporter\ProxyHelper;
/**
* Creates the service-locators required by ServiceValueResolver for commands.
*
* @author Nicolas Grekas <p@tchwork.com>
* @author Robin Chalas <robin.chalas@gmail.com>
*/
final class RegisterCommandArgumentLocatorsPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container): void
{
if (!$container->hasDefinition('console.argument_resolver.service')) {
return;
}
$parameterBag = $container->getParameterBag();
$serviceLocators = [];
foreach ($container->findTaggedServiceIds('console.command.service_arguments', true) as $id => $tags) {
$def = $container->getDefinition($id);
$class = $def->getClass();
$autowire = $def->isAutowired();
$bindings = $def->getBindings();
// Resolve service class, taking parent definitions into account
while ($def instanceof ChildDefinition) {
$def = $container->findDefinition($def->getParent());
$class = $class ?: $def->getClass();
$bindings += $def->getBindings();
}
$class = $parameterBag->resolveValue($class);
if (!$r = $container->getReflectionClass($class)) {
throw new InvalidArgumentException(\sprintf('Class "%s" used for command "%s" cannot be found.', $class, $id));
}
// Get all console.command tags to find command names and their methods
$commandTags = $container->getDefinition($id)->getTag('console.command');
$manualArguments = [];
// Validate and collect explicit per-arguments service references
foreach ($tags as $attributes) {
if (!isset($attributes['argument']) && !isset($attributes['id'])) {
$autowire = true;
continue;
}
foreach (['argument', 'id'] as $k) {
if (!isset($attributes[$k][0])) {
throw new InvalidArgumentException(\sprintf('Missing "%s" attribute on tag "console.command.service_arguments" %s for service "%s".', $k, json_encode($attributes, \JSON_UNESCAPED_UNICODE), $id));
}
}
$manualArguments[$attributes['argument']] = $attributes['id'];
}
foreach ($commandTags as $commandTag) {
$commandName = $commandTag['command'] ?? null;
if (!$commandName) {
continue;
}
$methodName = $commandTag['method'] ?? '__invoke';
if (!$r->hasMethod($methodName)) {
continue;
}
$method = $r->getMethod($methodName);
$arguments = [];
$erroredIds = 0;
foreach ($method->getParameters() as $p) {
$type = preg_replace('/(^|[(|&])\\\\/', '\1', $target = ltrim(ProxyHelper::exportType($p) ?? '', '?'));
$invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
$autowireAttributes = null;
$parsedName = $p->name;
$k = null;
if (isset($manualArguments[$p->name])) {
$target = $manualArguments[$p->name];
if ('?' !== $target[0]) {
$invalidBehavior = ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE;
} elseif ('' === $target = substr($target, 1)) {
throw new InvalidArgumentException(\sprintf('A "console.command.service_arguments" tag must have non-empty "id" attributes for service "%s".', $id));
} elseif ($p->allowsNull() && !$p->isOptional()) {
$invalidBehavior = ContainerInterface::NULL_ON_INVALID_REFERENCE;
}
} elseif (isset($bindings[$bindingName = $type.' $'.$name = Target::parseName($p, $k, $parsedName)])
|| isset($bindings[$bindingName = $type.' $'.$parsedName])
|| isset($bindings[$bindingName = '$'.$name])
|| isset($bindings[$bindingName = $type])
) {
$binding = $bindings[$bindingName];
[$bindingValue, $bindingId, , $bindingType, $bindingFile] = $binding->getValues();
$binding->setValues([$bindingValue, $bindingId, true, $bindingType, $bindingFile]);
$arguments[$p->name] = $bindingValue;
continue;
} elseif (!$autowire || (!($autowireAttributes = $p->getAttributes(Autowire::class, \ReflectionAttribute::IS_INSTANCEOF)) && (!$type || '\\' !== $target[0]))) {
continue;
} elseif (!$autowireAttributes && is_subclass_of($type, \UnitEnum::class)) {
// Do not attempt to register enum typed arguments if not already present in bindings
continue;
} elseif (!$p->allowsNull()) {
$invalidBehavior = $autowireAttributes ? ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE : ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE;
}
// Skip console-specific types that are resolved by other resolvers
if (\in_array($type, [InputInterface::class, RawInputInterface::class, OutputInterface::class], true)) {
continue;
}
if ($autowireAttributes) {
$attribute = $autowireAttributes[0]->newInstance();
$value = $parameterBag->resolveValue($attribute->value);
if ($attribute instanceof AutowireCallable) {
$arguments[$p->name] = $attribute->buildDefinition($value, $type, $p);
} elseif ($value instanceof Reference) {
$arguments[$p->name] = $type ? new TypedReference($value, $type, $invalidBehavior, $p->name) : new Reference($value, $invalidBehavior);
} else {
$arguments[$p->name] = new Reference('.value.'.$container->hash($value));
$container->register((string) $arguments[$p->name], 'mixed')
->setFactory('current')
->addArgument([$value]);
}
continue;
}
if ($type && !$p->isOptional() && !$p->allowsNull() && !class_exists($type) && !interface_exists($type, false)) {
$message = \sprintf('Cannot determine command argument for "%s::%s()": the $%s argument is type-hinted with the non-existent class or interface: "%s".', $class, $method->name, $p->name, $type);
// See if the type-hint lives in the same namespace as the command
if (0 === strncmp($type, $class, strrpos($class, '\\'))) {
$message .= ' Did you forget to add a use statement?';
}
$container->register($erroredId = '.errored.'.$container->hash($message), $type)
->addError($message);
$arguments[$p->name] = new Reference($erroredId, ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE);
++$erroredIds;
} else {
$target = preg_replace('/(^|[(|&])\\\\/', '\1', $target);
$arguments[$p->name] = $type ? new TypedReference($target, $type, $invalidBehavior, Target::parseName($p)) : new Reference($target, $invalidBehavior);
}
}
if ($arguments) {
$serviceLocators[$commandName] = ServiceLocatorTagPass::register($container, $arguments, \count($arguments) !== $erroredIds ? $commandName : null);
}
}
}
$container->getDefinition('console.argument_resolver.service')
->replaceArgument(0, ServiceLocatorTagPass::register($container, $serviceLocators));
}
}
@@ -0,0 +1,61 @@
<?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 Symfony\Component\Console\DependencyInjection;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
/**
* Removes empty service-locators registered for ServiceValueResolver for commands.
*
* @author Robin Chalas <robin.chalas@gmail.com>
*/
final class RemoveEmptyCommandArgumentLocatorsPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container): void
{
if (!$container->hasDefinition('console.argument_resolver.service')) {
return;
}
$serviceResolverDef = $container->getDefinition('console.argument_resolver.service');
$commandLocatorRef = $serviceResolverDef->getArgument(0);
if (!$commandLocatorRef) {
return;
}
$commandLocator = $container->getDefinition((string) $commandLocatorRef);
if ($commandLocator->getFactory()) {
$commandLocator = $container->getDefinition($commandLocator->getFactory()[0]);
}
$commands = $commandLocator->getArgument(0);
foreach ($commands as $commandName => $argumentRef) {
$argumentLocator = $container->getDefinition((string) $argumentRef->getValues()[0]);
if ($argumentLocator->getFactory()) {
$argumentLocator = $container->getDefinition($argumentLocator->getFactory()[0]);
}
if (!$argumentLocator->getArgument(0)) {
$reason = \sprintf('Removing service-argument resolver for command "%s": no corresponding services exist for the referenced types.', $commandName);
unset($commands[$commandName]);
$container->log($this, $reason);
}
}
$commandLocator->replaceArgument(0, $commands);
}
}