initial commit

This commit is contained in:
boris
2025-09-30 09:24:25 +01:00
committed by boris
parent a783a12c97
commit c7770ea03b
4695 changed files with 525784 additions and 0 deletions

View File

@@ -0,0 +1,221 @@
<?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\Bundle\FrameworkBundle\Console;
use Symfony\Component\Console\Application as BaseApplication;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Command\ListCommand;
use Symfony\Component\Console\Command\TraceableCommand;
use Symfony\Component\Console\Debug\CliRequest;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\HttpKernel\KernelInterface;
/**
* @author Fabien Potencier <fabien@symfony.com>
*/
class Application extends BaseApplication
{
private bool $commandsRegistered = false;
private array $registrationErrors = [];
public function __construct(
private KernelInterface $kernel,
) {
parent::__construct('Symfony', Kernel::VERSION);
$inputDefinition = $this->getDefinition();
$inputDefinition->addOption(new InputOption('--env', '-e', InputOption::VALUE_REQUIRED, 'The Environment name.', $kernel->getEnvironment()));
$inputDefinition->addOption(new InputOption('--no-debug', null, InputOption::VALUE_NONE, 'Switch off debug mode.'));
$inputDefinition->addOption(new InputOption('--profile', null, InputOption::VALUE_NONE, 'Enables profiling (requires debug).'));
}
/**
* Gets the Kernel associated with this Console.
*/
public function getKernel(): KernelInterface
{
return $this->kernel;
}
public function reset(): void
{
if ($this->kernel->getContainer()->has('services_resetter')) {
$this->kernel->getContainer()->get('services_resetter')->reset();
}
}
/**
* Runs the current application.
*
* @return int 0 if everything went fine, or an error code
*/
public function doRun(InputInterface $input, OutputInterface $output): int
{
$this->registerCommands();
if ($this->registrationErrors) {
$this->renderRegistrationErrors($input, $output);
}
$this->setDispatcher($this->kernel->getContainer()->get('event_dispatcher'));
return parent::doRun($input, $output);
}
protected function doRunCommand(Command $command, InputInterface $input, OutputInterface $output): int
{
$requestStack = null;
$renderRegistrationErrors = true;
if (!$command instanceof ListCommand) {
if ($this->registrationErrors) {
$this->renderRegistrationErrors($input, $output);
$this->registrationErrors = [];
$renderRegistrationErrors = false;
}
}
if ($input->hasParameterOption('--profile')) {
$container = $this->kernel->getContainer();
if (!$this->kernel->isDebug()) {
if ($output instanceof ConsoleOutputInterface) {
$output = $output->getErrorOutput();
}
(new SymfonyStyle($input, $output))->warning('Debug mode should be enabled when the "--profile" option is used.');
} elseif (!$container->has('debug.stopwatch')) {
if ($output instanceof ConsoleOutputInterface) {
$output = $output->getErrorOutput();
}
(new SymfonyStyle($input, $output))->warning('The "--profile" option needs the Stopwatch component. Try running "composer require symfony/stopwatch".');
} elseif (!$container->has('.virtual_request_stack')) {
if ($output instanceof ConsoleOutputInterface) {
$output = $output->getErrorOutput();
}
(new SymfonyStyle($input, $output))->warning('The "--profile" option needs the profiler integration. Try enabling the "framework.profiler" option.');
} else {
$command = new TraceableCommand($command, $container->get('debug.stopwatch'));
$requestStack = $container->get('.virtual_request_stack');
$requestStack->push(new CliRequest($command));
}
}
try {
$returnCode = parent::doRunCommand($command, $input, $output);
} finally {
$requestStack?->pop();
}
if ($renderRegistrationErrors && $this->registrationErrors) {
$this->renderRegistrationErrors($input, $output);
$this->registrationErrors = [];
}
return $returnCode;
}
public function find(string $name): Command
{
$this->registerCommands();
return parent::find($name);
}
public function get(string $name): Command
{
$this->registerCommands();
return parent::get($name);
}
public function all(?string $namespace = null): array
{
$this->registerCommands();
return parent::all($namespace);
}
public function getLongVersion(): string
{
return parent::getLongVersion().\sprintf(' (env: <comment>%s</>, debug: <comment>%s</>)', $this->kernel->getEnvironment(), $this->kernel->isDebug() ? 'true' : 'false');
}
public function add(Command $command): ?Command
{
$this->registerCommands();
return parent::add($command);
}
protected function registerCommands(): void
{
if ($this->commandsRegistered) {
return;
}
$this->commandsRegistered = true;
$this->kernel->boot();
$container = $this->kernel->getContainer();
foreach ($this->kernel->getBundles() as $bundle) {
if ($bundle instanceof Bundle) {
try {
$bundle->registerCommands($this);
} catch (\Throwable $e) {
$this->registrationErrors[] = $e;
}
}
}
if ($container->has('console.command_loader')) {
$this->setCommandLoader($container->get('console.command_loader'));
}
if ($container->hasParameter('console.command.ids')) {
$lazyCommandIds = $container->hasParameter('console.lazy_command.ids') ? $container->getParameter('console.lazy_command.ids') : [];
foreach ($container->getParameter('console.command.ids') as $id) {
if (!isset($lazyCommandIds[$id])) {
try {
$this->add($container->get($id));
} catch (\Throwable $e) {
$this->registrationErrors[] = $e;
}
}
}
}
}
private function renderRegistrationErrors(InputInterface $input, OutputInterface $output): void
{
if ($output instanceof ConsoleOutputInterface) {
$output = $output->getErrorOutput();
}
(new SymfonyStyle($input, $output))->warning('Some commands could not be registered:');
foreach ($this->registrationErrors as $error) {
$this->doRenderThrowable($error, $output);
}
}
}

View File

@@ -0,0 +1,379 @@
<?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\Bundle\FrameworkBundle\Console\Descriptor;
use Symfony\Component\Config\Resource\ClassExistenceResource;
use Symfony\Component\Console\Descriptor\DescriptorInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\Compiler\AnalyzeServiceReferencesPass;
use Symfony\Component\DependencyInjection\Compiler\ServiceReferenceGraphEdge;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
/**
* @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com>
*
* @internal
*/
abstract class Descriptor implements DescriptorInterface
{
protected OutputInterface $output;
public function describe(OutputInterface $output, mixed $object, array $options = []): void
{
$this->output = $output;
if ($object instanceof ContainerBuilder) {
(new AnalyzeServiceReferencesPass(false, false))->process($object);
}
$deprecatedParameters = [];
if ($object instanceof ContainerBuilder && isset($options['parameter']) && ($parameterBag = $object->getParameterBag()) instanceof ParameterBag) {
$deprecatedParameters = $parameterBag->allDeprecated();
}
match (true) {
$object instanceof RouteCollection => $this->describeRouteCollection($this->filterRoutesByHttpMethod($object, $options['method'] ?? ''), $options),
$object instanceof Route => $this->describeRoute($object, $options),
$object instanceof ParameterBag => $this->describeContainerParameters($object, $options),
$object instanceof ContainerBuilder && !empty($options['env-vars']) => $this->describeContainerEnvVars($this->getContainerEnvVars($object), $options),
$object instanceof ContainerBuilder && isset($options['group_by']) && 'tags' === $options['group_by'] => $this->describeContainerTags($object, $options),
$object instanceof ContainerBuilder && isset($options['id']) => $this->describeContainerService($this->resolveServiceDefinition($object, $options['id']), $options, $object),
$object instanceof ContainerBuilder && isset($options['parameter']) => $this->describeContainerParameter($object->resolveEnvPlaceholders($object->getParameter($options['parameter'])), $deprecatedParameters[$options['parameter']] ?? null, $options),
$object instanceof ContainerBuilder && isset($options['deprecations']) => $this->describeContainerDeprecations($object, $options),
$object instanceof ContainerBuilder => $this->describeContainerServices($object, $options),
$object instanceof Definition => $this->describeContainerDefinition($object, $options),
$object instanceof Alias => $this->describeContainerAlias($object, $options),
$object instanceof EventDispatcherInterface => $this->describeEventDispatcherListeners($object, $options),
\is_callable($object) => $this->describeCallable($object, $options),
default => throw new \InvalidArgumentException(\sprintf('Object of type "%s" is not describable.', get_debug_type($object))),
};
if ($object instanceof ContainerBuilder) {
$object->getCompiler()->getServiceReferenceGraph()->clear();
}
}
protected function getOutput(): OutputInterface
{
return $this->output;
}
protected function write(string $content, bool $decorated = false): void
{
$this->output->write($content, false, $decorated ? OutputInterface::OUTPUT_NORMAL : OutputInterface::OUTPUT_RAW);
}
abstract protected function describeRouteCollection(RouteCollection $routes, array $options = []): void;
abstract protected function describeRoute(Route $route, array $options = []): void;
abstract protected function describeContainerParameters(ParameterBag $parameters, array $options = []): void;
abstract protected function describeContainerTags(ContainerBuilder $container, array $options = []): void;
/**
* Describes a container service by its name.
*
* Common options are:
* * name: name of described service
*
* @param Definition|Alias|object $service
*/
abstract protected function describeContainerService(object $service, array $options = [], ?ContainerBuilder $container = null): void;
/**
* Describes container services.
*
* Common options are:
* * tag: filters described services by given tag
*/
abstract protected function describeContainerServices(ContainerBuilder $container, array $options = []): void;
abstract protected function describeContainerDeprecations(ContainerBuilder $container, array $options = []): void;
abstract protected function describeContainerDefinition(Definition $definition, array $options = [], ?ContainerBuilder $container = null): void;
abstract protected function describeContainerAlias(Alias $alias, array $options = [], ?ContainerBuilder $container = null): void;
abstract protected function describeContainerParameter(mixed $parameter, ?array $deprecation, array $options = []): void;
abstract protected function describeContainerEnvVars(array $envs, array $options = []): void;
/**
* Describes event dispatcher listeners.
*
* Common options are:
* * name: name of listened event
*/
abstract protected function describeEventDispatcherListeners(EventDispatcherInterface $eventDispatcher, array $options = []): void;
abstract protected function describeCallable(mixed $callable, array $options = []): void;
protected function formatValue(mixed $value): string
{
if ($value instanceof \UnitEnum) {
return ltrim(var_export($value, true), '\\');
}
if (\is_object($value)) {
return \sprintf('object(%s)', $value::class);
}
if (\is_string($value)) {
return $value;
}
return preg_replace("/\n\s*/s", '', var_export($value, true));
}
protected function formatParameter(mixed $value): string
{
if ($value instanceof \UnitEnum) {
return ltrim(var_export($value, true), '\\');
}
// Recursively search for enum values, so we can replace it
// before json_encode (which will not display anything for \UnitEnum otherwise)
if (\is_array($value)) {
array_walk_recursive($value, static function (&$value) {
if ($value instanceof \UnitEnum) {
$value = ltrim(var_export($value, true), '\\');
}
});
}
if (\is_bool($value) || \is_array($value) || (null === $value)) {
$jsonString = json_encode($value);
if (preg_match('/^(.{60})./us', $jsonString, $matches)) {
return $matches[1].'...';
}
return $jsonString;
}
return (string) $value;
}
protected function resolveServiceDefinition(ContainerBuilder $container, string $serviceId): mixed
{
if ($container->hasDefinition($serviceId)) {
return $container->getDefinition($serviceId);
}
// Some service IDs don't have a Definition, they're aliases
if ($container->hasAlias($serviceId)) {
return $container->getAlias($serviceId);
}
if ('service_container' === $serviceId) {
return (new Definition(ContainerInterface::class))->setPublic(true)->setSynthetic(true);
}
// the service has been injected in some special way, just return the service
return $container->get($serviceId);
}
protected function findDefinitionsByTag(ContainerBuilder $container, bool $showHidden): array
{
$definitions = [];
$tags = $container->findTags();
asort($tags);
foreach ($tags as $tag) {
foreach ($container->findTaggedServiceIds($tag) as $serviceId => $attributes) {
$definition = $this->resolveServiceDefinition($container, $serviceId);
if ($showHidden xor '.' === ($serviceId[0] ?? null)) {
continue;
}
if (!isset($definitions[$tag])) {
$definitions[$tag] = [];
}
$definitions[$tag][$serviceId] = $definition;
}
}
return $definitions;
}
protected function sortParameters(ParameterBag $parameters): array
{
$parameters = $parameters->all();
ksort($parameters);
return $parameters;
}
protected function sortServiceIds(array $serviceIds): array
{
asort($serviceIds);
return $serviceIds;
}
protected function sortTaggedServicesByPriority(array $services): array
{
$maxPriority = [];
foreach ($services as $service => $tags) {
$maxPriority[$service] = \PHP_INT_MIN;
foreach ($tags as $tag) {
$currentPriority = $tag['priority'] ?? 0;
if ($maxPriority[$service] < $currentPriority) {
$maxPriority[$service] = $currentPriority;
}
}
}
uasort($maxPriority, fn ($a, $b) => $b <=> $a);
return array_keys($maxPriority);
}
protected function sortTagsByPriority(array $tags): array
{
$sortedTags = [];
foreach ($tags as $tagName => $tag) {
$sortedTags[$tagName] = $this->sortByPriority($tag);
}
return $sortedTags;
}
protected function sortByPriority(array $tag): array
{
usort($tag, fn ($a, $b) => ($b['priority'] ?? 0) <=> ($a['priority'] ?? 0));
return $tag;
}
/**
* @return array<string, string[]>
*/
protected function getReverseAliases(RouteCollection $routes): array
{
$reverseAliases = [];
foreach ($routes->getAliases() as $name => $alias) {
$reverseAliases[$alias->getId()][] = $name;
}
return $reverseAliases;
}
public static function getClassDescription(string $class, ?string &$resolvedClass = null): string
{
$resolvedClass = $class;
try {
$resource = new ClassExistenceResource($class, false);
// isFresh() will explode ONLY if a parent class/trait does not exist
$resource->isFresh(0);
$r = new \ReflectionClass($class);
$resolvedClass = $r->name;
if ($docComment = $r->getDocComment()) {
$docComment = preg_split('#\n\s*\*\s*[\n@]#', substr($docComment, 3, -2), 2)[0];
return trim(preg_replace('#\s*\n\s*\*\s*#', ' ', $docComment));
}
} catch (\ReflectionException) {
}
return '';
}
private function getContainerEnvVars(ContainerBuilder $container): array
{
if (!$container->hasParameter('debug.container.dump')) {
return [];
}
if (!$container->getParameter('debug.container.dump') || !is_file($container->getParameter('debug.container.dump'))) {
return [];
}
$file = file_get_contents($container->getParameter('debug.container.dump'));
preg_match_all('{%env\(((?:\w++:)*+\w++)\)%}', $file, $envVars);
$envVars = array_unique($envVars[1]);
$bag = $container->getParameterBag();
$getDefaultParameter = fn (string $name) => parent::get($name);
$getDefaultParameter = $getDefaultParameter->bindTo($bag, $bag::class);
$getEnvReflection = new \ReflectionMethod($container, 'getEnv');
$envs = [];
foreach ($envVars as $env) {
$processor = 'string';
if (false !== $i = strrpos($name = $env, ':')) {
$name = substr($env, $i + 1);
$processor = substr($env, 0, $i);
}
$defaultValue = ($hasDefault = $container->hasParameter("env($name)")) ? $getDefaultParameter("env($name)") : null;
if (false === ($runtimeValue = $_ENV[$name] ?? $_SERVER[$name] ?? getenv($name))) {
$runtimeValue = null;
}
$processedValue = ($hasRuntime = null !== $runtimeValue) || $hasDefault ? $getEnvReflection->invoke($container, $env) : null;
$envs["$name$processor"] = [
'name' => $name,
'processor' => $processor,
'default_available' => $hasDefault,
'default_value' => $defaultValue,
'runtime_available' => $hasRuntime,
'runtime_value' => $runtimeValue,
'processed_value' => $processedValue,
];
}
ksort($envs);
return array_values($envs);
}
protected function getServiceEdges(ContainerBuilder $container, string $serviceId): array
{
try {
return array_values(array_unique(array_map(
fn (ServiceReferenceGraphEdge $edge) => $edge->getSourceNode()->getId(),
$container->getCompiler()->getServiceReferenceGraph()->getNode($serviceId)->getInEdges()
)));
} catch (InvalidArgumentException $exception) {
return [];
}
}
private function filterRoutesByHttpMethod(RouteCollection $routes, string $method): RouteCollection
{
if (!$method) {
return $routes;
}
$filteredRoutes = clone $routes;
foreach ($filteredRoutes as $routeName => $route) {
if ($route->getMethods() && !\in_array($method, $route->getMethods(), true)) {
$filteredRoutes->remove($routeName);
}
}
return $filteredRoutes;
}
}

