Skip to content

[TwigBundle] Enable #[AsTwigFilter], #[AsTwigFunction] and #[AsTwigTest] attributes to configure runtime extensions #52748

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

Merged
merged 1 commit into from
Mar 26, 2025
Merged
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
6 changes: 6 additions & 0 deletions src/Symfony/Bundle/TwigBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
CHANGELOG
=========

7.3
---

* Enable `#[AsTwigFilter]`, `#[AsTwigFunction]` and `#[AsTwigTest]` attributes
to configure extensions on runtime classes

7.1
---

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?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\TwigBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Twig\Attribute\AsTwigFilter;
use Twig\Attribute\AsTwigFunction;
use Twig\Attribute\AsTwigTest;
use Twig\Extension\AttributeExtension;

/**
* Register an instance of AttributeExtension for each service using the
* PHP attributes to declare Twig callables.
*
* @author Jérôme Tamarelle <jerome@tamarelle.net>
*
* @internal
*/
final class AttributeExtensionPass implements CompilerPassInterface
{
private const TAG = 'twig.attribute_extension';

public static function autoconfigureFromAttribute(ChildDefinition $definition, AsTwigFilter|AsTwigFunction|AsTwigTest $attribute, \ReflectionMethod $reflector): void
{
$definition->addTag(self::TAG);

// The service must be tagged as a runtime to call non-static methods
if (!$reflector->isStatic()) {
$definition->addTag('twig.runtime');
}
}

public function process(ContainerBuilder $container): void
{
foreach ($container->findTaggedServiceIds(self::TAG, true) as $id => $tags) {
$container->register('.twig.extension.'.$id, AttributeExtension::class)
->setArguments([$container->getDefinition($id)->getClass()])
->addTag('twig.extension');
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace Symfony\Bundle\TwigBundle\DependencyInjection;

use Symfony\Bundle\TwigBundle\DependencyInjection\Compiler\AttributeExtensionPass;
use Symfony\Component\AssetMapper\AssetMapper;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Config\Resource\FileExistenceResource;
Expand All @@ -25,6 +26,9 @@
use Symfony\Component\Translation\LocaleSwitcher;
use Symfony\Component\Translation\Translator;
use Symfony\Contracts\Service\ResetInterface;
use Twig\Attribute\AsTwigFilter;
use Twig\Attribute\AsTwigFunction;
use Twig\Attribute\AsTwigTest;
use Twig\Environment;
use Twig\Extension\ExtensionInterface;
use Twig\Extension\RuntimeExtensionInterface;
Expand Down Expand Up @@ -179,6 +183,10 @@ public function load(array $configs, ContainerBuilder $container): void
$container->registerForAutoconfiguration(LoaderInterface::class)->addTag('twig.loader');
$container->registerForAutoconfiguration(RuntimeExtensionInterface::class)->addTag('twig.runtime');

$container->registerAttributeForAutoconfiguration(AsTwigFilter::class, AttributeExtensionPass::autoconfigureFromAttribute(...));
$container->registerAttributeForAutoconfiguration(AsTwigFunction::class, AttributeExtensionPass::autoconfigureFromAttribute(...));
$container->registerAttributeForAutoconfiguration(AsTwigTest::class, AttributeExtensionPass::autoconfigureFromAttribute(...));

Comment on lines +186 to +189
Copy link
Member Author

Choose a reason for hiding this comment

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

If the attribute class is not declared (Older Twig version), this will be skipped.

try {
$attributeReflector = new \ReflectionClass($attributeName);
} catch (\ReflectionException) {
continue;
}

if (false === $config['cache']) {
$container->removeDefinition('twig.template_cache_warmer');
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
<?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\TwigBundle\Tests\Functional;

use Symfony\Bundle\FrameworkBundle\FrameworkBundle;
use Symfony\Bundle\TwigBundle\Tests\TestCase;
use Symfony\Bundle\TwigBundle\TwigBundle;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpKernel\Kernel;
use Twig\Attribute\AsTwigFilter;
use Twig\Attribute\AsTwigFunction;
use Twig\Attribute\AsTwigTest;
use Twig\Environment;
use Twig\Error\RuntimeError;
use Twig\Extension\AttributeExtension;

class AttributeExtensionTest extends TestCase
{
public function testExtensionWithAttributes()
{
if (!class_exists(AttributeExtension::class)) {
self::markTestSkipped('Twig 3.21 is required.');
}

$kernel = new class('test', true) extends Kernel
{
public function registerBundles(): iterable
{
return [new FrameworkBundle(), new TwigBundle()];
}

public function registerContainerConfiguration(LoaderInterface $loader): void
{
$loader->load(static function (ContainerBuilder $container) {
$container->register(StaticExtensionWithAttributes::class, StaticExtensionWithAttributes::class)
->setAutoconfigured(true);
$container->register(RuntimeExtensionWithAttributes::class, RuntimeExtensionWithAttributes::class)
->setArguments(['prefix_'])
->setAutoconfigured(true);

$container->setAlias('twig_test', 'twig')->setPublic(true);
});
}

public function getProjectDir(): string
{
return sys_get_temp_dir().'/'.Kernel::VERSION.'/AttributeExtension';
}
};

$kernel->boot();

/** @var Environment $twig */
$twig = $kernel->getContainer()->get('twig_test');

self::assertInstanceOf(AttributeExtension::class, $twig->getExtension(StaticExtensionWithAttributes::class));
self::assertInstanceOf(AttributeExtension::class, $twig->getExtension(RuntimeExtensionWithAttributes::class));
self::assertInstanceOf(RuntimeExtensionWithAttributes::class, $twig->getRuntime(RuntimeExtensionWithAttributes::class));

self::expectException(RuntimeError::class);
$twig->getRuntime(StaticExtensionWithAttributes::class);
}

/**
* @before
* @after
*/
protected function deleteTempDir()
{
if (file_exists($dir = sys_get_temp_dir().'/'.Kernel::VERSION.'/AttributeExtension')) {
(new Filesystem())->remove($dir);
}
}
}

class StaticExtensionWithAttributes
{
#[AsTwigFilter('foo')]
public static function fooFilter(string $value): string
{
return $value;
}

#[AsTwigFunction('foo')]
public static function fooFunction(string $value): string
{
return $value;
}

#[AsTwigTest('foo')]
public static function fooTest(bool $value): bool
{
return $value;
}
}

class RuntimeExtensionWithAttributes
{
public function __construct(private bool $prefix)
{
}

#[AsTwigFilter('foo')]
#[AsTwigFunction('foo')]
public function prefix(string $value): string
{
return $this->prefix.$value;
}
}
2 changes: 2 additions & 0 deletions src/Symfony/Bundle/TwigBundle/TwigBundle.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace Symfony\Bundle\TwigBundle;

use Symfony\Bundle\TwigBundle\DependencyInjection\Compiler\AttributeExtensionPass;
use Symfony\Bundle\TwigBundle\DependencyInjection\Compiler\ExtensionPass;
use Symfony\Bundle\TwigBundle\DependencyInjection\Compiler\RuntimeLoaderPass;
use Symfony\Bundle\TwigBundle\DependencyInjection\Compiler\TwigEnvironmentPass;
Expand All @@ -33,6 +34,7 @@ public function build(ContainerBuilder $container): void

// ExtensionPass must be run before the FragmentRendererPass as it adds tags that are processed later
$container->addCompilerPass(new ExtensionPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION, 10);
$container->addCompilerPass(new AttributeExtensionPass());
$container->addCompilerPass(new TwigEnvironmentPass());
$container->addCompilerPass(new TwigLoaderPass());
$container->addCompilerPass(new RuntimeLoaderPass(), PassConfig::TYPE_BEFORE_REMOVING);
Expand Down
Loading