-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
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
Create attributes AsTwigFilter
, AsTwigFunction
and AsTwigTest
to ease extension development
#3916
base: 3.x
Are you sure you want to change the base?
Conversation
AsTwigFilter
, AsTwigFunction
and AsTwigTest
to improve extension development
AsTwigFilter
, AsTwigFunction
and AsTwigTest
to improve extension developmentAsTwigFilter
, AsTwigFunction
and AsTwigTest
to ease extension development
I'll rework the implementation after reading discussions on symfony/symfony#50016 |
d505321
to
e64a54b
Compare
src/Extension/AttributeExtension.php
Outdated
$parameters = $method->getParameters(); | ||
$needsEnvironment = isset($parameters[0]) && Environment::class === $parameters[0]->getType()?->getName(); | ||
$firstParam = $needsEnvironment ? 1 : 0; | ||
$needsContext = isset($parameters[$firstParam]) && 'context' === $parameters[$firstParam]->getName() && 'array' === $parameters[$firstParam]->getType()?->getName(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this special behavior of parameter named $context
needs to be documented on the attributes.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I added the doc and example in the attribute class header.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The Symfony serialize
filter accepts an array $context
as 3rd argument. This will not conflict but this means developers could have an unexpected behavior if they don't know about this special argument handling.
src/Extension/WithLastModified.php
Outdated
|
||
namespace Twig\Extension; | ||
|
||
interface WithLastModified |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is also a new feature required to detect when the class that defines attributes have been updated.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Alternatively, we can make passing a class name to the ExtensionSet, that will be scanned by it. This has slightly more impact on existing classes.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@stof I can't replace the modification date by a hash, the Environment::isFresh
relies on a date comparison between the ExtensionSet and the cache file mtime.
Lines 416 to 419 in aeeec9a
public function isTemplateFresh(string $name, int $time): bool | |
{ | |
return $this->extensionSet->getLastModified() <= $time && $this->getLoader()->isFresh($name, $time); | |
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LastModifiedAwareInterface
? What's the existing convention in Twig?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Renamed to ModificationAwareInterface
. The convention if to suffix with Interface
.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
With the last change, I removed this interface. ExtensionSet
is now aware of the extension classes that use attributes, and check their modification date as well.
* Identifies a class that uses PHP attributes to define filters, functions, or tests. | ||
*/ | ||
#[\Attribute(\Attribute::TARGET_CLASS)] | ||
class AsTwigExtension |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What is the purpose of this attribute ? I don't see (yet) how it is / will be used
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It's similar to Twig\Extension\RuntimeExtensionInterface
, it's a marker for classes that provide extension features, to be automatically tagged by Symfony dependency injection.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Given that extensions must implement the ExtensionInterface anyway, there is no need for a marker attribute. The Symfony dependency injection component is also able to perform auto-configuration based on implemented interfaces (and TwigBundle already does it for the Twig ExtensionInterface
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It's more a question of DX. It's more meaningful to use an attribute than an interface as a marker as the developer will use attributes in the class. Implementing an interface without method is a deviation from the interface system.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I've made this attribute mandatory to prevent any object from being passed by mistake. In practice, it will be mandatory anyway for Symfony autoconfiguration.
c627a38
to
4c1adc1
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ready for review @fabpot.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What is a bit strange is having one single instance of AttributeExtension be responsible for registering many runtimes. Maybe we should instead have one AttributeExtension per runtime? Then it might be easier to use this standalone :
addExtension(new AttributeExtension(new AttributeBasedRuntime)))
(and such runtimes could have a static factory to make this even easier to create). Note that this suggestion might be wrong as I didn't think of how runtimes should be made lazy-instantiated.
In the ExtensionSet
, extensions are identified by their class name. The same extension class cannot be registered multiple times with distinct configuration.
I updated this PR so that extension can be registered directly using any class name or object that have the #[AsTwigExtension]
attribute (the attribute becomes required).
$twig = new \Twig\Environment($loader);
- $twig->addExtension(new \Twig\Extension\AttributeExtension([
- ProjectExtension::class,
- ]));
+ $twig->addExtension(ProjectExtension::class);
$twig->addRuntimeLoader(new \Twig\RuntimeLoader\FactoryLoader([
ProjectExtension::class => function () use ($lipsumProvider) {
return new ProjectExtension($lipsumProvider);
},
]));
To use standalone (non-lazy-loaded):
$twig->addExtension(new ProjectExtension($lipsumProvider));
/** | ||
* @param ExtensionInterface|object|class-string $extension | ||
*/ | ||
public function addExtension(object|string $extension) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is a breaking change.
src/Extension/AttributeExtension.php
Outdated
} | ||
|
||
// Assign all at the end to avoid inconsistent state in case of exception | ||
$this->filters = $filters; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
you should do array_values
on those arrays instead of returning names as keys
src/Attribute/AsTwigTest.php
Outdated
* | ||
* If the first argument of the method has Twig\Environment type-hint, the test will receive the current environment. | ||
* If the next argument of the method is named $context and has array type-hint, the test will receive the current context. | ||
* The last argument of the method is the value to be tested, if any. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this is wrong. It is not the last argument. It is the following argument. A test can have as many arguments as you want after the value being tested, which become arguments in the Twig signature.
src/Attribute/AsTwigFilter.php
Outdated
public ?array $preservesSafety = null, | ||
|
||
/** | ||
* Set to true if the filter is deprecated. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
what is the string type about then ?
src/Attribute/AsTwigFilter.php
Outdated
public ?string $preEscape = null, | ||
|
||
/** | ||
* Preserves the safety of the value that the filter is applied to. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this misses the doc for the type of array values
throw new \LogicException(sprintf('Extension class "%s" must have the attribute "%s" in order to use attributes', is_string($objectOrClass) ? $objectOrClass : get_debug_type($objectOrClass), AsTwigExtension::class)); | ||
} | ||
|
||
foreach ($reflectionClass->getMethods() as $method) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
thinking about that, I'm wondering whether those asTwigFilter
, AsTwigFunction
and AsTwigTest
attributes should be read by that extension at all.
An alternative solution would be to have an extension in which you inject this list of test, filter and function metadata, and letting TwigBundle perform all this attribute reading at build-time instead.
This would even removed the need for the AsTwigExtension
attribute entirely (which would be quite confusing as the class having this attribute is not a twig extension but a twig runtime) because the autoconfiguration system is able to apply autoconfiguration based on method-level attributes already.
if ($extension instanceof ExtensionInterface) { | ||
$this->initExtension($extension); | ||
} else { | ||
$classes[] = $extension; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
making $this->extensions
contain a mix of extensions and of runtimes (but not all of them) looks weird to me
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
if this is a way to solve the case of getLastModified
, I'd rather add a way to make ExtensionSet aware of a separate list of runtimes needing to be checked (which would allow solving the case where we don't invalidate the cache today if you change the argument names in a runtime while it actually impacts the template compilation if you use named parameters in Twig, by making TwigBundle inject the name of all runtimes in the list).
…as attribute properties
…extension to be registered
One drawback to writing extensions at present is that the declaration of functions/filters/tests is not directly adjacent to the methods. It's worse for runtime extensions because they need to be in 2 different classes. See
SerializerExtension
andSerializerRuntime
as an example.By using attributes for filters, functions and tests definition, we can make writing extensions more expressive, and use reflection to detect particular options (
needs_environment
,needs_context
,is_variadic
).Example if we implemented the
formatDate
filter:Twig/extra/intl-extra/IntlExtension.php
Lines 392 to 395 in aeeec9a
By using the
AsTwigFilter
attribute, it is not necessary to create thegetFilters()
method. Theneeds_environment
option is detected from method signature. The name is still required as the method naming convention (camelCase) doesn't match with Twig naming convention (snake_case).This approach does not totally replace the current definition of extensions, which is still necessary for advanced needs. It does, however, make for more pleasant reading and writing.
This makes writing lazy-loaded runtime extension the easiest way to create Twig extension in Symfony: symfony/symfony#52748
Related to symfony/symfony#50016
Is there any need to cache the parsing of method attributes? They are only read at compile time, but that can have a performance impact during development or when using dynamic templates.