View File

@@ -0,0 +1,454 @@
<?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\Bundle\FrameworkBundle\Console\Descriptor;
use Symfony\Component\Console\Exception\LogicException;
use Symfony\Component\Console\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\Argument\AbstractArgument;
use Symfony\Component\DependencyInjection\Argument\ArgumentInterface;
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
/**
* @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com>
*
* @internal
*/
class JsonDescriptor extends Descriptor
{
protected function describeRouteCollection(RouteCollection $routes, array $options = []): void
{
$data = [];
foreach ($routes->all() as $name => $route) {
$data[$name] = $this->getRouteData($route);
if (($showAliases ??= $options['show_aliases'] ?? false) && $aliases = ($reverseAliases ??= $this->getReverseAliases($routes))[$name] ?? []) {
$data[$name]['aliases'] = $aliases;
}
}
$this->writeData($data, $options);
}
protected function describeRoute(Route $route, array $options = []): void
{
$this->writeData($this->getRouteData($route), $options);
}
protected function describeContainerParameters(ParameterBag $parameters, array $options = []): void
{
$this->writeData($this->sortParameters($parameters), $options);
}
protected function describeContainerTags(ContainerBuilder $container, array $options = []): void
{
$showHidden = isset($options['show_hidden']) && $options['show_hidden'];
$data = [];
foreach ($this->findDefinitionsByTag($container, $showHidden) as $tag => $definitions) {
$data[$tag] = [];
foreach ($definitions as $definition) {
$data[$tag][] = $this->getContainerDefinitionData($definition, true, $container, $options['id'] ?? null);
}
}
$this->writeData($data, $options);
}
protected function describeContainerService(object $service, array $options = [], ?ContainerBuilder $container = null): void
{
if (!isset($options['id'])) {
throw new \InvalidArgumentException('An "id" option must be provided.');
}
if ($service instanceof Alias) {
$this->describeContainerAlias($service, $options, $container);
} elseif ($service instanceof Definition) {
$this->writeData($this->getContainerDefinitionData($service, isset($options['omit_tags']) && $options['omit_tags'], $container, $options['id']), $options);
} else {
$this->writeData($service::class, $options);
}
}
protected function describeContainerServices(ContainerBuilder $container, array $options = []): void
{
$serviceIds = isset($options['tag']) && $options['tag']
? $this->sortTaggedServicesByPriority($container->findTaggedServiceIds($options['tag']))
: $this->sortServiceIds($container->getServiceIds());
$showHidden = isset($options['show_hidden']) && $options['show_hidden'];
$omitTags = isset($options['omit_tags']) && $options['omit_tags'];
$data = ['definitions' => [], 'aliases' => [], 'services' => []];
if (isset($options['filter'])) {
$serviceIds = array_filter($serviceIds, $options['filter']);
}
foreach ($serviceIds as $serviceId) {
$service = $this->resolveServiceDefinition($container, $serviceId);
if ($showHidden xor '.' === ($serviceId[0] ?? null)) {
continue;
}
if ($service instanceof Alias) {
$data['aliases'][$serviceId] = $this->getContainerAliasData($service);
} elseif ($service instanceof Definition) {
if ($service->hasTag('container.excluded')) {
continue;
}
$data['definitions'][$serviceId] = $this->getContainerDefinitionData($service, $omitTags, $container, $serviceId);
} else {
$data['services'][$serviceId] = $service::class;
}
}
$this->writeData($data, $options);
}
protected function describeContainerDefinition(Definition $definition, array $options = [], ?ContainerBuilder $container = null): void
{
$this->writeData($this->getContainerDefinitionData($definition, isset($options['omit_tags']) && $options['omit_tags'], $container, $options['id'] ?? null), $options);
}
protected function describeContainerAlias(Alias $alias, array $options = [], ?ContainerBuilder $container = null): void
{
if (!$container) {
$this->writeData($this->getContainerAliasData($alias), $options);
return;
}
$this->writeData(
[$this->getContainerAliasData($alias), $this->getContainerDefinitionData($container->getDefinition((string) $alias), isset($options['omit_tags']) && $options['omit_tags'], $container, (string) $alias)],
array_merge($options, ['id' => (string) $alias])
);
}
protected function describeEventDispatcherListeners(EventDispatcherInterface $eventDispatcher, array $options = []): void
{
$this->writeData($this->getEventDispatcherListenersData($eventDispatcher, $options), $options);
}
protected function describeCallable(mixed $callable, array $options = []): void
{
$this->writeData($this->getCallableData($callable), $options);
}
protected function describeContainerParameter(mixed $parameter, ?array $deprecation, array $options = []): void
{
$key = $options['parameter'] ?? '';
$data = [$key => $parameter];
if ($deprecation) {
$data['_deprecation'] = \sprintf('Since %s %s: %s', $deprecation[0], $deprecation[1], \sprintf(...\array_slice($deprecation, 2)));
}
$this->writeData($data, $options);
}
protected function describeContainerEnvVars(array $envs, array $options = []): void
{
throw new LogicException('Using the JSON format to debug environment variables is not supported.');
}
protected function describeContainerDeprecations(ContainerBuilder $container, array $options = []): void
{
$containerDeprecationFilePath = \sprintf('%s/%sDeprecations.log', $container->getParameter('kernel.build_dir'), $container->getParameter('kernel.container_class'));
if (!file_exists($containerDeprecationFilePath)) {
throw new RuntimeException('The deprecation file does not exist, please try warming the cache first.');
}
$logs = unserialize(file_get_contents($containerDeprecationFilePath));
$formattedLogs = [];
$remainingCount = 0;
foreach ($logs as $log) {
$formattedLogs[] = [
'message' => $log['message'],
'file' => $log['file'],
'line' => $log['line'],
'count' => $log['count'],
];
$remainingCount += $log['count'];
}
$this->writeData(['remainingCount' => $remainingCount, 'deprecations' => $formattedLogs], $options);
}
private function writeData(array $data, array $options): void
{
$flags = $options['json_encoding'] ?? 0;
// Recursively search for enum values, so we can replace it
// before json_encode (which will not display anything for \UnitEnum otherwise)
array_walk_recursive($data, static function (&$value) {
if ($value instanceof \UnitEnum) {
$value = ltrim(var_export($value, true), '\\');
}
});
$this->write(json_encode($data, $flags | \JSON_PRETTY_PRINT)."\n");
}
protected function getRouteData(Route $route): array
{
$data = [
'path' => $route->getPath(),
'pathRegex' => $route->compile()->getRegex(),
'host' => '' !== $route->getHost() ? $route->getHost() : 'ANY',
'hostRegex' => '' !== $route->getHost() ? $route->compile()->getHostRegex() : '',
'scheme' => $route->getSchemes() ? implode('|', $route->getSchemes()) : 'ANY',
'method' => $route->getMethods() ? implode('|', $route->getMethods()) : 'ANY',
'class' => $route::class,
'defaults' => $route->getDefaults(),
'requirements' => $route->getRequirements() ?: 'NO CUSTOM',
'options' => $route->getOptions(),
];
if ('' !== $route->getCondition()) {
$data['condition'] = $route->getCondition();
}
return $data;
}
protected function sortParameters(ParameterBag $parameters): array
{
$sortedParameters = parent::sortParameters($parameters);
if ($deprecated = $parameters->allDeprecated()) {
$deprecations = [];
foreach ($deprecated as $parameter => $deprecation) {
$deprecations[$parameter] = \sprintf('Since %s %s: %s', $deprecation[0], $deprecation[1], \sprintf(...\array_slice($deprecation, 2)));
}
$sortedParameters['_deprecations'] = $deprecations;
}
return $sortedParameters;
}
private function getContainerDefinitionData(Definition $definition, bool $omitTags = false, ?ContainerBuilder $container = null, ?string $id = null): array
{
$data = [
'class' => (string) $definition->getClass(),
'public' => $definition->isPublic() && !$definition->isPrivate(),
'synthetic' => $definition->isSynthetic(),
'lazy' => $definition->isLazy(),
'shared' => $definition->isShared(),
'abstract' => $definition->isAbstract(),
'autowire' => $definition->isAutowired(),
'autoconfigure' => $definition->isAutoconfigured(),
];
if ($definition->isDeprecated()) {
$data['deprecated'] = true;
$data['deprecation_message'] = $definition->getDeprecation($id)['message'];
} else {
$data['deprecated'] = false;
}
if ('' !== $classDescription = $this->getClassDescription((string) $definition->getClass())) {
$data['description'] = $classDescription;
}
$data['arguments'] = $this->describeValue($definition->getArguments(), $omitTags, $container, $id);
$data['file'] = $definition->getFile();
if ($factory = $definition->getFactory()) {
if (\is_array($factory)) {
if ($factory[0] instanceof Reference) {
$data['factory_service'] = (string) $factory[0];
} elseif ($factory[0] instanceof Definition) {
$data['factory_service'] = \sprintf('inline factory service (%s)', $factory[0]->getClass() ?? 'class not configured');
} else {
$data['factory_class'] = $factory[0];
}
$data['factory_method'] = $factory[1];
} else {
$data['factory_function'] = $factory;
}
}
$calls = $definition->getMethodCalls();
if (\count($calls) > 0) {
$data['calls'] = [];
foreach ($calls as $callData) {
$data['calls'][] = $callData[0];
}
}
if (!$omitTags) {
$data['tags'] = [];
foreach ($this->sortTagsByPriority($definition->getTags()) as $tagName => $tagData) {
foreach ($tagData as $parameters) {
$data['tags'][] = ['name' => $tagName, 'parameters' => $parameters];
}
}
}
$data['usages'] = null !== $container && null !== $id ? $this->getServiceEdges($container, $id) : [];
return $data;
}
private function getContainerAliasData(Alias $alias): array
{
return [
'service' => (string) $alias,
'public' => $alias->isPublic() && !$alias->isPrivate(),
];
}
private function getEventDispatcherListenersData(EventDispatcherInterface $eventDispatcher, array $options): array
{
$data = [];
$event = $options['event'] ?? null;
if (null !== $event) {
foreach ($eventDispatcher->getListeners($event) as $listener) {
$l = $this->getCallableData($listener);
$l['priority'] = $eventDispatcher->getListenerPriority($event, $listener);
$data[] = $l;
}
} else {
$registeredListeners = \array_key_exists('events', $options) ? array_combine($options['events'], array_map(fn ($event) => $eventDispatcher->getListeners($event), $options['events'])) : $eventDispatcher->getListeners();
ksort($registeredListeners);
foreach ($registeredListeners as $eventListened => $eventListeners) {
foreach ($eventListeners as $eventListener) {
$l = $this->getCallableData($eventListener);
$l['priority'] = $eventDispatcher->getListenerPriority($eventListened, $eventListener);
$data[$eventListened][] = $l;
}
}
}
return $data;
}
private function getCallableData(mixed $callable): array
{
$data = [];
if (\is_array($callable)) {
$data['type'] = 'function';
if (\is_object($callable[0])) {
$data['name'] = $callable[1];
$data['class'] = $callable[0]::class;
} else {
if (!str_starts_with($callable[1], 'parent::')) {
$data['name'] = $callable[1];
$data['class'] = $callable[0];
$data['static'] = true;
} else {
$data['name'] = substr($callable[1], 8);
$data['class'] = $callable[0];
$data['static'] = true;
$data['parent'] = true;
}
}
return $data;
}
if (\is_string($callable)) {
$data['type'] = 'function';
if (!str_contains($callable, '::')) {
$data['name'] = $callable;
} else {
$callableParts = explode('::', $callable);
$data['name'] = $callableParts[1];
$data['class'] = $callableParts[0];
$data['static'] = true;
}
return $data;
}
if ($callable instanceof \Closure) {
$data['type'] = 'closure';
$r = new \ReflectionFunction($callable);
if ($r->isAnonymous()) {
return $data;
}
$data['name'] = $r->name;
if ($class = $r->getClosureCalledClass()) {
$data['class'] = $class->name;
if (!$r->getClosureThis()) {
$data['static'] = true;
}
}
return $data;
}
if (method_exists($callable, '__invoke')) {
$data['type'] = 'object';
$data['name'] = $callable::class;
return $data;
}
throw new \InvalidArgumentException('Callable is not describable.');
}
private function describeValue($value, bool $omitTags, ?ContainerBuilder $container = null, ?string $id = null): mixed
{
if (\is_array($value)) {
$data = [];
foreach ($value as $k => $v) {
$data[$k] = $this->describeValue($v, $omitTags, $container, $id);
}
return $data;
}
if ($value instanceof ServiceClosureArgument) {
$value = $value->getValues()[0];
}
if ($value instanceof Reference) {
return [
'type' => 'service',
'id' => (string) $value,
];
}
if ($value instanceof AbstractArgument) {
return ['type' => 'abstract', 'text' => $value->getText()];
}
if ($value instanceof ArgumentInterface) {
return $this->describeValue($value->getValues(), $omitTags, $container, $id);
}
if ($value instanceof Definition) {
return $this->getContainerDefinitionData($value, $omitTags, $container, $id);
}
return $value;
}
}

