diff --git a/src/TwigComponent/src/ComponentFactory.php b/src/TwigComponent/src/ComponentFactory.php index 37a757ccb7b..d673de45f7d 100644 --- a/src/TwigComponent/src/ComponentFactory.php +++ b/src/TwigComponent/src/ComponentFactory.php @@ -46,6 +46,8 @@ public function __construct( public function metadataFor(string $name): ComponentMetadata { + $name = $this->classMap[$name] ?? $name; + if ($config = $this->config[$name] ?? null) { return new ComponentMetadata($config); } @@ -59,14 +61,6 @@ public function metadataFor(string $name): ComponentMetadata return new ComponentMetadata($this->config[$name]); } - if ($mappedName = $this->classMap[$name] ?? null) { - if ($config = $this->config[$mappedName] ?? null) { - return new ComponentMetadata($config); - } - - throw new \InvalidArgumentException(\sprintf('Unknown component "%s".', $name)); - } - $this->throwUnknownComponentException($name); } diff --git a/src/TwigComponent/tests/Unit/ComponentFactoryTest.php b/src/TwigComponent/tests/Unit/ComponentFactoryTest.php index 0d2dafc01c0..d803ad9ef6f 100644 --- a/src/TwigComponent/tests/Unit/ComponentFactoryTest.php +++ b/src/TwigComponent/tests/Unit/ComponentFactoryTest.php @@ -93,4 +93,32 @@ public function testMetadataForReuseAnonymousConfig() $this->assertSame('foo', $metadata->getName()); $this->assertSame('foo.html.twig', $metadata->getTemplate()); } + + /** + * @testWith ["bar"] + * ["Foo\\Bar"] + */ + public function testPrefersClassComponentOverAnonymous(string $name) + { + $templateFinder = $this->createMock(ComponentTemplateFinderInterface::class); + $templateFinder->expects($this->never()) + ->method('findAnonymousComponentTemplate'); + + $factory = new ComponentFactory( + $templateFinder, + $this->createMock(ServiceLocator::class), + $this->createMock(PropertyAccessorInterface::class), + $this->createMock(EventDispatcherInterface::class), + [ + 'bar' => ['key' => 'bar', 'template' => 'bar.html.twig'], + ], + ['Foo\\Bar' => 'bar'], + $this->createMock(Environment::class), + ); + + $metadata = $factory->metadataFor($name); + + $this->assertSame('bar', $metadata->getName()); + $this->assertSame('bar.html.twig', $metadata->getTemplate()); + } }