Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
252 changes: 252 additions & 0 deletions src/LiveComponent/src/Command/LiveComponentDebugCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,252 @@
<?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\UX\LiveComponent\Command;

use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\TypeInfo\Type;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveArg;
use Symfony\UX\LiveComponent\Attribute\LiveProp;
use Symfony\UX\LiveComponent\Metadata\LiveComponentMetadata;
use Symfony\UX\LiveComponent\Metadata\LiveComponentMetadataFactory;

#[AsCommand(name: 'debug:live-component', description: 'Display live components and their usage for an application')]
class LiveComponentDebugCommand extends Command
{
public function __construct(
protected readonly LiveComponentMetadataFactory $metadataFactory,
protected readonly array $componentClassMap,
) {
parent::__construct();
}

protected function configure(): void
{
$this
->setDefinition([
new InputArgument(
'name',
InputArgument::OPTIONAL,
'A LiveComponent name or part of the name'
),
new InputOption(
name: 'listening',
mode: InputOption::VALUE_REQUIRED,
description: 'Filter list to display only those listening to the given event'
),
])
->setHelp(
<<<'EOF'
The <info>%command.name%</info> display all the live components in your application.

To list all live components:

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

To get specific information about a component, specify its name (or a part of it):

<info>php %command.full_name% ProductSearch</info>
EOF
);
}

protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$name = $input->getArgument('name');

if (\is_string($name)) {
$componentName = $this->findComponentName($io, $name, $input->isInteractive());
if (null === $componentName) {
$io->error(\sprintf('Unknown component "%s".', $name));

return Command::FAILURE;
}

$this->displayComponentDetails($io, $componentName);

return Command::SUCCESS;
}

$components = $this->findComponents($input->getOption('listening'));

$this->displayComponentsTable($components, $io);

return Command::SUCCESS;
}

private function findComponentName(SymfonyStyle $io, string $name, bool $interactive): ?string
{
$components = [];
foreach ($this->componentClassMap as $component) {
if ($name === $component['key']) {
return $name;
}
if (str_contains($component['key'], $name)) {
$components[$component['key']] = $component['key'];
}
}

if ($interactive && \count($components)) {
return $io->choice('Select one of the following component to display its information', array_values($components), 0);
}

return null;
}

/**
* @return array<string, LiveComponentMetadata>
*/
private function findComponents(?string $eventFilter = null): array
{
$components = [];
if (null === $eventFilter) {
foreach ($this->componentClassMap as $name => $data) {
$components[$name] ??= $this->metadataFactory->getMetadata($name);
}

return $components;
}
Comment on lines +118 to +124
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if (null === $eventFilter) {
return $this->componentClassMap;
}
$components = [];
if (null === $eventFilter) {
foreach ($this->componentClassMap as $class => $name) {
$components[$name] ??= $this->liveComponentMetadataFactory->getMetadata($name);
}
return $components;
}


foreach ($this->componentClassMap as $name => $component) {
foreach (AsLiveComponent::liveListeners($component['class']) as $listener) {
if ($listener['event'] === $eventFilter) {
$components[$name] ??= $this->metadataFactory->getMetadata($name);
break;
}
}
}

return $components;
}

private function displayComponentDetails(SymfonyStyle $io, string $name): void
{
$metadata = $this->metadataFactory->getMetadata($name);

$table = $io->createTable();
$table->setHeaderTitle('Component');
$table->setHeaders(['Property', 'Value']);
$table->addRows([
['Name', $metadata->getComponentMetadata()->getName()],
['Class', $metadata->getComponentMetadata()->getClass()],
]);

$table->addRows([
['LiveProps', implode("\n", $this->getComponentLiveProps($metadata))],
['LiveListeners', implode("\n", $this->getComponentLiveListeners($metadata->getComponentMetadata()->getClass()))],
]);

$table->render();
}

/**
* @param array<string, LiveComponentMetadata> $components
*/
private function displayComponentsTable(array $components, SymfonyStyle $io): void
{
$table = $io->createTable();
$table->setStyle('default');
$table->setHeaderTitle('Components');
$table->setHeaders(['Name', 'Class']);
foreach ($components as $component) {
$table->addRow([
$component->getComponentMetadata()->getName(),
$component->getComponentMetadata()->getClass() ?? '',
]);
}
$table->render();
}

/**
* @return array<string, string>
*/
private function getComponentLiveProps(LiveComponentMetadata $component): array
{
$liveProps = [];
foreach ($component->getAllLivePropsMetadata(null) as $liveProp) {
$reflection = new \ReflectionProperty($component->getComponentMetadata()->getClass(), $liveProp->getName());
$type = $this->displayType($liveProp->getType());
$propertyName = '$'.$liveProp->getName();
$defaultValueDisplay = $reflection->hasDefaultValue() ?
$this->displayDefaultValue($reflection->getDefaultValue()) :
'';
$arguments = $reflection->getAttributes(LiveProp::class)[0]->getArguments();
$argumentsDisplay = empty($arguments) ?
'' :
' ('.implode(', ', array_map(
static fn ($key, $value) => $key.': '.json_encode($value),
array_keys($arguments),
$arguments
)).')';

$propertyDisplay = $type.$propertyName.$defaultValueDisplay.$argumentsDisplay;
$liveProps[$liveProp->getName()] = $propertyDisplay;
}

return $liveProps;
}

