Skip to content

[TwigComponent] AnonymousComponentRegistry to share anonymous component in your bundles #1456

New issue

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

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

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from 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
17 changes: 17 additions & 0 deletions src/TwigComponent/src/AnonymousComponentRegistryInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?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\TwigComponent;

interface AnonymousComponentRegistryInterface
{
public function get(string $name): ?string;
}
32 changes: 32 additions & 0 deletions src/TwigComponent/src/ComponentTemplateFinder.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ final class ComponentTemplateFinder implements ComponentTemplateFinderInterface
public function __construct(
Environment|LoaderInterface $loader,
private readonly ?string $directory = null,
private readonly iterable $anonymousComponentRegistries = [],
) {
if ($loader instanceof Environment) {
trigger_deprecation('symfony/ux-twig-component', '2.13', 'The "%s()" method will require "%s $loader" as first argument in 3.0. Passing an "Environment" instance is deprecated.', __METHOD__, LoaderInterface::class);
Expand All @@ -36,6 +37,26 @@ public function __construct(
}

public function findAnonymousComponentTemplate(string $name): ?string
{
$template = $this->findAnonymousComponentInTemplateDirectory($name);
$registryTemplate = $this->findAnonymousComponentFromRegistry($name);

if (null !== $template && null !== $registryTemplate) {
throw new \LogicException(sprintf('The component "%s" is defined in both the template directory and in a component registry.', $name));
}

if (null !== $template) {
return $template;
}

if (null !== $registryTemplate) {
return $registryTemplate;
}

return null;
}

private function findAnonymousComponentInTemplateDirectory(string $name): ?string
{
$loader = $this->loader;
$componentPath = rtrim(str_replace(':', '/', $name));
Expand Down Expand Up @@ -68,4 +89,15 @@ public function findAnonymousComponentTemplate(string $name): ?string

return null;
}

private function findAnonymousComponentFromRegistry(string $name): ?string
{
foreach ($this->anonymousComponentRegistries as $registry) {
if (null !== $template = $registry->get($name)) {
return $template;
}
}

return null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,15 @@
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Argument\AbstractArgument;
use Symfony\Component\DependencyInjection\Argument\TaggedIteratorArgument;
use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
use Symfony\Component\DependencyInjection\Parameter;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\UX\TwigComponent\AnonymousComponentRegistryInterface;
use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;
use Symfony\UX\TwigComponent\Command\TwigComponentDebugCommand;
use Symfony\UX\TwigComponent\ComponentFactory;
Expand Down Expand Up @@ -64,10 +66,14 @@ public function load(array $configs, ContainerBuilder $container): void
}
$container->setParameter('ux.twig_component.component_defaults', $defaults);

$container->registerForAutoconfiguration(AnonymousComponentRegistryInterface::class)
->addTag('ux.twig_component.anonymous_component_registry');

$container->register('ux.twig_component.component_template_finder', ComponentTemplateFinder::class)
->setArguments([
new Reference('twig.loader'),
$config['anonymous_template_directory'],
new TaggedIteratorArgument('ux.twig_component.anonymous_component_registry'),
]);
$container->setAlias(ComponentRendererInterface::class, 'ux.twig_component.component_renderer');

Expand Down
2 changes: 2 additions & 0 deletions src/TwigComponent/tests/Fixtures/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
use Symfony\UX\TwigComponent\Tests\Fixtures\Component\ComponentB;
use Symfony\UX\TwigComponent\Tests\Fixtures\Service\AnonymousComponentRegistry;
use Symfony\UX\TwigComponent\TwigComponentBundle;

/**
Expand Down Expand Up @@ -87,6 +88,7 @@ protected function configureContainer(ContainerConfigurator $c): void
'key' => 'component_d',
'template' => 'components/custom2.html.twig',
])
->set('anonymous_component_registry', AnonymousComponentRegistry::class)->tag('ux.twig_component.anonymous_component_registry')
;

if ('missing_key' === $this->environment) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?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\TwigComponent\Tests\Fixtures\Service;

use Symfony\UX\TwigComponent\AnonymousComponentRegistryInterface;

class AnonymousComponentRegistry implements AnonymousComponentRegistryInterface
{
public function register(): array
{
return [
'ux:Icon' => 'components/Icon.html.twig',
];
}

public function get(string $name): ?string
{
return $this->register()[$name] ?? null;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<twig:ux:Icon/>
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<div>
I am an Icon
</div>
10 changes: 10 additions & 0 deletions src/TwigComponent/tests/Integration/ComponentExtensionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\UX\TwigComponent\Tests\Integration;

use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\UX\TwigComponent\Tests\Fixtures\Service\AnonymousComponentRegistry;
use Symfony\UX\TwigComponent\Tests\Fixtures\User;
use Twig\Environment;
use Twig\Error\RuntimeError;
Expand Down Expand Up @@ -216,6 +217,15 @@ public function testComponentPropsWithTrailingComma(): void
$this->assertStringContainsString('Hello FOO, 123, and 456', $output);
}

public function testRenderAnonymousComponentFromRegistry(): void
{
self::getContainer()->set('component_registry', new AnonymousComponentRegistry());

$output = self::getContainer()->get(Environment::class)->render('anonymous_component_from_registry.html.twig');

$this->assertStringContainsString('I am an Icon', $output);
}

private function renderComponent(string $name, array $data = []): string
{
return self::getContainer()->get(Environment::class)->render('render_component.html.twig', [
Expand Down
34 changes: 34 additions & 0 deletions src/TwigComponent/tests/Unit/ComponentTemplateFinderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use PHPUnit\Framework\TestCase;
use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait;
use Symfony\UX\TwigComponent\AnonymousComponentRegistryInterface;
use Symfony\UX\TwigComponent\ComponentTemplateFinder;
use Twig\Environment;
use Twig\Loader\ArrayLoader;
Expand Down Expand Up @@ -126,6 +127,39 @@ public function testFindTemplateWithinDirectory(): void
$this->assertEquals('foo/foo/bar.html.twig', $finder->findAnonymousComponentTemplate('foo:bar'));
}

public function testFindTemplateFromRegistry(): void
{
$registry = $this->createMock(AnonymousComponentRegistryInterface::class);
$registry->expects($this->once())
->method('get')
->with('bar')
->willReturn('bar.html.twig')
;
$loader = $this->createLoader([]);
$finder = new ComponentTemplateFinder($loader, '', [$registry]);

$this->assertEquals('bar.html.twig', $finder->findAnonymousComponentTemplate('bar'));
}

public function testThrowErrorWhenConflictBetweenRegistryAndLocalTemplate()
{
$templates = [
'components/bar.html.twig',
];

$registry = $this->createMock(AnonymousComponentRegistryInterface::class);
$registry->expects($this->once())
->method('get')
->with('bar')
->willReturn('bar.html.twig')
;
$loader = $this->createLoader($templates);
$finder = new ComponentTemplateFinder($loader, 'components', [$registry]);

$this->expectException(\LogicException::class);
$finder->findAnonymousComponentTemplate('bar');
}

private function createLoader(array $templates): LoaderInterface
{
return new ArrayLoader(array_combine($templates, $templates));
Expand Down