View File

@@ -0,0 +1,448 @@
<?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\Bundle\FrameworkBundle\Console\Descriptor;
use Symfony\Component\Console\Exception\LogicException;
use Symfony\Component\Console\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
/**
* @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com>
*
* @internal
*/
class MarkdownDescriptor extends Descriptor
{
protected function describeRouteCollection(RouteCollection $routes, array $options = []): void
{
$first = true;
foreach ($routes->all() as $name => $route) {
if ($first) {
$first = false;
} else {
$this->write("\n\n");
}
$this->describeRoute($route, ['name' => $name]);
if (($showAliases ??= $options['show_aliases'] ?? false) && $aliases = ($reverseAliases ??= $this->getReverseAliases($routes))[$name] ?? []) {
$this->write(\sprintf("- Aliases: \n%s", implode("\n", array_map(static fn (string $alias): string => \sprintf(' - %s', $alias), $aliases))));
}
}
$this->write("\n");
}
protected function describeRoute(Route $route, array $options = []): void
{
$output = '- Path: '.$route->getPath()
."\n".'- Path Regex: '.$route->compile()->getRegex()
."\n".'- Host: '.('' !== $route->getHost() ? $route->getHost() : 'ANY')
."\n".'- Host Regex: '.('' !== $route->getHost() ? $route->compile()->getHostRegex() : '')
."\n".'- Scheme: '.($route->getSchemes() ? implode('|', $route->getSchemes()) : 'ANY')
."\n".'- Method: '.($route->getMethods() ? implode('|', $route->getMethods()) : 'ANY')
."\n".'- Class: '.$route::class
."\n".'- Defaults: '.$this->formatRouterConfig($route->getDefaults())
."\n".'- Requirements: '.($route->getRequirements() ? $this->formatRouterConfig($route->getRequirements()) : 'NO CUSTOM')
."\n".'- Options: '.$this->formatRouterConfig($route->getOptions());
if ('' !== $route->getCondition()) {
$output .= "\n".'- Condition: '.$route->getCondition();
}
$this->write(isset($options['name'])
? $options['name']."\n".str_repeat('-', \strlen($options['name']))."\n\n".$output
: $output);
$this->write("\n");
}
protected function describeContainerParameters(ParameterBag $parameters, array $options = []): void
{
$deprecatedParameters = $parameters->allDeprecated();
$this->write("Container parameters\n====================\n");
foreach ($this->sortParameters($parameters) as $key => $value) {
$this->write(\sprintf(
"\n- `%s`: `%s`%s",
$key,
$this->formatParameter($value),
isset($deprecatedParameters[$key]) ? \sprintf(' *Since %s %s: %s*', $deprecatedParameters[$key][0], $deprecatedParameters[$key][1], \sprintf(...\array_slice($deprecatedParameters[$key], 2))) : ''
));
}
}
protected function describeContainerTags(ContainerBuilder $container, array $options = []): void
{
$showHidden = isset($options['show_hidden']) && $options['show_hidden'];
$this->write("Container tags\n==============");
foreach ($this->findDefinitionsByTag($container, $showHidden) as $tag => $definitions) {
$this->write("\n\n".$tag."\n".str_repeat('-', \strlen($tag)));
foreach ($definitions as $serviceId => $definition) {
$this->write("\n\n");
$this->describeContainerDefinition($definition, ['omit_tags' => true, 'id' => $serviceId], $container);
}
}
}
protected function describeContainerService(object $service, array $options = [], ?ContainerBuilder $container = null): void
{
if (!isset($options['id'])) {
throw new \InvalidArgumentException('An "id" option must be provided.');
}
$childOptions = array_merge($options, ['id' => $options['id'], 'as_array' => true]);
if ($service instanceof Alias) {
$this->describeContainerAlias($service, $childOptions, $container);
} elseif ($service instanceof Definition) {
$this->describeContainerDefinition($service, $childOptions, $container);
} else {
$this->write(\sprintf('**`%s`:** `%s`', $options['id'], $service::class));
}
}
protected function describeContainerDeprecations(ContainerBuilder $container, array $options = []): void
{
$containerDeprecationFilePath = \sprintf('%s/%sDeprecations.log', $container->getParameter('kernel.build_dir'), $container->getParameter('kernel.container_class'));
if (!file_exists($containerDeprecationFilePath)) {
throw new RuntimeException('The deprecation file does not exist, please try warming the cache first.');
}
$logs = unserialize(file_get_contents($containerDeprecationFilePath));
if (0 === \count($logs)) {
$this->write("## There are no deprecations in the logs!\n");
return;
}
$formattedLogs = [];
$remainingCount = 0;
foreach ($logs as $log) {
$formattedLogs[] = \sprintf("- %sx: \"%s\" in %s:%s\n", $log['count'], $log['message'], $log['file'], $log['line']);
$remainingCount += $log['count'];
}
$this->write(\sprintf("## Remaining deprecations (%s)\n\n", $remainingCount));
foreach ($formattedLogs as $formattedLog) {
$this->write($formattedLog);
}
}
protected function describeContainerServices(ContainerBuilder $container, array $options = []): void
{
$showHidden = isset($options['show_hidden']) && $options['show_hidden'];
$title = $showHidden ? 'Hidden services' : 'Services';
if (isset($options['tag'])) {
$title .= ' with tag `'.$options['tag'].'`';
}
$this->write($title."\n".str_repeat('=', \strlen($title)));
$serviceIds = isset($options['tag']) && $options['tag']
? $this->sortTaggedServicesByPriority($container->findTaggedServiceIds($options['tag']))
: $this->sortServiceIds($container->getServiceIds());
$services = ['definitions' => [], 'aliases' => [], 'services' => []];
if (isset($options['filter'])) {
$serviceIds = array_filter($serviceIds, $options['filter']);
}
foreach ($serviceIds as $serviceId) {
$service = $this->resolveServiceDefinition($container, $serviceId);
if ($showHidden xor '.' === ($serviceId[0] ?? null)) {
continue;
}
if ($service instanceof Alias) {
$services['aliases'][$serviceId] = $service;
} elseif ($service instanceof Definition) {
if ($service->hasTag('container.excluded')) {
continue;
}
$services['definitions'][$serviceId] = $service;
} else {
$services['services'][$serviceId] = $service;
}
}
if (!empty($services['definitions'])) {
$this->write("\n\nDefinitions\n-----------\n");
foreach ($services['definitions'] as $id => $service) {
$this->write("\n");
$this->describeContainerDefinition($service, ['id' => $id], $container);
}
}
if (!empty($services['aliases'])) {
$this->write("\n\nAliases\n-------\n");
foreach ($services['aliases'] as $id => $service) {
$this->write("\n");
$this->describeContainerAlias($service, ['id' => $id]);
}
}
if (!empty($services['services'])) {
$this->write("\n\nServices\n--------\n");
foreach ($services['services'] as $id => $service) {
$this->write("\n");
$this->write(\sprintf('- `%s`: `%s`', $id, $service::class));
}
}
}
protected function describeContainerDefinition(Definition $definition, array $options = [], ?ContainerBuilder $container = null): void
{
$output = '';
if ('' !== $classDescription = $this->getClassDescription((string) $definition->getClass())) {
$output .= '- Description: `'.$classDescription.'`'."\n";
}
$output .= '- Class: `'.$definition->getClass().'`'
."\n".'- Public: '.($definition->isPublic() && !$definition->isPrivate() ? 'yes' : 'no')
."\n".'- Synthetic: '.($definition->isSynthetic() ? 'yes' : 'no')
."\n".'- Lazy: '.($definition->isLazy() ? 'yes' : 'no')
."\n".'- Shared: '.($definition->isShared() ? 'yes' : 'no')
."\n".'- Abstract: '.($definition->isAbstract() ? 'yes' : 'no')
."\n".'- Autowired: '.($definition->isAutowired() ? 'yes' : 'no')
."\n".'- Autoconfigured: '.($definition->isAutoconfigured() ? 'yes' : 'no')
;
if ($definition->isDeprecated()) {
$output .= "\n".'- Deprecated: yes';
$output .= "\n".'- Deprecation message: '.$definition->getDeprecation($options['id'])['message'];
} else {
$output .= "\n".'- Deprecated: no';
}
$output .= "\n".'- Arguments: '.($definition->getArguments() ? 'yes' : 'no');
if ($definition->getFile()) {
$output .= "\n".'- File: `'.$definition->getFile().'`';
}
if ($factory = $definition->getFactory()) {
if (\is_array($factory)) {
if ($factory[0] instanceof Reference) {
$output .= "\n".'- Factory Service: `'.$factory[0].'`';
} elseif ($factory[0] instanceof Definition) {
$output .= "\n".\sprintf('- Factory Service: inline factory service (%s)', $factory[0]->getClass() ? \sprintf('`%s`', $factory[0]->getClass()) : 'not configured');
} else {
$output .= "\n".'- Factory Class: `'.$factory[0].'`';
}
$output .= "\n".'- Factory Method: `'.$factory[1].'`';
} else {
$output .= "\n".'- Factory Function: `'.$factory.'`';
}
}
$calls = $definition->getMethodCalls();
foreach ($calls as $callData) {
$output .= "\n".'- Call: `'.$callData[0].'`';
}
if (!(isset($options['omit_tags']) && $options['omit_tags'])) {
foreach ($this->sortTagsByPriority($definition->getTags()) as $tagName => $tagData) {
foreach ($tagData as $parameters) {
$output .= "\n".'- Tag: `'.$tagName.'`';
foreach ($parameters as $name => $value) {
$output .= "\n".' - '.ucfirst($name).': '.(\is_array($value) ? $this->formatParameter($value) : $value);
}
}
}
}
$inEdges = null !== $container && isset($options['id']) ? $this->getServiceEdges($container, $options['id']) : [];
$output .= "\n".'- Usages: '.($inEdges ? implode(', ', $inEdges) : 'none');
$this->write(isset($options['id']) ? \sprintf("### %s\n\n%s\n", $options['id'], $output) : $output);
}
protected function describeContainerAlias(Alias $alias, array $options = [], ?ContainerBuilder $container = null): void
{
$output = '- Service: `'.$alias.'`'
."\n".'- Public: '.($alias->isPublic() && !$alias->isPrivate() ? 'yes' : 'no');
if (!isset($options['id'])) {
$this->write($output);
return;
}
$this->write(\sprintf("### %s\n\n%s\n", $options['id'], $output));
if (!$container) {
return;
}
$this->write("\n");
$this->describeContainerDefinition($container->getDefinition((string) $alias), array_merge($options, ['id' => (string) $alias]), $container);
}
protected function describeContainerParameter(mixed $parameter, ?array $deprecation, array $options = []): void
{
if (isset($options['parameter'])) {
$this->write(\sprintf("%s\n%s\n\n%s%s", $options['parameter'], str_repeat('=', \strlen($options['parameter'])), $this->formatParameter($parameter), $deprecation ? \sprintf("\n\n*Since %s %s: %s*", $deprecation[0], $deprecation[1], \sprintf(...\array_slice($deprecation, 2))) : ''));
} else {
$this->write($parameter);
}
}
protected function describeContainerEnvVars(array $envs, array $options = []): void
{
throw new LogicException('Using the markdown format to debug environment variables is not supported.');
}
protected function describeEventDispatcherListeners(EventDispatcherInterface $eventDispatcher, array $options = []): void
{
$event = $options['event'] ?? null;
$dispatcherServiceName = $options['dispatcher_service_name'] ?? null;
$title = 'Registered listeners';
if (null !== $dispatcherServiceName) {
$title .= \sprintf(' of event dispatcher "%s"', $dispatcherServiceName);
}
if (null !== $event) {
$title .= \sprintf(' for event `%s` ordered by descending priority', $event);
$registeredListeners = $eventDispatcher->getListeners($event);
} else {
// Try to see if "events" exists
$registeredListeners = \array_key_exists('events', $options) ? array_combine($options['events'], array_map(fn ($event) => $eventDispatcher->getListeners($event), $options['events'])) : $eventDispatcher->getListeners();
}
$this->write(\sprintf('# %s', $title)."\n");
if (null !== $event) {
foreach ($registeredListeners as $order => $listener) {
$this->write("\n".\sprintf('## Listener %d', $order + 1)."\n");
$this->describeCallable($listener);
$this->write(\sprintf('- Priority: `%d`', $eventDispatcher->getListenerPriority($event, $listener))."\n");
}
} else {
ksort($registeredListeners);
foreach ($registeredListeners as $eventListened => $eventListeners) {
$this->write("\n".\sprintf('## %s', $eventListened)."\n");
foreach ($eventListeners as $order => $eventListener) {
$this->write("\n".\sprintf('### Listener %d', $order + 1)."\n");
$this->describeCallable($eventListener);
$this->write(\sprintf('- Priority: `%d`', $eventDispatcher->getListenerPriority($eventListened, $eventListener))."\n");
}
}
}
}
protected function describeCallable(mixed $callable, array $options = []): void
{
$string = '';
if (\is_array($callable)) {
$string .= "\n- Type: `function`";
if (\is_object($callable[0])) {
$string .= "\n".\sprintf('- Name: `%s`', $callable[1]);
$string .= "\n".\sprintf('- Class: `%s`', $callable[0]::class);
} else {
if (!str_starts_with($callable[1], 'parent::')) {
$string .= "\n".\sprintf('- Name: `%s`', $callable[1]);
$string .= "\n".\sprintf('- Class: `%s`', $callable[0]);
$string .= "\n- Static: yes";
} else {
$string .= "\n".\sprintf('- Name: `%s`', substr($callable[1], 8));
$string .= "\n".\sprintf('- Class: `%s`', $callable[0]);
$string .= "\n- Static: yes";
$string .= "\n- Parent: yes";
}
}
$this->write($string."\n");
return;
}
if (\is_string($callable)) {
$string .= "\n- Type: `function`";
if (!str_contains($callable, '::')) {
$string .= "\n".\sprintf('- Name: `%s`', $callable);
} else {
$callableParts = explode('::', $callable);
$string .= "\n".\sprintf('- Name: `%s`', $callableParts[1]);
$string .= "\n".\sprintf('- Class: `%s`', $callableParts[0]);
$string .= "\n- Static: yes";
}
$this->write($string."\n");
return;
}
if ($callable instanceof \Closure) {
$string .= "\n- Type: `closure`";
$r = new \ReflectionFunction($callable);
if ($r->isAnonymous()) {
$this->write($string."\n");
return;
}
$string .= "\n".\sprintf('- Name: `%s`', $r->name);
if ($class = $r->getClosureCalledClass()) {
$string .= "\n".\sprintf('- Class: `%s`', $class->name);
if (!$r->getClosureThis()) {
$string .= "\n- Static: yes";
}
}
$this->write($string."\n");
return;
}
if (method_exists($callable, '__invoke')) {
$string .= "\n- Type: `object`";
$string .= "\n".\sprintf('- Name: `%s`', $callable::class);
$this->write($string."\n");
return;
}
throw new \InvalidArgumentException('Callable is not describable.');
}
private function formatRouterConfig(array $array): string
{
if (!$array) {
return 'NONE';
}
$string = '';
ksort($array);
foreach ($array as $name => $value) {
$string .= "\n".' - `'.$name.'`: '.$this->formatValue($value);
}
return $string;
}
}

