Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

[LiveComponent] Add debug:live-component command #1163

Closed
Closed
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
30 changes: 25 additions & 5 deletions src/LiveComponent/src/Attribute/AsLiveComponent.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,10 @@ public function serviceConfig(): array

/**
* @internal
*
* @param object|class-string $component
*/
public static function isActionAllowed(object $component, string $action): bool
public static function isActionAllowed(object|string $component, string $action): bool
{
foreach (self::attributeMethodsFor(LiveAction::class, $component) as $method) {
if ($action === $method->getName()) {
Expand All @@ -60,37 +62,55 @@ public static function isActionAllowed(object $component, string $action): bool
return false;
}

/**
* @param object|class-string $component
*
* @return \ReflectionMethod[]
*
* @internal
*/
public static function liveActionMethods(object|string $component): iterable
{
return iterator_to_array(self::attributeMethodsFor(LiveAction::class, $component));
}

/**
* @internal
*
* @param object|class-string $component
*
* @return \ReflectionMethod[]
*/
public static function preReRenderMethods(object $component): iterable
public static function preReRenderMethods(object|string $component): iterable
{
return self::attributeMethodsByPriorityFor($component, PreReRender::class);
}

/**
* @internal
*
* @param object|class-string $component
*
* @return \ReflectionMethod[]
*/
public static function postHydrateMethods(object $component): iterable
public static function postHydrateMethods(object|string $component): iterable
{
return self::attributeMethodsByPriorityFor($component, PostHydrate::class);
}

/**
* @internal
*
* @param object|class-string $component
*
* @return \ReflectionMethod[]
*/
public static function preDehydrateMethods(object $component): iterable
public static function preDehydrateMethods(object|string $component): iterable
{
return self::attributeMethodsByPriorityFor($component, PreDehydrate::class);
}

public static function liveListeners(object $component): array
public static function liveListeners(object|string $component): array
{
$listeners = [];
foreach (self::attributeMethodsFor(LiveListener::class, $component) as $method) {
Expand Down
226 changes: 226 additions & 0 deletions src/LiveComponent/src/Command/LiveComponentDebugCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,226 @@
<?php

namespace Symfony\UX\LiveComponent\Command;

use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Completion\CompletionInput;
use Symfony\Component\Console\Completion\CompletionSuggestions;
use Symfony\Component\Console\Helper\TableSeparator;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Metadata\LiveComponentMetadata;
use Symfony\UX\LiveComponent\Metadata\LiveComponentMetadataFactory;
use Symfony\UX\LiveComponent\Metadata\LivePropMetadata;
use Symfony\UX\TwigComponent\ComponentFactory;

/**
* @author Simon André <[email protected]>
*
* @experimental
*/
#[AsCommand(name: 'debug:live-component', description: 'Display Live components')]
class LiveComponentDebugCommand extends Command
{
private ?array $liveComponentsMap = null;

/**
* @internal
*/
public function __construct(
private readonly ComponentFactory $componentFactory,
private readonly LiveComponentMetadataFactory $metadataFactory,
) {
parent::__construct();
}

protected function configure(): void
{
$this
->setDefinition([
new InputArgument('name', InputArgument::OPTIONAL, 'A LiveComponent name (or part of the component name)'),
])
->setHelp(<<<'EOF'
The <info>%command.name%</info> display all the Live components in your application.

To list all 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% FooBar</info>
EOF
);
}

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

if (!\is_string($name)) {
$this->displayComponentsTable($io, $this->findComponents());
$io->text([
'// Provide the name of a LiveComponent as argument of this command to get its detailed information.',
'// (e.g. <comment>debug:live-component FooBar</comment>)',
]);

return Command::SUCCESS;
}

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

return Command::FAILURE;
}

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

return Command::SUCCESS;
}

public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void
{
if ($input->mustSuggestArgumentValuesFor('name')) {
$suggestions->suggestValues(array_keys($this->findComponents()));
}
}

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

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

$table = $io->createTable();
$table->setHeaderTitle('Live Component');
$table->setHeaders(['Property', 'Value']);
$table->addRows([
['Name', $componentMetadata->getName()],
['Class', '<comment>'.$componentClass.'</comment>'],
['Template', $componentMetadata->getTemplate()],
]);

if ($props = $metadata->getAllLivePropsMetadata()) {
$formatLiveProp = fn (LivePropMetadata $liveProp) => sprintf(
'%s <comment>$%s</comment>',
$liveProp->getType() ?? '',
$liveProp->getName(),
);
$table->addRows([
new TableSeparator(),
['LiveProp', implode("\n", array_map($formatLiveProp(...), $props))],
]);
}

$methods = array_filter([
'LiveAction' => AsLiveComponent::liveActionMethods($componentClass),
'PreReRender' => AsLiveComponent::preReRenderMethods($componentClass),
'PreDehydrate' => AsLiveComponent::preDehydrateMethods($componentClass),
'PostHydrate' => AsLiveComponent::postHydrateMethods($componentClass),
]);
foreach ($methods as $title => $values) {
$table->addRows([
new TableSeparator(),
[$title, implode("\n", array_map($this->formatMethod(...), $values))],
]);
}

$io->newLine();
$table->render();
}

private function formatMethod(\ReflectionMethod $method): string
{
$parameters = array_map($this->formatParameter(...), $method->getParameters());

return sprintf('<comment>%s</comment>(%s)', $method->getName(), implode(',', $parameters));
}

private function formatParameter(\ReflectionParameter $param): string
{
$formatted = sprintf('$%s', $param->getName());
if ($type = (string) $param->getType()) {
if ($type = substr(strrchr($type, '\\'), 1)) {
$formatted = sprintf('<fg=white;bg=default>%s</> %s', $type, $formatted);
}
}

return trim($formatted);
}

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

return $components;
}

private function findComponentName(SymfonyStyle $io, string $name, bool $interactive): ?string
{
$components = [];
foreach ($this->getLiveComponents() as $componentName) {
if ($name === $componentName) {
return $name;
}
if (str_contains($componentName, $name)) {
$components[$componentName] = $componentName;
}
}
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>
*
* @internal
*/
private function getLiveComponents(): array
{
if (null !== $this->liveComponentsMap) {
return $this->liveComponentsMap;
}

$reflector = new \ReflectionClass($this->componentFactory);
$config = $reflector->getProperty('config')->getValue($this->componentFactory);
$liveMap = array_filter($config, fn (array $c) => $c['live'] ?? false);

return $this->liveComponentsMap = array_keys($liveMap);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\DependencyInjection\Reference;
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;
Expand Down Expand Up @@ -233,6 +234,13 @@ function (ChildDefinition $definition, AsLiveComponent $attribute) {
$container->register('ux.live_component.twig.cache_warmer', TemplateCacheWarmer::class)
->setArguments([new Reference('twig.template_iterator'), self::TEMPLATES_MAP_FILENAME])
->addTag('kernel.cache_warmer');

$container->register('ux.live_component.command.debug', LiveComponentDebugCommand::class)
->setArguments([
new Reference('ux.twig_component.component_factory'),
new Reference('ux.live_component.metadata_factory'),
])
->addTag('console.command');
}

private function isAssetMapperAvailable(ContainerBuilder $container): bool
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\UX\LiveComponent\Tests\Integration\Command;

use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Console\Tester\CommandTester;

class LiveComponentDebugCommandTest extends KernelTestCase
{
public function testWithNoComponent(): void
{
$commandTester = $this->createCommandTester();
$commandTester->execute([]);

$commandTester->assertCommandIsSuccessful();

$display = $commandTester->getDisplay();

$this->tableDisplayCheck($display);
}

public function testWithNoMatchComponent(): void
{
$commandTester = $this->createCommandTester();
$result = $commandTester->execute(['name' => 'NoMatchComponent']);

$this->assertEquals(1, $result);
$this->assertStringContainsString('Unknown component "NoMatchComponent".', $commandTester->getDisplay());
}

public function testComponentWithClass(): void
{
$commandTester = $this->createCommandTester();
$commandTester->execute(['name' => 'Component1']);

$commandTester->assertCommandIsSuccessful();

$display = $commandTester->getDisplay();

$this->tableDisplayCheck($display);
$this->assertStringContainsString('Component1', $display);
$this->assertStringContainsString('Component\Component1', $display);
$this->assertStringContainsString('components/Component1.html.twig', $display);
}

private function createCommandTester(): CommandTester
{
$kernel = self::bootKernel();
$application = new Application($kernel);

return new CommandTester($application->find('debug:live-component'));
}

private function tableDisplayCheck(string $display): void
{
$this->assertStringContainsString('Component', $display);
$this->assertStringContainsString('Class', $display);
$this->assertStringContainsString('Template', $display);
}
}
Loading