/**
* @return array<string, string>
*/
private function getComponentLiveListeners(string $class): array
{
$events = [];
foreach (AsLiveComponent::liveListeners($class) as $liveListener) {
$name = $liveListener['event'];
$methodName = $liveListener['action'];
$method = new \ReflectionMethod($class, $methodName);
$parameters = array_map(
fn (\ReflectionParameter $parameter) => $this->displayType($parameter->getType()).'$'.$parameter->getName().$this->displayDefaultValue($parameter->isDefaultValueAvailable() ? $parameter->getDefaultValue() : null),
array_filter(
$method->getParameters(),
static fn (\ReflectionParameter $parameter) => !empty($parameter->getAttributes(LiveArg::class))
)
);
$parametersDisplay = empty($parameters) ?
'' :
' ('.implode(', ', $parameters).')';

$display = $name.' => '.$methodName.$parametersDisplay;
$events[] = $display;
}

return $events;
}

private function displayType(Type|string|null $type): string
{
$display = (string) $type;
if ($type instanceof Type && $type->isNullable() && !str_contains($display, 'null')) {
$display = '?'.$display;
}
if ('' !== $display) {
$display .= ' ';
}

return $display;
}

private function displayDefaultValue(mixed $defaultValue): string
{
return (null !== $defaultValue) ?
' = '.json_encode($defaultValue) :
'';
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?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\UX\LiveComponent\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

/**
* @internal
*/
final class LiveComponentPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container): void
{
$componentClassMap = [];
foreach ($container->findTaggedServiceIds('twig.component') as $id => $tags) {
if (!($tags[0]['live'] ?? false)) {
continue;
}

$definition = $container->findDefinition($id);

foreach ($tags as $tag) {
if (!\array_key_exists('key', $tag)) {
continue;
}

$tag['class'] = $definition->getClass();
$componentClassMap[$tag['key']] = $tag;
}
}

$debugCommandDefinition = $container->findDefinition('ux.live_component.command.debug');
$debugCommandDefinition->setArgument(1, $componentClassMap);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\DependencyInjection\Argument\AbstractArgument;
use Symfony\Component\DependencyInjection\Argument\TaggedIteratorArgument;
use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\ContainerBuilder;
Expand All @@ -26,9 +27,11 @@
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\Routing\RouterInterface;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Command\LiveComponentDebugCommand;
use Symfony\UX\LiveComponent\ComponentValidator;
use Symfony\UX\LiveComponent\ComponentValidatorInterface;
use Symfony\UX\LiveComponent\Controller\BatchActionController;
use Symfony\UX\LiveComponent\DependencyInjection\Compiler\LiveComponentPass;
use Symfony\UX\LiveComponent\EventListener\AddLiveAttributesSubscriber;
use Symfony\UX\LiveComponent\EventListener\DataModelPropsSubscriber;
use Symfony\UX\LiveComponent\EventListener\DeferLiveComponentSubscriber;
Expand Down Expand Up @@ -275,6 +278,13 @@ static function (ChildDefinition $definition, AsLiveComponent $attribute) {
new Parameter('container.build_hash'),
])
->addTag('kernel.cache_warmer');

$container->register('ux.live_component.command.debug', LiveComponentDebugCommand::class)
->setArguments([
new Reference('ux.live_component.metadata_factory'),
new AbstractArgument(\sprintf('Added in %s.', LiveComponentPass::class)),
])
->addTag('console.command');
}

public function getConfigTreeBuilder(): TreeBuilder
Expand Down
2 changes: 2 additions & 0 deletions src/LiveComponent/src/LiveComponentBundle.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\UX\LiveComponent\DependencyInjection\Compiler\ComponentDefaultActionPass;
use Symfony\UX\LiveComponent\DependencyInjection\Compiler\LiveComponentPass;
use Symfony\UX\LiveComponent\DependencyInjection\Compiler\OptionalDependencyPass;

/**
Expand All @@ -29,6 +30,7 @@ public function build(ContainerBuilder $container): void
// must run before Symfony\Component\Serializer\DependencyInjection\SerializerPass
$container->addCompilerPass(new OptionalDependencyPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION, 100);
$container->addCompilerPass(new ComponentDefaultActionPass());
$container->addCompilerPass(new LiveComponentPass());
}

public function getPath(): string
Expand Down
5 changes: 4 additions & 1 deletion src/LiveComponent/src/Metadata/LegacyLivePropMetadata.php
Original file line number Diff line number Diff line change
Expand Up @@ -125,8 +125,11 @@ public function hasModifier(): bool
* If a modifier is specified, a modified clone is returned.
* Otherwise, the metadata is returned as it is.
*/
public function withModifier(object $component): self
public function withModifier(?object $component): self
{
if (null === $component) {
return $this;
}
if (null === ($modifier = $this->liveProp->modifier())) {
return $this;
}
Expand Down
2 changes: 1 addition & 1 deletion src/LiveComponent/src/Metadata/LiveComponentMetadata.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public function getComponentMetadata(): ComponentMetadata
/**
* @return list<LivePropMetadata|LegacyLivePropMetadata>
*/
public function getAllLivePropsMetadata(object $component): iterable
public function getAllLivePropsMetadata(?object $component): iterable
{
foreach ($this->livePropsMetadata as $livePropMetadata) {
yield $livePropMetadata->withModifier($component);
Expand Down
5 changes: 4 additions & 1 deletion src/LiveComponent/src/Metadata/LivePropMetadata.php
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,11 @@ public function hasModifier(): bool
* If a modifier is specified, a modified clone is returned.
* Otherwise, the metadata is returned as it is.
*/
public function withModifier(object $component): self
public function withModifier(?object $component): self
{
if (null === $component) {
return $this;
}
if (null === ($modifier = $this->liveProp->modifier())) {
return $this;
}
Expand Down
Loading
Loading