View File

@@ -0,0 +1,673 @@
<?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\Bundle\FrameworkBundle\Console\Descriptor;
use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Helper\Dumper;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Helper\TableCell;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\Argument\AbstractArgument;
use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
use Symfony\Component\DependencyInjection\Argument\ServiceLocatorArgument;
use Symfony\Component\DependencyInjection\Argument\TaggedIteratorArgument;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\ErrorHandler\ErrorRenderer\FileLinkFormatter;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
/**
* @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com>
*
* @internal
*/
class TextDescriptor extends Descriptor
{
public function __construct(
private ?FileLinkFormatter $fileLinkFormatter = null,
) {
}
protected function describeRouteCollection(RouteCollection $routes, array $options = []): void
{
$showControllers = isset($options['show_controllers']) && $options['show_controllers'];
$tableHeaders = ['Name', 'Method', 'Scheme', 'Host', 'Path'];
if ($showControllers) {
$tableHeaders[] = 'Controller';
}
if ($showAliases = $options['show_aliases'] ?? false) {
$tableHeaders[] = 'Aliases';
}
$tableRows = [];
foreach ($routes->all() as $name => $route) {
$controller = $route->getDefault('_controller');
$row = [
$name,
$route->getMethods() ? implode('|', $route->getMethods()) : 'ANY',
$route->getSchemes() ? implode('|', $route->getSchemes()) : 'ANY',
'' !== $route->getHost() ? $route->getHost() : 'ANY',
$this->formatControllerLink($controller, $route->getPath(), $options['container'] ?? null),
];
if ($showControllers) {
$row[] = $controller ? $this->formatControllerLink($controller, $this->formatCallable($controller), $options['container'] ?? null) : '';
}
if ($showAliases) {
$row[] = implode('|', ($reverseAliases ??= $this->getReverseAliases($routes))[$name] ?? []);
}
$tableRows[] = $row;
}
if (isset($options['output'])) {
$options['output']->table($tableHeaders, $tableRows);
} else {
$table = new Table($this->getOutput());
$table->setHeaders($tableHeaders)->setRows($tableRows);
$table->render();
}
}
protected function describeRoute(Route $route, array $options = []): void
{
$defaults = $route->getDefaults();
if (isset($defaults['_controller'])) {
$defaults['_controller'] = $this->formatControllerLink($defaults['_controller'], $this->formatCallable($defaults['_controller']), $options['container'] ?? null);
}
$tableHeaders = ['Property', 'Value'];
$tableRows = [
['Route Name', $options['name'] ?? ''],
['Path', $route->getPath()],
['Path Regex', $route->compile()->getRegex()],
['Host', '' !== $route->getHost() ? $route->getHost() : 'ANY'],
['Host Regex', '' !== $route->getHost() ? $route->compile()->getHostRegex() : ''],
['Scheme', $route->getSchemes() ? implode('|', $route->getSchemes()) : 'ANY'],
['Method', $route->getMethods() ? implode('|', $route->getMethods()) : 'ANY'],
['Requirements', $route->getRequirements() ? $this->formatRouterConfig($route->getRequirements()) : 'NO CUSTOM'],
['Class', $route::class],
['Defaults', $this->formatRouterConfig($defaults)],
['Options', $this->formatRouterConfig($route->getOptions())],
];
if ('' !== $route->getCondition()) {
$tableRows[] = ['Condition', $route->getCondition()];
}
$table = new Table($this->getOutput());
$table->setHeaders($tableHeaders)->setRows($tableRows);
$table->render();
}
protected function describeContainerParameters(ParameterBag $parameters, array $options = []): void
{
$tableHeaders = ['Parameter', 'Value'];
$deprecatedParameters = $parameters->allDeprecated();
$tableRows = [];
foreach ($this->sortParameters($parameters) as $parameter => $value) {
$tableRows[] = [$parameter, $this->formatParameter($value)];
if (isset($deprecatedParameters[$parameter])) {
$tableRows[] = [new TableCell(
\sprintf('<comment>(Since %s %s: %s)</comment>', $deprecatedParameters[$parameter][0], $deprecatedParameters[$parameter][1], \sprintf(...\array_slice($deprecatedParameters[$parameter], 2))),
['colspan' => 2]
)];
}
}
$options['output']->title('Symfony Container Parameters');
$options['output']->table($tableHeaders, $tableRows);
}
protected function describeContainerTags(ContainerBuilder $container, array $options = []): void
{
$showHidden = isset($options['show_hidden']) && $options['show_hidden'];
if ($showHidden) {
$options['output']->title('Symfony Container Hidden Tags');
} else {
$options['output']->title('Symfony Container Tags');
}
foreach ($this->findDefinitionsByTag($container, $showHidden) as $tag => $definitions) {
$options['output']->section(\sprintf('"%s" tag', $tag));
$options['output']->listing(array_keys($definitions));
}
}
protected function describeContainerService(object $service, array $options = [], ?ContainerBuilder $container = null): void
{
if (!isset($options['id'])) {
throw new \InvalidArgumentException('An "id" option must be provided.');
}
if ($service instanceof Alias) {
$this->describeContainerAlias($service, $options, $container);
} elseif ($service instanceof Definition) {
$this->describeContainerDefinition($service, $options, $container);
} else {
$options['output']->title(\sprintf('Information for Service "<info>%s</info>"', $options['id']));
$options['output']->table(
['Service ID', 'Class'],
[
[$options['id'], $service::class],
]
);
}
}
protected function describeContainerServices(ContainerBuilder $container, array $options = []): void
{
$showHidden = isset($options['show_hidden']) && $options['show_hidden'];
$showTag = $options['tag'] ?? null;
if ($showHidden) {
$title = 'Symfony Container Hidden Services';
} else {
$title = 'Symfony Container Services';
}
if ($showTag) {
$title .= \sprintf(' Tagged with "%s" Tag', $options['tag']);
}
$options['output']->title($title);
$serviceIds = isset($options['tag']) && $options['tag']
? $this->sortTaggedServicesByPriority($container->findTaggedServiceIds($options['tag']))
: $this->sortServiceIds($container->getServiceIds());
$maxTags = [];
if (isset($options['filter'])) {
$serviceIds = array_filter($serviceIds, $options['filter']);
}
foreach ($serviceIds as $key => $serviceId) {
$definition = $this->resolveServiceDefinition($container, $serviceId);
// filter out hidden services unless shown explicitly
if ($showHidden xor '.' === ($serviceId[0] ?? null)) {
unset($serviceIds[$key]);
continue;
}
if ($definition instanceof Definition) {
if ($definition->hasTag('container.excluded')) {
unset($serviceIds[$key]);
continue;
}
if ($showTag) {
$tags = $definition->getTag($showTag);
foreach ($tags as $tag) {
foreach ($tag as $key => $value) {
if (!isset($maxTags[$key])) {
$maxTags[$key] = \strlen($key);
}
if (\is_array($value)) {
$value = $this->formatParameter($value);
}
if (\strlen($value) > $maxTags[$key]) {
$maxTags[$key] = \strlen($value);
}
}
}
}
}
}
$tagsCount = \count($maxTags);
$tagsNames = array_keys($maxTags);
$tableHeaders = array_merge(['Service ID'], $tagsNames, ['Class name']);
$tableRows = [];
$rawOutput = isset($options['raw_text']) && $options['raw_text'];
foreach ($serviceIds as $serviceId) {
$definition = $this->resolveServiceDefinition($container, $serviceId);
$styledServiceId = $rawOutput ? $serviceId : \sprintf('<fg=cyan>%s</fg=cyan>', OutputFormatter::escape($serviceId));
if ($definition instanceof Definition) {
if ($showTag) {
foreach ($this->sortByPriority($definition->getTag($showTag)) as $key => $tag) {
$tagValues = [];
foreach ($tagsNames as $tagName) {
if (\is_array($tagValue = $tag[$tagName] ?? '')) {
$tagValue = $this->formatParameter($tagValue);
}
$tagValues[] = $tagValue;
}
if (0 === $key) {
$tableRows[] = array_merge([$serviceId], $tagValues, [$definition->getClass()]);
} else {
$tableRows[] = array_merge([' (same service as previous, another tag)'], $tagValues, ['']);
}
}
} else {
$tableRows[] = [$styledServiceId, $definition->getClass()];
}
} elseif ($definition instanceof Alias) {
$alias = $definition;
$tableRows[] = array_merge([$styledServiceId, \sprintf('alias for "%s"', $alias)], $tagsCount ? array_fill(0, $tagsCount, '') : []);
} else {
$tableRows[] = array_merge([$styledServiceId, $definition::class], $tagsCount ? array_fill(0, $tagsCount, '') : []);
}
}
$options['output']->table($tableHeaders, $tableRows);
}
protected function describeContainerDefinition(Definition $definition, array $options = [], ?ContainerBuilder $container = null): void
{
if (isset($options['id'])) {
$options['output']->title(\sprintf('Information for Service "<info>%s</info>"', $options['id']));
}
if ('' !== $classDescription = $this->getClassDescription((string) $definition->getClass())) {
$options['output']->text($classDescription."\n");
}
$tableHeaders = ['Option', 'Value'];
$tableRows[] = ['Service ID', $options['id'] ?? '-'];
$tableRows[] = ['Class', $definition->getClass() ?: '-'];
$omitTags = isset($options['omit_tags']) && $options['omit_tags'];
if (!$omitTags && ($tags = $definition->getTags())) {
$tagInformation = [];
foreach ($tags as $tagName => $tagData) {
foreach ($tagData as $tagParameters) {
$parameters = array_map(fn ($key, $value) => \sprintf('<info>%s</info>: %s', $key, \is_array($value) ? $this->formatParameter($value) : $value), array_keys($tagParameters), array_values($tagParameters));
$parameters = implode(', ', $parameters);
if ('' === $parameters) {
$tagInformation[] = \sprintf('%s', $tagName);
} else {
$tagInformation[] = \sprintf('%s (%s)', $tagName, $parameters);
}
}
}
$tagInformation = implode("\n", $tagInformation);
} else {
$tagInformation = '-';
}
$tableRows[] = ['Tags', $tagInformation];
$calls = $definition->getMethodCalls();
if (\count($calls) > 0) {
$callInformation = [];
foreach ($calls as $call) {
$callInformation[] = $call[0];
}
$tableRows[] = ['Calls', implode(', ', $callInformation)];
}
$tableRows[] = ['Public', $definition->isPublic() && !$definition->isPrivate() ? 'yes' : 'no'];
$tableRows[] = ['Synthetic', $definition->isSynthetic() ? 'yes' : 'no'];
$tableRows[] = ['Lazy', $definition->isLazy() ? 'yes' : 'no'];
$tableRows[] = ['Shared', $definition->isShared() ? 'yes' : 'no'];
$tableRows[] = ['Abstract', $definition->isAbstract() ? 'yes' : 'no'];
$tableRows[] = ['Autowired', $definition->isAutowired() ? 'yes' : 'no'];
$tableRows[] = ['Autoconfigured', $definition->isAutoconfigured() ? 'yes' : 'no'];
if ($definition->getFile()) {
$tableRows[] = ['Required File', $definition->getFile()];
}
if ($factory = $definition->getFactory()) {
if (\is_array($factory)) {
if ($factory[0] instanceof Reference) {
$tableRows[] = ['Factory Service', $factory[0]];
} elseif ($factory[0] instanceof Definition) {
$tableRows[] = ['Factory Service', \sprintf('inline factory service (%s)', $factory[0]->getClass() ?? 'class not configured')];
} else {
$tableRows[] = ['Factory Class', $factory[0]];
}
$tableRows[] = ['Factory Method', $factory[1]];
} else {
$tableRows[] = ['Factory Function', $factory];
}
}
$argumentsInformation = [];
if ($arguments = $definition->getArguments()) {
foreach ($arguments as $argument) {
if ($argument instanceof ServiceClosureArgument) {
$argument = $argument->getValues()[0];
}
if ($argument instanceof Reference) {
$argumentsInformation[] = \sprintf('Service(%s)', (string) $argument);
} elseif ($argument instanceof IteratorArgument) {
if ($argument instanceof TaggedIteratorArgument) {
$argumentsInformation[] = \sprintf('Tagged Iterator for "%s"%s', $argument->getTag(), $options['is_debug'] ? '' : \sprintf(' (%d element(s))', \count($argument->getValues())));
} else {
$argumentsInformation[] = \sprintf('Iterator (%d element(s))', \count($argument->getValues()));
}
foreach ($argument->getValues() as $ref) {
$argumentsInformation[] = \sprintf('- Service(%s)', $ref);
}
} elseif ($argument instanceof ServiceLocatorArgument) {
$argumentsInformation[] = \sprintf('Service locator (%d element(s))', \count($argument->getValues()));
} elseif ($argument instanceof Definition) {
$argumentsInformation[] = 'Inlined Service';
} elseif ($argument instanceof \UnitEnum) {
$argumentsInformation[] = ltrim(var_export($argument, true), '\\');
} elseif ($argument instanceof AbstractArgument) {
$argumentsInformation[] = \sprintf('Abstract argument (%s)', $argument->getText());
} else {
$argumentsInformation[] = \is_array($argument) ? \sprintf('Array (%d element(s))', \count($argument)) : $argument;
}
}
$tableRows[] = ['Arguments', implode("\n", $argumentsInformation)];
}
$inEdges = null !== $container && isset($options['id']) ? $this->getServiceEdges($container, $options['id']) : [];
$tableRows[] = ['Usages', $inEdges ? implode(\PHP_EOL, $inEdges) : 'none'];
$options['output']->table($tableHeaders, $tableRows);
}
protected function describeContainerDeprecations(ContainerBuilder $container, array $options = []): void
{
$containerDeprecationFilePath = \sprintf('%s/%sDeprecations.log', $container->getParameter('kernel.build_dir'), $container->getParameter('kernel.container_class'));
if (!file_exists($containerDeprecationFilePath)) {
$options['output']->warning('The deprecation file does not exist, please try warming the cache first.');
return;
}
$logs = unserialize(file_get_contents($containerDeprecationFilePath));
if (0 === \count($logs)) {
$options['output']->success('There are no deprecations in the logs!');
return;
}
$formattedLogs = [];
$remainingCount = 0;
foreach ($logs as $log) {
$formattedLogs[] = \sprintf("%sx: %s\n in %s:%s", $log['count'], $log['message'], $log['file'], $log['line']);
$remainingCount += $log['count'];
}
$options['output']->title(\sprintf('Remaining deprecations (%s)', $remainingCount));
$options['output']->listing($formattedLogs);
}
protected function describeContainerAlias(Alias $alias, array $options = [], ?ContainerBuilder $container = null): void
{
if ($alias->isPublic() && !$alias->isPrivate()) {
$options['output']->comment(\sprintf('This service is a <info>public</info> alias for the service <info>%s</info>', (string) $alias));
} else {
$options['output']->comment(\sprintf('This service is a <comment>private</comment> alias for the service <info>%s</info>', (string) $alias));
}
if (!$container) {
return;
}
$this->describeContainerDefinition($container->getDefinition((string) $alias), array_merge($options, ['id' => (string) $alias]), $container);
}
protected function describeContainerParameter(mixed $parameter, ?array $deprecation, array $options = []): void
{
$parameterName = $options['parameter'];
$rows = [
[$parameterName, $this->formatParameter($parameter)],
];
if ($deprecation) {
$rows[] = [new TableCell(
\sprintf('<comment>(Since %s %s: %s)</comment>', $deprecation[0], $deprecation[1], \sprintf(...\array_slice($deprecation, 2))),
['colspan' => 2]
)];
}
$options['output']->table(['Parameter', 'Value'], $rows);
}
protected function describeContainerEnvVars(array $envs, array $options = []): void
{
$dump = new Dumper($this->output);
$options['output']->title('Symfony Container Environment Variables');
if (null !== $name = $options['name'] ?? null) {
$options['output']->comment('Displaying detailed environment variable usage matching '.$name);
$matches = false;
foreach ($envs as $env) {
if ($name === $env['name'] || false !== stripos($env['name'], $name)) {
$matches = true;
$options['output']->section('%env('.$env['processor'].':'.$env['name'].')%');
$options['output']->table([], [
['<info>Default value</>', $env['default_available'] ? $dump($env['default_value']) : 'n/a'],
['<info>Real value</>', $env['runtime_available'] ? $dump($env['runtime_value']) : 'n/a'],
['<info>Processed value</>', $env['default_available'] || $env['runtime_available'] ? $dump($env['processed_value']) : 'n/a'],
]);
}
}
if (!$matches) {
$options['output']->block('None of the environment variables match this name.');
} else {
$options['output']->comment('Note real values might be different between web and CLI.');
}
return;
}
if (!$envs) {
$options['output']->block('No environment variables are being used.');
return;
}
$rows = [];
$missing = [];
foreach ($envs as $env) {
if (isset($rows[$env['name']])) {
continue;
}
$rows[$env['name']] = [
$env['name'],
$env['default_available'] ? $dump($env['default_value']) : 'n/a',
$env['runtime_available'] ? $dump($env['runtime_value']) : 'n/a',
];
if (!$env['default_available'] && !$env['runtime_available']) {
$missing[$env['name']] = true;
}
}
$options['output']->table(['Name', 'Default value', 'Real value'], $rows);
$options['output']->comment('Note real values might be different between web and CLI.');
if ($missing) {
$options['output']->warning('The following variables are missing:');
$options['output']->listing(array_keys($missing));
}
}
protected function describeEventDispatcherListeners(EventDispatcherInterface $eventDispatcher, array $options = []): void
{
$event = $options['event'] ?? null;
$dispatcherServiceName = $options['dispatcher_service_name'] ?? null;
$title = 'Registered Listeners';
if (null !== $dispatcherServiceName) {
$title .= \sprintf(' of Event Dispatcher "%s"', $dispatcherServiceName);
}
if (null !== $event) {
$title .= \sprintf(' for "%s" Event', $event);
$registeredListeners = $eventDispatcher->getListeners($event);
} else {
$title .= ' Grouped by Event';
// Try to see if "events" exists
$registeredListeners = \array_key_exists('events', $options) ? array_combine($options['events'], array_map(fn ($event) => $eventDispatcher->getListeners($event), $options['events'])) : $eventDispatcher->getListeners();
}
$options['output']->title($title);
if (null !== $event) {
$this->renderEventListenerTable($eventDispatcher, $event, $registeredListeners, $options['output']);
} else {
ksort($registeredListeners);
foreach ($registeredListeners as $eventListened => $eventListeners) {
$options['output']->section(\sprintf('"%s" event', $eventListened));
$this->renderEventListenerTable($eventDispatcher, $eventListened, $eventListeners, $options['output']);
}
}
}
protected function describeCallable(mixed $callable, array $options = []): void
{
$this->writeText($this->formatCallable($callable), $options);
}
private function renderEventListenerTable(EventDispatcherInterface $eventDispatcher, string $event, array $eventListeners, SymfonyStyle $io): void
{
$tableHeaders = ['Order', 'Callable', 'Priority'];
$tableRows = [];
foreach ($eventListeners as $order => $listener) {
$tableRows[] = [\sprintf('#%d', $order + 1), $this->formatCallable($listener), $eventDispatcher->getListenerPriority($event, $listener)];
}
$io->table($tableHeaders, $tableRows);
}
private function formatRouterConfig(array $config): string
{
if (!$config) {
return 'NONE';
}
ksort($config);
$configAsString = '';
foreach ($config as $key => $value) {
$configAsString .= \sprintf("\n%s: %s", $key, $this->formatValue($value));
}
return trim($configAsString);
}
private function formatControllerLink(mixed $controller, string $anchorText, ?callable $getContainer = null): string
{
if (null === $this->fileLinkFormatter) {
return $anchorText;
}
try {
if (null === $controller) {
return $anchorText;
} elseif (\is_array($controller)) {
$r = new \ReflectionMethod($controller[0], $controller[1]);
} elseif ($controller instanceof \Closure) {
$r = new \ReflectionFunction($controller);
} elseif (method_exists($controller, '__invoke')) {
$r = new \ReflectionMethod($controller, '__invoke');
} elseif (!\is_string($controller)) {
return $anchorText;
} elseif (str_contains($controller, '::')) {
$r = new \ReflectionMethod(...explode('::', $controller, 2));
} else {
$r = new \ReflectionFunction($controller);
}
} catch (\ReflectionException) {
if (\is_array($controller)) {
$controller = implode('::', $controller);
}
$id = $controller;
$method = '__invoke';
if ($pos = strpos($controller, '::')) {
$id = substr($controller, 0, $pos);
$method = substr($controller, $pos + 2);
}
if (!$getContainer || !($container = $getContainer()) || !$container->has($id)) {
return $anchorText;
}
try {
$r = new \ReflectionMethod($container->findDefinition($id)->getClass(), $method);
} catch (\ReflectionException) {
return $anchorText;
}
}
$fileLink = $this->fileLinkFormatter->format($r->getFileName(), $r->getStartLine());
if ($fileLink) {
return \sprintf('<href=%s>%s</>', $fileLink, $anchorText);
}
return $anchorText;
}
private function formatCallable(mixed $callable): string
{
if (\is_array($callable)) {
if (\is_object($callable[0])) {
return \sprintf('%s::%s()', $callable[0]::class, $callable[1]);
}
return \sprintf('%s::%s()', $callable[0], $callable[1]);
}
if (\is_string($callable)) {
return \sprintf('%s()', $callable);
}
if ($callable instanceof \Closure) {
$r = new \ReflectionFunction($callable);
if ($r->isAnonymous()) {
return 'Closure()';
}
if ($class = $r->getClosureCalledClass()) {
return \sprintf('%s::%s()', $class->name, $r->name);
}
return $r->name.'()';
}
if (method_exists($callable, '__invoke')) {
return \sprintf('%s::__invoke()', $callable::class);
}
throw new \InvalidArgumentException('Callable is not describable.');
}
private function writeText(string $content, array $options = []): void
{
$this->write(
isset($options['raw_text']) && $options['raw_text'] ? strip_tags($content) : $content,
isset($options['raw_output']) ? !$options['raw_output'] : true
);
}
}

