8000 [WIP] [FrameworkBundle] Add debug:autoconfigure command by atailouloute · Pull Request #35033 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[WIP] [FrameworkBundle] Add debug:autoconfigure command #35033

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
WIP: Add debug:autoconfigure command
  • Loading branch information
atailouloute committed Feb 6, 2020
commit c876203e46b491207ebdf4bdbdbb305b3e7bec8b
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
*
* @internal
*/
final class DebugAutoconfigurationCommand extends Command
final class DebugAutoconfigurationCommand extends ContainerDebugCommand
{
protected static $defaultName = 'debug:autoconfiguration';

Expand All @@ -45,8 +45,7 @@ protected function configure()
])
->setDescription('Displays current autoconfiguration for an application')
->setHelp(<<<'EOF'
The <info>%command.name%</info> command displays all services that
are autoconfigured:
The <info>%command.name%</info> command displays all services that are autoconfigured:

<info>php %command.full_name%</info>

Expand All @@ -62,108 +61,83 @@ protected function configure()
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$errorIo = $io->getErrorStyle();

$autoconfiguredInstanceofItems = $this->getContainerBuilder()->getAutoconfiguredInstanceof();
$definitions = $this->getContainerBuilder()->getAutoconfiguredInstanceof();
ksort($definitions, SORT_NATURAL);

if ($search = $input->getArgument('search')) {
$autoconfiguredInstanceofItems = array_filter($autoconfiguredInstanceofItems, function ($key) use ($search) {
$definitions = array_filter($definitions, function ($key) use ($search) {
return false !== stripos(str_replace('\\', '', $key), $search);
}, ARRAY_FILTER_USE_KEY);

if (!$autoconfiguredInstanceofItems) {
if (0 === \count($definitions)) {
$errorIo->error(sprintf('No autoconfiguration interface/class found matching "%s"', $search));

return 1;
}
}

ksort($autoconfiguredInstanceofItems, SORT_NATURAL);

$io->title('Autoconfiguration');
if ($search) {
$io->text(sprintf('(only showing classes/interfaces matching <comment>%s</comment>)', $search));
}
$io->newLine();
$name = $this->findProperInterfaceName(array_keys($definitions), $input, $io, $search);
/** @var ChildDefinition $definition */
$definition = $definitions[$name];

/** @var ChildDefinition $autoconfiguredInstanceofItem */
foreach ($autoconfiguredInstanceofItems as $key => $autoconfiguredInstanceofItem) {
$io->title(sprintf('Information for Interface/Class "<info>%s</info>"', $name));
$tableHeaders = ['Option', 'Value'];
$tableRows = [];

foreach ($autoconfiguredInstanceofItem->getTags() as $tag => $tagAttributes) {
$tableRows[] = ['Tag', $tag];
if ($tagAttributes !== [[]]) {
$tableRows[] = ['Tag attribute', $this->dumpTagAttribute($tagAttributes)];
$tagInformation = [];
foreach ($definition->getTags() as $tagName => $tagData) {
foreach ($tagData as $tagParameters) {
$parameters = array_map(function ($key, $value) {
return sprintf('<info>%s</info>: %s', $key, $value);
}, array_keys($tagParameters), array_values($tagParameters));
$parameters = implode(', ', $parameters);

if ('' === $parameters) {
$tagInformation[] = sprintf('%s', $tagName);
} else {
$tagInformation[] = sprintf('%s (%s)', $tagName, $parameters);
}
}
}
$tableRows[] = ['Tags', implode("\n", $tagInformation)];

if ($autoconfiguredInstanceofItem->getMethodCalls()) {
$tableRows[] = ['Method call', $this->dumpMethodCall($autoconfiguredInstanceofItem)];
}

if ($autoconfiguredInstanceofItem->getBindings()) {
$tableRows[] = ['Bindings', $this->dumpBindings($autoconfiguredInstanceofItem)];
$calls = $definition->getMethodCalls();
if (\count($calls) > 0) {
$callInformation = [];
foreach ($calls as $call) {
$callInformation[] = $call[0];
}
$tableRows[] = ['Calls', implode(', ', $callInformation)];
}

$io->title(sprintf('Autoconfiguration for "%s"', $key));
$io->newLine();
$io->table(['Option', 'Value'], $tableRows);
}
}

private function dumpMethodCall(ChildDefinition $autoconfiguredInstanceofItem)
{
$tagContainerBuilder = new ContainerBuilder();
foreach ($tagContainerBuilder->getServiceIds() as $serviceId) {
$tagContainerBuilder->removeDefinition($serviceId);
$tagContainerBuilder->removeAlias($serviceId);
$io->table($tableHeaders, $tableRows);
} else {
$io->table(['Interface/Class'], array_map(static function ($interface) {
return [$interface];
}, array_keys($definitions)));
}
$tagContainerBuilder->addDefinitions([$autoconfiguredInstanceofItem]);

$dumper = new YamlDumper($tagContainerBuilder);
preg_match('/calls\:\n((?: +- .+\n)+)/', $dumper->dump(), $matches);
$io->newLine();

return preg_replace('/^\s+/m', '', $matches[1]);
return 0;
}

private function dumpBindings(ChildDefinition $autoconfiguredInstanceofItem)
private function findProperInterfaceName(array $list, InputInterface $input, SymfonyStyle $io, string $name): string
{
$tagContainerBuilder = new ContainerBuilder();
foreach ($tagContainerBuilder->getServiceIds() as $serviceId) {
$tagContainerBuilder->removeDefinition($serviceId);
$tagContainerBuilder->removeAlias($serviceId);
}
$name = ltrim($name, '\\');

$dumper = new YamlDumper($tagContainerBuilder);
foreach ($autoconfiguredInstanceofItem->getBindings() as $bindingKey => $bindingValue) {
$tagContainerBuilder->setParameter($bindingKey, $bindingValue->getValues()[0]);
if (\in_array($name, $list, true)) {
return $name;
}

preg_match('/parameters\:\n((?: + .+\n)+)/', $dumper->dump(), $matches);

return preg_replace('/^\s+/m', '', $matches[1]);
}

private function dumpTagAttribute(array $tagAttribute)
{
$cloner = new VarCloner();
$cliDumper = new CliDumper(null, null, AbstractDumper::DUMP_LIGHT_ARRAY);

return $cliDumper->dump($cloner->cloneVar(current($tagAttribute)), true);
}
if (1 === \count($list)) {
return $list[0];
}

private function getContainerBuilder(): ContainerBuilder
{
$kernel = $this->getApplication()->getKernel();
$buildContainer = \Closure::bind(function () { return $this->buildContainer(); }, $kernel, \get_class($kernel));
$container = $buildContainer();
$container->getCompilerPassConfig()->setRemovingPasses([]);
$container->getCompilerPassConfig()->setAfterRemovingPasses([]);
$container->compile();

return $container;
return $io->choice('Select one of the following interfaces to display its information', $list);
}
}
43 changes: 43 additions & 0 deletions src/Symfony/Component/DependencyInjection/Dumper/XmlDumper.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
use Symfony\Component\DependencyInjection\Argument\ServiceLocatorArgument;
use Symfony\Component\DependencyInjection\Argument\TaggedIteratorArgument;
use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
Expand Down Expand Up @@ -53,6 +54,7 @@ public function dump(array $options = [])

$this->addParameters($container);
$this->addServices($container);
$this->addAutoconfiguredInstanceof($container);

$this->document->appendChild($container);
$xml = $this->document->saveXML();
Expand Down Expand Up @@ -337,6 +339,47 @@ private function convertParameters(array $parameters, string $type, \DOMElement
}
}

private function addAutoconfiguredInstanceof(\DOMElement $parent)
{
$childDefinitions = $this->container->getAutoconfiguredInstanceof();

if (!$childDefinitions) {
return;
}

$autoconfiguredInstanceOf = $this->document->createElement('autoconfigured-instanceof');

foreach ($childDefinitions as $id => $definition) {
$this->addAutoconfiguredInstanceofItem($definition, $id, $autoconfiguredInstanceOf);
}

// dump($this->container);
// die;

$parent->appendChild($autoconfiguredInstanceOf);
}

private function addAutoconfiguredInstanceofItem(ChildDefinition $definition, string $id, \DOMElement $parent)
{
$item = $this->document->createElement('autoconfigured-instanceof-item');
$item->setAttribute('id', $id);

foreach ($definition->getTags() as $name => $tags) {
foreach ($tags as $attributes) {
$tag = $this->document->createElement('tag');
$tag->setAttribute('name', $name);
foreach ($attributes as $key => $value) {
$tag->setAttribute($key, $value);
}
$item->appendChild($tag);
}
}

$this->addMethodCalls($definition->getMethodCalls(), $item);

$parent->appendChild($item);
}

/**
* Escapes arguments.
*/
Expand Down
48 changes: 48 additions & 0 deletions src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,9 @@ public function load($resource, string $type = null)
$this->instanceof = [];
$this->registerAliasesForSinglyImplementedInterfaces();
}

// autoconfiguredInstanceof
$this->parseAutoconfiguredInstanceOf($xml, $path);
}

/**
Expand Down Expand Up @@ -112,6 +115,51 @@ private function parseImports(\DOMDocument $xml, string $file)
}
}

private function parseAutoconfiguredInstanceOf(\DOMDocument $xml, string $file)
{
$xpath = new \DOMXPath($xml);
$xpath->registerNamespace('container', self::NS);

if (false === $autoconfiguredInstanceof = $xpath->query(('//container:autoconfigured-instanceof/container:autoconfigured-instanceof-item'))) {
return;
}

foreach ($autoconfiguredInstanceof as $item) {
$definition = $this->container->registerForAutoconfiguration($item->getAttribute('id'));

foreach ($this->getChildren($item, 'call') as $call) {
$definition->addMethodCall($call->getAttribute('method'), $this->getArgumentsAsPhp($call, 'argument', $file), XmlUtils::phpize($call->getAttribute('returns-clone')));
}

$tags = $this->getChildren($item, 'tag');

if (!empty($defaults['tags'])) {
$tags = array_merge($tags, $defaults['tags']);
}

foreach ($tags as $tag) {
$parameters = [];
foreach ($tag->attributes as $name => $node) {
if ('name' === $name) {
continue;
}

if (false !== strpos($name, '-') && false === strpos($name, '_') && !\array_key_exists($normalizedName = str_replace('-', '_', $name), $parameters)) {
$parameters[$normalizedName] = XmlUtils::phpize($node->nodeValue);
}
// keep not normalized key
$parameters[$name] = XmlUtils::phpize($node->nodeValue);
}

if ('' === $tag->getAttribute('name')) {
throw new InvalidArgumentException(sprintf('The tag name for service "%s" in %s must be a non-empty string.', (string) $item->getAttribute('id'), $file));
}

$definition->addTag($tag->getAttribute('name'), $parameters);
}
}
}

private function parseDefinitions(\DOMDocument $xml, string $file, array $defaults)
{
$xpath = new \DOMXPath($xml);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@
<xsd:element name="services" type="services" />
<xsd:group ref="foreign" />
</xsd:sequence>
<xsd:sequence minOccurs="0">
<xsd:element name="autoconfigured-instanceof" type="autoconfigured-instanceof" />
<xsd:group ref="foreign" />
</xsd:sequence>
</xsd:sequence>
</xsd:complexType>

Expand All @@ -60,6 +64,25 @@
</xsd:choice>
</xsd:complexType>

<xsd:complexType name="autoconfigured-instanceof">
<xsd:annotation>
<xsd:documentation><![CDATA[
Enclosing element for the autoconfigured instanceof
]]></xsd:documentation>
</xsd:annotation>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="autoconfigured-instanceof-item" type="service" minOccurs="1" />
</xsd:choice>
</xsd:complexType>

<xsd:complexType name="autoconfigured-instanceof-item">
<xsd:choice maxOccurs="unbounded">
<xsd:element name="call" type="call" minOccurs="0" maxOccurs="unbounded" />
<xsd:element name="tag" type="tag" minOccurs="0" maxOccurs="unbounded" />
</xsd:choice>
<xsd:attribute name="id" type="xsd:string" />
</xsd:complexType>

<xsd:complexType name="imports">
<xsd:annotation>
<xsd:documentation><![CDATA[
Expand Down
0