View File

@@ -0,0 +1,606 @@
<?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\Bundle\FrameworkBundle\Console\Descriptor;
use Symfony\Component\Console\Exception\LogicException;
use Symfony\Component\Console\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\Argument\AbstractArgument;
use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
use Symfony\Component\DependencyInjection\Argument\ServiceLocatorArgument;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
/**
* @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com>
*
* @internal
*/
class XmlDescriptor extends Descriptor
{
protected function describeRouteCollection(RouteCollection $routes, array $options = []): void
{
$this->writeDocument($this->getRouteCollectionDocument($routes, $options));
}
protected function describeRoute(Route $route, array $options = []): void
{
$this->writeDocument($this->getRouteDocument($route, $options['name'] ?? null));
}
protected function describeContainerParameters(ParameterBag $parameters, array $options = []): void
{
$this->writeDocument($this->getContainerParametersDocument($parameters));
}
protected function describeContainerTags(ContainerBuilder $container, array $options = []): void
{
$this->writeDocument($this->getContainerTagsDocument($container, isset($options['show_hidden']) && $options['show_hidden']));
}
protected function describeContainerService(object $service, array $options = [], ?ContainerBuilder $container = null): void
{
if (!isset($options['id'])) {
throw new \InvalidArgumentException('An "id" option must be provided.');
}
$this->writeDocument($this->getContainerServiceDocument($service, $options['id'], $container));
}
protected function describeContainerServices(ContainerBuilder $container, array $options = []): void
{
$this->writeDocument($this->getContainerServicesDocument($container, $options['tag'] ?? null, isset($options['show_hidden']) && $options['show_hidden'], $options['filter'] ?? null));
}
protected function describeContainerDefinition(Definition $definition, array $options = [], ?ContainerBuilder $container = null): void
{
$this->writeDocument($this->getContainerDefinitionDocument($definition, $options['id'] ?? null, isset($options['omit_tags']) && $options['omit_tags'], $container));
}
protected function describeContainerAlias(Alias $alias, array $options = [], ?ContainerBuilder $container = null): void
{
$dom = new \DOMDocument('1.0', 'UTF-8');
$dom->appendChild($dom->importNode($this->getContainerAliasDocument($alias, $options['id'] ?? null)->childNodes->item(0), true));
if (!$container) {
$this->writeDocument($dom);
return;
}
$dom->appendChild($dom->importNode($this->getContainerDefinitionDocument($container->getDefinition((string) $alias), (string) $alias, false, $container)->childNodes->item(0), true));
$this->writeDocument($dom);
}
protected function describeEventDispatcherListeners(EventDispatcherInterface $eventDispatcher, array $options = []): void
{
$this->writeDocument($this->getEventDispatcherListenersDocument($eventDispatcher, $options));
}
protected function describeCallable(mixed $callable, array $options = []): void
{
$this->writeDocument($this->getCallableDocument($callable));
}
protected function describeContainerParameter(mixed $parameter, ?array $deprecation, array $options = []): void
{
$this->writeDocument($this->getContainerParameterDocument($parameter, $deprecation, $options));
}
protected function describeContainerEnvVars(array $envs, array $options = []): void
{
throw new LogicException('Using the XML format to debug environment variables is not supported.');
}
protected function describeContainerDeprecations(ContainerBuilder $container, array $options = []): void
{
$containerDeprecationFilePath = \sprintf('%s/%sDeprecations.log', $container->getParameter('kernel.build_dir'), $container->getParameter('kernel.container_class'));
if (!file_exists($containerDeprecationFilePath)) {
throw new RuntimeException('The deprecation file does not exist, please try warming the cache first.');
}
$logs = unserialize(file_get_contents($containerDeprecationFilePath));
$dom = new \DOMDocument('1.0', 'UTF-8');
$dom->appendChild($deprecationsXML = $dom->createElement('deprecations'));
$remainingCount = 0;
foreach ($logs as $log) {
$deprecationsXML->appendChild($deprecationXML = $dom->createElement('deprecation'));
$deprecationXML->setAttribute('count', $log['count']);
$deprecationXML->appendChild($dom->createElement('message', $log['message']));
$deprecationXML->appendChild($dom->createElement('file', $log['file']));
$deprecationXML->appendChild($dom->createElement('line', $log['line']));
$remainingCount += $log['count'];
}
$deprecationsXML->setAttribute('remainingCount', $remainingCount);
$this->writeDocument($dom);
}
private function writeDocument(\DOMDocument $dom): void
{
$dom->formatOutput = true;
$this->write($dom->saveXML());
}
private function getRouteCollectionDocument(RouteCollection $routes, array $options): \DOMDocument
{
$dom = new \DOMDocument('1.0', 'UTF-8');
$dom->appendChild($routesXML = $dom->createElement('routes'));
foreach ($routes->all() as $name => $route) {
$routeXML = $this->getRouteDocument($route, $name);
if (($showAliases ??= $options['show_aliases'] ?? false) && $aliases = ($reverseAliases ??= $this->getReverseAliases($routes))[$name] ?? []) {
$routeXML->firstChild->appendChild($aliasesXML = $routeXML->createElement('aliases'));
foreach ($aliases as $alias) {
$aliasesXML->appendChild($aliasXML = $routeXML->createElement('alias'));
$aliasXML->appendChild(new \DOMText($alias));
}
}
$routesXML->appendChild($routesXML->ownerDocument->importNode($routeXML->childNodes->item(0), true));
}
return $dom;
}
private function getRouteDocument(Route $route, ?string $name = null): \DOMDocument
{
$dom = new \DOMDocument('1.0', 'UTF-8');
$dom->appendChild($routeXML = $dom->createElement('route'));
if ($name) {
$routeXML->setAttribute('name', $name);
}
$routeXML->setAttribute('class', $route::class);
$routeXML->appendChild($pathXML = $dom->createElement('path'));
$pathXML->setAttribute('regex', $route->compile()->getRegex());
$pathXML->appendChild(new \DOMText($route->getPath()));
if ('' !== $route->getHost()) {
$routeXML->appendChild($hostXML = $dom->createElement('host'));
$hostXML->setAttribute('regex', $route->compile()->getHostRegex());
$hostXML->appendChild(new \DOMText($route->getHost()));
}
foreach ($route->getSchemes() as $scheme) {
$routeXML->appendChild($schemeXML = $dom->createElement('scheme'));
$schemeXML->appendChild(new \DOMText($scheme));
}
foreach ($route->getMethods() as $method) {
$routeXML->appendChild($methodXML = $dom->createElement('method'));
$methodXML->appendChild(new \DOMText($method));
}
if ($route->getDefaults()) {
$routeXML->appendChild($defaultsXML = $dom->createElement('defaults'));
foreach ($route->getDefaults() as $attribute => $value) {
$defaultsXML->appendChild($defaultXML = $dom->createElement('default'));
$defaultXML->setAttribute('key', $attribute);
$defaultXML->appendChild(new \DOMText($this->formatValue($value)));
}
}
$originRequirements = $requirements = $route->getRequirements();
unset($requirements['_scheme'], $requirements['_method']);
if ($requirements) {
$routeXML->appendChild($requirementsXML = $dom->createElement('requirements'));
foreach ($originRequirements as $attribute => $pattern) {
$requirementsXML->appendChild($requirementXML = $dom->createElement('requirement'));
$requirementXML->setAttribute('key', $attribute);
$requirementXML->appendChild(new \DOMText($pattern));
}
}
if ($route->getOptions()) {
$routeXML->appendChild($optionsXML = $dom->createElement('options'));
foreach ($route->getOptions() as $name => $value) {
$optionsXML->appendChild($optionXML = $dom->createElement('option'));
$optionXML->setAttribute('key', $name);
$optionXML->appendChild(new \DOMText($this->formatValue($value)));
}
}
if ('' !== $route->getCondition()) {
$routeXML->appendChild($conditionXML = $dom->createElement('condition'));
$conditionXML->appendChild(new \DOMText($route->getCondition()));
}
return $dom;
}
private function getContainerParametersDocument(ParameterBag $parameters): \DOMDocument
{
$dom = new \DOMDocument('1.0', 'UTF-8');
$dom->appendChild($parametersXML = $dom->createElement('parameters'));
$deprecatedParameters = $parameters->allDeprecated();
foreach ($this->sortParameters($parameters) as $key => $value) {
$parametersXML->appendChild($parameterXML = $dom->createElement('parameter'));
$parameterXML->setAttribute('key', $key);
$parameterXML->appendChild(new \DOMText($this->formatParameter($value)));
if (isset($deprecatedParameters[$key])) {
$parameterXML->setAttribute('deprecated', \sprintf('Since %s %s: %s', $deprecatedParameters[$key][0], $deprecatedParameters[$key][1], \sprintf(...\array_slice($deprecatedParameters[$key], 2))));
}
}
return $dom;
}
private function getContainerTagsDocument(ContainerBuilder $container, bool $showHidden = false): \DOMDocument
{
$dom = new \DOMDocument('1.0', 'UTF-8');
$dom->appendChild($containerXML = $dom->createElement('container'));
foreach ($this->findDefinitionsByTag($container, $showHidden) as $tag => $definitions) {
$containerXML->appendChild($tagXML = $dom->createElement('tag'));
$tagXML->setAttribute('name', $tag);
foreach ($definitions as $serviceId => $definition) {
$definitionXML = $this->getContainerDefinitionDocument($definition, $serviceId, true, $container);
$tagXML->appendChild($dom->importNode($definitionXML->childNodes->item(0), true));
}
}
return $dom;
}
private function getContainerServiceDocument(object $service, string $id, ?ContainerBuilder $container = null): \DOMDocument
{
$dom = new \DOMDocument('1.0', 'UTF-8');
if ($service instanceof Alias) {
$dom->appendChild($dom->importNode($this->getContainerAliasDocument($service, $id)->childNodes->item(0), true));
if ($container) {
$dom->appendChild($dom->importNode($this->getContainerDefinitionDocument($container->getDefinition((string) $service), (string) $service, false, $container)->childNodes->item(0), true));
}
} elseif ($service instanceof Definition) {
$dom->appendChild($dom->importNode($this->getContainerDefinitionDocument($service, $id, false, $container)->childNodes->item(0), true));
} else {
$dom->appendChild($serviceXML = $dom->createElement('service'));
$serviceXML->setAttribute('id', $id);
$serviceXML->setAttribute('class', $service::class);
}
return $dom;
}
private function getContainerServicesDocument(ContainerBuilder $container, ?string $tag = null, bool $showHidden = false, ?callable $filter = null): \DOMDocument
{
$dom = new \DOMDocument('1.0', 'UTF-8');
$dom->appendChild($containerXML = $dom->createElement('container'));
$serviceIds = $tag
? $this->sortTaggedServicesByPriority($container->findTaggedServiceIds($tag))
: $this->sortServiceIds($container->getServiceIds());
if ($filter) {
$serviceIds = array_filter($serviceIds, $filter);
}
foreach ($serviceIds as $serviceId) {
$service = $this->resolveServiceDefinition($container, $serviceId);
if ($showHidden xor '.' === ($serviceId[0] ?? null)) {
continue;
}
if ($service instanceof Definition && $service->hasTag('container.excluded')) {
continue;
}
$serviceXML = $this->getContainerServiceDocument($service, $serviceId, null);
$containerXML->appendChild($containerXML->ownerDocument->importNode($serviceXML->childNodes->item(0), true));
}
return $dom;
}
private function getContainerDefinitionDocument(Definition $definition, ?string $id = null, bool $omitTags = false, ?ContainerBuilder $container = null): \DOMDocument
{
$dom = new \DOMDocument('1.0', 'UTF-8');
$dom->appendChild($serviceXML = $dom->createElement('definition'));
if ($id) {
$serviceXML->setAttribute('id', $id);
}
if ('' !== $classDescription = $this->getClassDescription((string) $definition->getClass())) {
$serviceXML->appendChild($descriptionXML = $dom->createElement('description'));
$descriptionXML->appendChild($dom->createCDATASection($classDescription));
}
$serviceXML->setAttribute('class', $definition->getClass() ?? '');
if ($factory = $definition->getFactory()) {
$serviceXML->appendChild($factoryXML = $dom->createElement('factory'));
if (\is_array($factory)) {
if ($factory[0] instanceof Reference) {
$factoryXML->setAttribute('service', (string) $factory[0]);
} elseif ($factory[0] instanceof Definition) {
$factoryXML->setAttribute('service', \sprintf('inline factory service (%s)', $factory[0]->getClass() ?? 'not configured'));
} else {
$factoryXML->setAttribute('class', $factory[0]);
}
$factoryXML->setAttribute('method', $factory[1]);
} else {
$factoryXML->setAttribute('function', $factory);
}
}
$serviceXML->setAttribute('public', $definition->isPublic() && !$definition->isPrivate() ? 'true' : 'false');
$serviceXML->setAttribute('synthetic', $definition->isSynthetic() ? 'true' : 'false');
$serviceXML->setAttribute('lazy', $definition->isLazy() ? 'true' : 'false');
$serviceXML->setAttribute('shared', $definition->isShared() ? 'true' : 'false');
$serviceXML->setAttribute('abstract', $definition->isAbstract() ? 'true' : 'false');
$serviceXML->setAttribute('autowired', $definition->isAutowired() ? 'true' : 'false');
$serviceXML->setAttribute('autoconfigured', $definition->isAutoconfigured() ? 'true' : 'false');
if ($definition->isDeprecated()) {
$serviceXML->setAttribute('deprecated', 'true');
$serviceXML->setAttribute('deprecation_message', $definition->getDeprecation($id)['message']);
} else {
$serviceXML->setAttribute('deprecated', 'false');
}
$serviceXML->setAttribute('file', $definition->getFile() ?? '');
$calls = $definition->getMethodCalls();
if (\count($calls) > 0) {
$serviceXML->appendChild($callsXML = $dom->createElement('calls'));
foreach ($calls as $callData) {
$callsXML->appendChild($callXML = $dom->createElement('call'));
$callXML->setAttribute('method', $callData[0]);
if ($callData[2] ?? false) {
$callXML->setAttribute('returns-clone', 'true');
}
}
}
foreach ($this->getArgumentNodes($definition->getArguments(), $dom, $container) as $node) {
$serviceXML->appendChild($node);
}
if (!$omitTags) {
if ($tags = $this->sortTagsByPriority($definition->getTags())) {
$serviceXML->appendChild($tagsXML = $dom->createElement('tags'));
foreach ($tags as $tagName => $tagData) {
foreach ($tagData as $parameters) {
$tagsXML->appendChild($tagXML = $dom->createElement('tag'));
$tagXML->setAttribute('name', $tagName);
foreach ($parameters as $name => $value) {
$tagXML->appendChild($parameterXML = $dom->createElement('parameter'));
$parameterXML->setAttribute('name', $name);
$parameterXML->appendChild(new \DOMText($this->formatParameter($value)));
}
}
}
}
}
if (null !== $container && null !== $id) {
$edges = $this->getServiceEdges($container, $id);
if ($edges) {
$serviceXML->appendChild($usagesXML = $dom->createElement('usages'));
foreach ($edges as $edge) {
$usagesXML->appendChild($usageXML = $dom->createElement('usage'));
$usageXML->appendChild(new \DOMText($edge));
}
}
}
return $dom;
}
/**
* @return \DOMNode[]
*/
private function getArgumentNodes(array $arguments, \DOMDocument $dom, ?ContainerBuilder $container = null): array
{
$nodes = [];
foreach ($arguments as $argumentKey => $argument) {
$argumentXML = $dom->createElement('argument');
if (\is_string($argumentKey)) {
$argumentXML->setAttribute('key', $argumentKey);
}
if ($argument instanceof ServiceClosureArgument) {
$argument = $argument->getValues()[0];
}
if ($argument instanceof Reference) {
$argumentXML->setAttribute('type', 'service');
$argumentXML->setAttribute('id', (string) $argument);
} elseif ($argument instanceof IteratorArgument || $argument instanceof ServiceLocatorArgument) {
$argumentXML->setAttribute('type', $argument instanceof IteratorArgument ? 'iterator' : 'service_locator');
foreach ($this->getArgumentNodes($argument->getValues(), $dom, $container) as $childArgumentXML) {
$argumentXML->appendChild($childArgumentXML);
}
} elseif ($argument instanceof Definition) {
$argumentXML->appendChild($dom->importNode($this->getContainerDefinitionDocument($argument, null, false, $container)->childNodes->item(0), true));
} elseif ($argument instanceof AbstractArgument) {
$argumentXML->setAttribute('type', 'abstract');
$argumentXML->appendChild(new \DOMText($argument->getText()));
} elseif (\is_array($argument)) {
$argumentXML->setAttribute('type', 'collection');
foreach ($this->getArgumentNodes($argument, $dom, $container) as $childArgumentXML) {
$argumentXML->appendChild($childArgumentXML);
}
} elseif ($argument instanceof \UnitEnum) {
$argumentXML->setAttribute('type', 'constant');
$argumentXML->appendChild(new \DOMText(ltrim(var_export($argument, true), '\\')));
} else {
$argumentXML->appendChild(new \DOMText($argument));
}
$nodes[] = $argumentXML;
}
return $nodes;
}
private function getContainerAliasDocument(Alias $alias, ?string $id = null): \DOMDocument
{
$dom = new \DOMDocument('1.0', 'UTF-8');
$dom->appendChild($aliasXML = $dom->createElement('alias'));
if ($id) {
$aliasXML->setAttribute('id', $id);
}
$aliasXML->setAttribute('service', (string) $alias);
$aliasXML->setAttribute('public', $alias->isPublic() && !$alias->isPrivate() ? 'true' : 'false');
return $dom;
}
private function getContainerParameterDocument(mixed $parameter, ?array $deprecation, array $options = []): \DOMDocument
{
$dom = new \DOMDocument('1.0', 'UTF-8');
$dom->appendChild($parameterXML = $dom->createElement('parameter'));
if (isset($options['parameter'])) {
$parameterXML->setAttribute('key', $options['parameter']);
if ($deprecation) {
$parameterXML->setAttribute('deprecated', \sprintf('Since %s %s: %s', $deprecation[0], $deprecation[1], \sprintf(...\array_slice($deprecation, 2))));
}
}
$parameterXML->appendChild(new \DOMText($this->formatParameter($parameter)));
return $dom;
}
private function getEventDispatcherListenersDocument(EventDispatcherInterface $eventDispatcher, array $options): \DOMDocument
{
$event = $options['event'] ?? null;
$dom = new \DOMDocument('1.0', 'UTF-8');
$dom->appendChild($eventDispatcherXML = $dom->createElement('event-dispatcher'));
if (null !== $event) {
$registeredListeners = $eventDispatcher->getListeners($event);
$this->appendEventListenerDocument($eventDispatcher, $event, $eventDispatcherXML, $registeredListeners);
} else {
// Try to see if "events" exists
$registeredListeners = \array_key_exists('events', $options) ? array_combine($options['events'], array_map(fn ($event) => $eventDispatcher->getListeners($event), $options['events'])) : $eventDispatcher->getListeners();
ksort($registeredListeners);
foreach ($registeredListeners as $eventListened => $eventListeners) {
$eventDispatcherXML->appendChild($eventXML = $dom->createElement('event'));
$eventXML->setAttribute('name', $eventListened);
$this->appendEventListenerDocument($eventDispatcher, $eventListened, $eventXML, $eventListeners);
}
}
return $dom;
}
private function appendEventListenerDocument(EventDispatcherInterface $eventDispatcher, string $event, \DOMElement $element, array $eventListeners): void
{
foreach ($eventListeners as $listener) {
$callableXML = $this->getCallableDocument($listener);
$callableXML->childNodes->item(0)->setAttribute('priority', $eventDispatcher->getListenerPriority($event, $listener));
$element->appendChild($element->ownerDocument->importNode($callableXML->childNodes->item(0), true));
}
}
private function getCallableDocument(mixed $callable): \DOMDocument
{
$dom = new \DOMDocument('1.0', 'UTF-8');
$dom->appendChild($callableXML = $dom->createElement('callable'));
if (\is_array($callable)) {
$callableXML->setAttribute('type', 'function');
if (\is_object($callable[0])) {
$callableXML->setAttribute('name', $callable[1]);
$callableXML->setAttribute('class', $callable[0]::class);
} else {
if (!str_starts_with($callable[1], 'parent::')) {
$callableXML->setAttribute('name', $callable[1]);
$callableXML->setAttribute('class', $callable[0]);
$callableXML->setAttribute('static', 'true');
} else {
$callableXML->setAttribute('name', substr($callable[1], 8));
$callableXML->setAttribute('class', $callable[0]);
$callableXML->setAttribute('static', 'true');
$callableXML->setAttribute('parent', 'true');
}
}
return $dom;
}
if (\is_string($callable)) {
$callableXML->setAttribute('type', 'function');
if (!str_contains($callable, '::')) {
$callableXML->setAttribute('name', $callable);
} else {
$callableParts = explode('::', $callable);
$callableXML->setAttribute('name', $callableParts[1]);
$callableXML->setAttribute('class', $callableParts[0]);
$callableXML->setAttribute('static', 'true');
}
return $dom;
}
if ($callable instanceof \Closure) {
$callableXML->setAttribute('type', 'closure');
$r = new \ReflectionFunction($callable);
if ($r->isAnonymous()) {
return $dom;
}
$callableXML->setAttribute('name', $r->name);
if ($class = $r->getClosureCalledClass()) {
$callableXML->setAttribute('class', $class->name);
if (!$r->getClosureThis()) {
$callableXML->setAttribute('static', 'true');
}
}
return $dom;
}
if (method_exists($callable, '__invoke')) {
$callableXML->setAttribute('type', 'object');
$callableXML->setAttribute('name', $callable::class);
return $dom;
}
throw new \InvalidArgumentException('Callable is not describable.');
}
}

View File

@@ -0,0 +1,37 @@
<?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\Bundle\FrameworkBundle\Console\Helper;
use Symfony\Bundle\FrameworkBundle\Console\Descriptor\JsonDescriptor;
use Symfony\Bundle\FrameworkBundle\Console\Descriptor\MarkdownDescriptor;
use Symfony\Bundle\FrameworkBundle\Console\Descriptor\TextDescriptor;
use Symfony\Bundle\FrameworkBundle\Console\Descriptor\XmlDescriptor;
use Symfony\Component\Console\Helper\DescriptorHelper as BaseDescriptorHelper;
use Symfony\Component\ErrorHandler\ErrorRenderer\FileLinkFormatter;
/**
* @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com>
*
* @internal
*/
class DescriptorHelper extends BaseDescriptorHelper
{
public function __construct(?FileLinkFormatter $fileLinkFormatter = null)
{
$this
->register('txt', new TextDescriptor($fileLinkFormatter))
->register('xml', new XmlDescriptor())
->register('json', new JsonDescriptor())
->register('md', new MarkdownDescriptor())
;
}
}